bcrypt vs crypto vs crypto-js vs jsrsasign vs node-forge vs node-rsa vs openpgp
Cryptographic Primitives and Security Protocols in JavaScript
bcryptcryptocrypto-jsjsrsasignnode-forgenode-rsaopenpgpSimilar Packages:

Cryptographic Primitives and Security Protocols in JavaScript

This comparison evaluates seven distinct cryptographic libraries available in the JavaScript ecosystem, ranging from Node.js core modules to specialized pure-JS implementations. crypto is the built-in Node.js module providing low-level access to OpenSSL bindings, serving as the foundation for server-side security. bcrypt is the industry standard library specifically for hashing passwords securely. crypto-js offers a broad collection of classic algorithms (like AES, SHA, MD5) implemented entirely in JavaScript, making it suitable for legacy browser support. node-forge is a comprehensive toolkit implementing TLS, X.509, and PKI standards in pure JavaScript, often used for client-side certificate generation. jsrsasign focuses heavily on RSA signing, verification, and JWT handling with extensive algorithm support. node-rsa provides a simplified interface specifically for RSA key generation and operations. Finally, openpgp is a dedicated implementation of the OpenPGP standard (RFC 4880) for end-to-end email and file encryption.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
bcrypt07,8041.11 MB38a year agoMIT
crypto034-139 years agoISC
crypto-js016,409487 kB2793 years agoMIT
jsrsasign03,369890 kB36a month agoMIT
node-forge05,3321.65 MB4656 months ago(BSD-3-Clause OR GPL-2.0)
node-rsa01,3801.44 MB14 months agoMIT
openpgp05,96617.4 MB364 months agoLGPL-3.0+

Cryptographic Primitives and Security Protocols in JavaScript: A Technical Deep Dive

Selecting the right cryptographic library in JavaScript is not just about picking an algorithm; it is about understanding the execution environment (Node.js vs. Browser), the specific security protocol required (PKI, PGP, or simple hashing), and the performance implications of native bindings versus pure JavaScript. The packages bcrypt, crypto, crypto-js, jsrsasign, node-forge, node-rsa, and openpgp each occupy distinct niches. Using the wrong tool can lead to build failures, security vulnerabilities, or unbearably slow application performance.

🔐 Password Hashing: The Specialized Case

Password hashing requires a specific approach: it must be slow enough to deter brute-force attacks and include automatic salting. General encryption libraries are unsafe for this purpose.

bcrypt is the definitive choice for Node.js backend password storage. It uses native C++ bindings to access the operating system's random number generator and performs computationally expensive key derivation.

// bcrypt: Hashing a password with a salt rounds cost of 10
const bcrypt = require('bcrypt');
const saltRounds = 10;
const password = 'mySecretPassword';

bcrypt.hash(password, saltRounds, function(err, hash) {
    // Store hash in database
});

// Verifying later
bcrypt.compare(password, hash, function(err, result) {
    // result == true if match
});

crypto, crypto-js, jsrsasign, node-forge, node-rsa, and openpgp are NOT suitable for password hashing. While they can technically run SHA-256, they lack the built-in adaptive cost factor and salt management strategies inherent to bcrypt. Attempting to build a password hasher using these tools often results in insecure implementations.

🖥️ Environment Constraints: Native vs. Pure JavaScript

The most critical architectural decision is whether your code runs on the server (Node.js) or the client (Browser).

crypto is a core Node.js module. It wraps OpenSSL, providing high-performance, hardware-accelerated cryptography. It is unavailable in browsers by default.

// crypto: Server-side SHA256 hashing
const crypto = require('crypto');

const hash = crypto.createHash('sha256')
  .update('some data to hash')
  .digest('hex');

console.log(hash);

crypto-js, jsrsasign, node-forge, node-rsa, and openpgp are written in pure JavaScript. They run everywhere but are generally slower than native bindings.

// crypto-js: Browser-compatible SHA256
const CryptoJS = require("crypto-js");

const hash = CryptoJS.SHA256("some data to hash").toString();

console.log(hash);

node-forge is unique because it implements TLS and X.509 logic in pure JS, allowing browsers to perform tasks usually reserved for servers, like generating Certificate Signing Requests (CSRs).

// node-forge: Generating a key pair in the browser
const forge = require('node-forge');
const keys = forge.pki.rsa.generateKeyPair({ bits: 2048 });

console.log(keys.publicKey.toString());

openpgp brings the complex OpenPGP standard to the browser, enabling end-to-end encryption without sending private keys to a server.

// openpgp: Encrypting a message in the browser
const openpgp = require('openpgp');

const encryptMessage = async () => {
  const message = await openpgp.createMessage({ text: 'Hello, World!' });
  const encrypted = await openpgp.encrypt({
    message,
    encryptionKeys: publicKeyArmored
  });
  return encrypted;
};

🔑 RSA Operations: Simplicity vs. Flexibility

When working with RSA encryption and signing, developers often face a trade-off between ease of use and algorithmic breadth.

node-rsa offers a clean, high-level API specifically for RSA. It abstracts away the complexity of padding schemes and key formats, making it ideal for simple encryption tasks.

// node-rsa: Simple RSA encryption
const NodeRSA = require('node-rsa');
const key = new NodeRSA({ b: 512 });

const text = 'Hello RSA';
const encrypted = key.encrypt(text, 'base64');
const decrypted = key.decrypt(encrypted, 'utf8');

console.log('Decrypted:', decrypted);

jsrsasign provides an extremely wide range of cryptographic algorithms, including many obscure curves and signature schemes not found in other libraries. It is powerful but verbose.

// jsrsasign: Signing data with RSA-SHA256
const KJUR = require('jsrsasign');
const privateKey = "-----BEGIN RSA PRIVATE KEY-----...";

const sig = new KJUR.crypto.Signature({ alg: 'SHA256withRSA' });
sig.init(privateKey);
sig.updateString('data to sign');
const signatureValue = sig.sign();

console.log(signatureValue);

crypto (Node.js) handles RSA via the crypto.privateEncrypt or crypto.sign methods but requires manual management of key formats (PEM vs DER) and padding constants.

// crypto: Server-side RSA signing
const crypto = require('crypto');
const fs = require('fs');

const privateKey = fs.readFileSync('private_key.pem');
const sign = crypto.createSign('SHA256');
sign.update('data to sign');
sign.end();

const signature = sign.sign(privateKey, 'hex');
console.log(signature);

node-forge allows for low-level manipulation of RSA primitives, often used when you need to construct custom PKCS#1 structures manually.

// node-forge: RSA Encryption
const forge = require('node-forge');
const publicKey = forge.pki.publicKeyFromPem(pemString);
const encrypted = publicKey.encrypt('Hello', 'RSA-OAEP');

console.log(forge.util.encode64(encrypted));

bcrypt, crypto-js, and openpgp do not provide direct, general-purpose RSA encryption APIs in the same manner. openpgp uses RSA internally but exposes it only through the PGP protocol envelope.

📜 Standards Compliance: PKI and PGP

Some projects require strict adherence to specific internet standards like X.509 (for certificates) or OpenPGP (for email encryption).

node-forge is the most complete pure-JS implementation of X.509. It allows you to create Certificate Authorities (CAs), sign certificates, and parse ASN.1 structures entirely in JavaScript.

// node-forge: Creating a self-signed X.509 certificate
const forge = require('node-forge');
const keys = forge.pki.rsa.generateKeyPair(2048);
const cert = forge.pki.createCertificate();

cert.publicKey = keys.publicKey;
cert.serialNumber = '01';
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.setSubject([{ name: 'commonName', value: 'example.com' }]);
cert.setIssuer([{ name: 'commonName', value: 'example.com' }]);
cert.sign(keys.privateKey, forge.md.sha256.create());

const pem = forge.pki.certificateToPem(cert);
console.log(pem);

openpgp is the only library here that implements the full OpenPGP standard (RFC 4880). It handles key rings, compression, armor encoding, and multi-recipient encryption.

// openpgp: Decrypting a PGP message
const openpgp = require('openpgp');

const decryptMessage = async (encryptedData, privateKeyArmored, passphrase) => {
  const privateKey = await openpgp.readPrivateKey({ armoredKey: privateKeyArmored });
  const message = await openpgp.readMessage({ armoredMessage: encryptedData });
  
  const { data: decrypted } = await openpgp.decrypt({
    message,
    decryptionKeys: privateKey,
    passphrase
  });
  
  return decrypted;
};

jsrsasign supports X.509 certificate parsing and verification but lacks the full certificate generation and management workflow found in node-forge.

// jsrsasign: Parsing an X.509 certificate
const X509 = require('jsrsasign').X509;
const certPem = "-----BEGIN CERTIFICATE-----...";
const x509 = new X509();
x509.readCertPEM(certPem);

console.log(x509.getSubjectString());

crypto, bcrypt, crypto-js, and node-rsa do not support X.509 or PGP standards natively. They operate at the primitive level (bytes and keys) rather than the protocol level.

⚠️ Deprecation and Maintenance Warning

When evaluating these packages, maintenance status is a security factor.

node-rsa has seen significantly reduced activity in recent years. While it still functions for basic RSA tasks, new projects requiring robust, long-term security should consider using the native crypto module in Node.js or node-forge for browser-based RSA needs, as these are more actively maintained and audited.

bcrypt relies on node-gyp for compilation. In modern serverless or edge computing environments (like Cloudflare Workers or Vercel Edge Functions) that do not support native C++ addons, bcrypt will fail to build. In those specific edge cases, developers must switch to pure JS alternatives like bcryptjs (a fork without native bindings) or rely on platform-provided crypto APIs, though bcryptjs is not part of this specific comparison list.

📊 Summary of Capabilities

Featurebcryptcryptocrypto-jsjsrsasignnode-forgenode-rsaopenpgp
Primary UsePassword HashingGeneral CryptoLegacy/Simple CryptoJWT & SignaturesPKI & X.509Simple RSAPGP Encryption
EnvironmentNode.js OnlyNode.js OnlyAny (Pure JS)Any (Pure JS)Any (Pure JS)Any (Pure JS)Any (Pure JS)
Password Hash✅ Native❌❌❌❌❌❌
RSA Encrypt❌✅❌✅✅✅(Internal)
X.509 Certs❌❌❌(Parse Only)✅ Full❌❌
PGP Standard❌❌❌❌❌❌✅ Full
PerformanceHigh (Native)Highest (Native)MediumLowLowMediumLow

💡 Architectural Recommendation

For backend Node.js services, always default to the built-in crypto module for encryption and signing, and bcrypt for passwords. This combination offers the best performance and security posture by leveraging the underlying OS security primitives.

For frontend applications requiring encryption, avoid rolling your own crypto. If you need simple data obfuscation or compatibility with old systems, crypto-js is sufficient. If you are building a secure messaging app or email client, openpgp is the only standard-compliant choice. For advanced browser-based identity features like generating client certificates, node-forge is the industry standard.

Avoid node-rsa for new high-security projects due to maintenance concerns, preferring node-forge or jsrsasign for pure-JS RSA needs. Finally, never attempt to use general encryption libraries like crypto-js or openpgp for password storage; stick to bcrypt or modern Argon2 alternatives.

How to Choose: bcrypt vs crypto vs crypto-js vs jsrsasign vs node-forge vs node-rsa vs openpgp

  • bcrypt:

    Choose bcrypt exclusively for hashing user passwords in Node.js environments. It automatically handles salt generation and uses an adaptive cost factor to resist brute-force attacks. Do not use it for general encryption or in the browser due to its reliance on native C++ bindings which cause performance issues and build complexities in client-side bundles.

  • crypto:

    Choose the built-in crypto module for all server-side Node.js projects requiring high-performance encryption, hashing, or random number generation. It is the most secure and efficient option for backend logic because it leverages OpenSSL directly. Avoid using it in frontend code as it is not available in browsers without heavy polyfills, which are generally discouraged for security-critical operations.

  • crypto-js:

    Choose crypto-js if you need to support older browsers that lack the Web Crypto API or require a simple, unified API for classic algorithms like AES, SHA-3, or HMAC in a pure JavaScript environment. It is ideal for lightweight obfuscation or interoperability with legacy systems. However, avoid it for high-security requirements in modern apps where the native window.crypto subarray is preferred for better performance and security guarantees.

  • jsrsasign:

    Choose jsrsasign when your primary requirement is robust RSA signature generation, verification, or JWT (JSON Web Token) handling with support for a vast array of algorithms (including exotic curves). It is particularly useful in environments where you need to sign data using private keys stored in various formats (PEM, JWK) without a backend. Be aware that its API is extensive and can be verbose compared to more modern, focused libraries.

  • node-forge:

    Choose node-forge when you need to perform complex PKI operations, such as generating X.509 certificates, handling CSR (Certificate Signing Requests), or implementing TLS handshakes entirely in JavaScript. It is the go-to solution for browser-based tools that need to create self-signed certificates or manage digital identities client-side. Avoid it for simple hashing or encryption tasks where lighter libraries like crypto-js or native APIs would suffice due to its larger bundle size.

  • node-rsa:

    Choose node-rsa if you need a straightforward, dedicated library for RSA key generation, encryption, and decryption with a clean, promise-friendly API. It simplifies common RSA tasks that can be verbose in the native crypto module. However, note that it is less actively maintained than other options and lacks the broad algorithmic support of jsrsasign or the PKI features of node-forge, making it best for simple, specific RSA use cases.

  • openpgp:

    Choose openpgp (openpgpjs) when you need to implement end-to-end encryption following the OpenPGP standard (RFC 4880), typically for secure email, file encryption, or messaging apps. It is the only library in this list that fully supports the PGP ecosystem, including key rings, armor formatting, and compression. Do not use it for general-purpose AES encryption if you do not need PGP compatibility, as it introduces unnecessary complexity and overhead.

README for bcrypt

node.bcrypt.js

ci

Build Status

A library to help you hash passwords.

You can read about bcrypt in Wikipedia as well as in the following article: How To Safely Store A Password

If You Are Submitting Bugs or Issues

Please verify that the NodeJS version you are using is a stable version; Unstable versions are currently not supported and issues created while using an unstable version will be closed.

If you are on a stable version of NodeJS, please provide a sufficient code snippet or log files for installation issues. The code snippet does not require you to include confidential information. However, it must provide enough information so the problem can be replicable, or it may be closed without an explanation.

Version Compatibility

Please upgrade to atleast v5.0.0 to avoid security issues mentioned below.

Node VersionBcrypt Version
0.4<= 0.4
0.6, 0.8, 0.10>= 0.5
0.11>= 0.8
4<= 2.1.0
8>= 1.0.3 < 4.0.0
10, 11>= 3
12 onwards>= 3.0.6

node-gyp only works with stable/released versions of node. Since the bcrypt module uses node-gyp to build and install, you'll need a stable version of node to use bcrypt. If you do not, you'll likely see an error that starts with:

gyp ERR! stack Error: "pre" versions of node cannot be installed, use the --nodedir flag instead

Security Issues And Concerns

Per bcrypt implementation, only the first 72 bytes of a string are used. Any extra bytes are ignored when matching passwords. Note that this is not the first 72 characters. It is possible for a string to contain less than 72 characters, while taking up more than 72 bytes (e.g. a UTF-8 encoded string containing emojis). If a string is provided, it will be encoded using UTF-8.

As should be the case with any security tool, anyone using this library should scrutinise it. If you find or suspect an issue with the code, please bring it to the maintainers' attention. We will spend some time ensuring that this library is as secure as possible.

Here is a list of BCrypt-related security issues/concerns that have come up over the years.

  • An issue with passwords was found with a version of the Blowfish algorithm developed for John the Ripper. This is not present in the OpenBSD version and is thus not a problem for this module. HT zooko.
  • Versions < 5.0.0 suffer from bcrypt wrap-around bug and will truncate passwords >= 255 characters leading to severely weakened passwords. Please upgrade at earliest. See this wiki page for more details.
  • Versions < 5.0.0 do not handle NUL characters inside passwords properly leading to all subsequent characters being dropped and thus resulting in severely weakened passwords. Please upgrade at earliest. See this wiki page for more details.

Compatibility Note

This library supports $2a$ and $2b$ prefix bcrypt hashes. $2x$ and $2y$ hashes are specific to bcrypt implementation developed for John the Ripper. In theory, they should be compatible with $2b$ prefix.

Compatibility with hashes generated by other languages is not 100% guaranteed due to difference in character encodings. However, it should not be an issue for most cases.

Migrating from v1.0.x

Hashes generated in earlier version of bcrypt remain 100% supported in v2.x.x and later versions. In most cases, the migration should be a bump in the package.json.

Hashes generated in v2.x.x using the defaults parameters will not work in earlier versions.

Dependencies

  • NodeJS
  • node-gyp
  • Please check the dependencies for this tool at: https://github.com/nodejs/node-gyp
  • Windows users will need the options for c# and c++ installed with their visual studio instance.
  • Python 2.x/3.x
  • OpenSSL - This is only required to build the bcrypt project if you are using versions <= 0.7.7. Otherwise, we're using the builtin node crypto bindings for seed data (which use the same OpenSSL code paths we were, but don't have the external dependency).

Install via NPM

npm install bcrypt

Note: OS X users using Xcode 4.3.1 or above may need to run the following command in their terminal prior to installing if errors occur regarding xcodebuild: sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer

Pre-built binaries for various NodeJS versions are made available on a best-effort basis.

Only the current stable and supported LTS releases are actively tested against.

There may be an interval between the release of the module and the availabilty of the compiled modules.

Currently, we have pre-built binaries that support the following platforms:

  1. Windows x32 and x64
  2. Linux x64 (GlibC and musl)
  3. macOS

If you face an error like this:

node-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v48-linux-x64.tar.gz

make sure you have the appropriate dependencies installed and configured for your platform. You can find installation instructions for the dependencies for some common platforms in this page.

Usage

async (recommended)

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';

To hash a password:

Technique 1 (generate a salt and hash on separate function calls):

bcrypt.genSalt(saltRounds, function(err, salt) {
    bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
        // Store hash in your password DB.
    });
});

Technique 2 (auto-gen a salt and hash):

bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
    // Store hash in your password DB.
});

Note that both techniques achieve the same end-result.

To check a password:

// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
    // result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
    // result == false
});

A Note on Timing Attacks

with promises

bcrypt uses whatever Promise implementation is available in global.Promise. NodeJS >= 0.12 has a native Promise implementation built in. However, this should work in any Promises/A+ compliant implementation.

Async methods that accept a callback, return a Promise when callback is not specified if Promise support is available.

bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) {
    // Store hash in your password DB.
});
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash).then(function(result) {
    // result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash).then(function(result) {
    // result == false
});

This is also compatible with async/await

async function checkUser(username, password) {
    //... fetch user from a db etc.

    const match = await bcrypt.compare(password, user.passwordHash);

    if(match) {
        //login
    }

    //...
}

ESM import

import bcrypt from "bcrypt";

// later
await bcrypt.compare(password, hash);

sync

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';

To hash a password:

Technique 1 (generate a salt and hash on separate function calls):

const salt = bcrypt.genSaltSync(saltRounds);
const hash = bcrypt.hashSync(myPlaintextPassword, salt);
// Store hash in your password DB.

Technique 2 (auto-gen a salt and hash):

const hash = bcrypt.hashSync(myPlaintextPassword, saltRounds);
// Store hash in your password DB.

As with async, both techniques achieve the same end-result.

To check a password:

// Load hash from your password DB.
bcrypt.compareSync(myPlaintextPassword, hash); // true
bcrypt.compareSync(someOtherPlaintextPassword, hash); // false

A Note on Timing Attacks

Why is async mode recommended over sync mode?

We recommend using async API if you use bcrypt on a server. Bcrypt hashing is CPU intensive which will cause the sync APIs to block the event loop and prevent your application from servicing any inbound requests or events. The async version uses a thread pool which does not block the main event loop.

API

BCrypt.

  • genSaltSync(rounds, minor)
    • rounds - [OPTIONAL] - the cost of processing the data. (default - 10)
    • minor - [OPTIONAL] - minor version of bcrypt to use. (default - b)
  • genSalt(rounds, minor, cb)
    • rounds - [OPTIONAL] - the cost of processing the data. (default - 10)
    • minor - [OPTIONAL] - minor version of bcrypt to use. (default - b)
    • cb - [OPTIONAL] - a callback to be fired once the salt has been generated. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.
      • err - First parameter to the callback detailing any errors.
      • salt - Second parameter to the callback providing the generated salt.
  • hashSync(data, salt)
    • data - [REQUIRED] - the data to be encrypted.
    • salt - [REQUIRED] - the salt to be used to hash the password. if specified as a number then a salt will be generated with the specified number of rounds and used (see example under Usage).
  • hash(data, salt, cb)
    • data - [REQUIRED] - the data to be encrypted.
    • salt - [REQUIRED] - the salt to be used to hash the password. if specified as a number then a salt will be generated with the specified number of rounds and used (see example under Usage).
    • cb - [OPTIONAL] - a callback to be fired once the data has been encrypted. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.
      • err - First parameter to the callback detailing any errors.
      • encrypted - Second parameter to the callback providing the encrypted form.
  • compareSync(data, encrypted)
    • data - [REQUIRED] - data to compare.
    • encrypted - [REQUIRED] - data to be compared to.
  • compare(data, encrypted, cb)
    • data - [REQUIRED] - data to compare.
    • encrypted - [REQUIRED] - data to be compared to.
    • cb - [OPTIONAL] - a callback to be fired once the data has been compared. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.
      • err - First parameter to the callback detailing any errors.
      • same - Second parameter to the callback providing whether the data and encrypted forms match [true | false].
  • getRounds(encrypted) - return the number of rounds used to encrypt a given hash
    • encrypted - [REQUIRED] - hash from which the number of rounds used should be extracted.

A Note on Rounds

A note about the cost: when you are hashing your data, the module will go through a series of rounds to give you a secure hash. The value you submit is not just the number of rounds the module will go through to hash your data. The module will use the value you enter and go through 2^rounds hashing iterations.

From @garthk, on a 2GHz core you can roughly expect:

rounds=8 : ~40 hashes/sec
rounds=9 : ~20 hashes/sec
rounds=10: ~10 hashes/sec
rounds=11: ~5  hashes/sec
rounds=12: 2-3 hashes/sec
rounds=13: ~1 sec/hash
rounds=14: ~1.5 sec/hash
rounds=15: ~3 sec/hash
rounds=25: ~1 hour/hash
rounds=31: 2-3 days/hash

A Note on Timing Attacks

Because it's come up multiple times in this project and other bcrypt projects, it needs to be said. The bcrypt library is not susceptible to timing attacks. From codahale/bcrypt-ruby#42:

One of the desired properties of a cryptographic hash function is preimage attack resistance, which means there is no shortcut for generating a message which, when hashed, produces a specific digest.

A great thread on this, in much more detail can be found @ codahale/bcrypt-ruby#43

If you're unfamiliar with timing attacks and want to learn more you can find a great writeup @ A Lesson In Timing Attacks

However, timing attacks are real. And the comparison function is not time safe. That means that it may exit the function early in the comparison process. Timing attacks happen because of the above. We don't need to be careful that an attacker will learn anything, and our comparison function provides a comparison of hashes. It is a utility to the overall purpose of the library. If you end up using it for something else, we cannot guarantee the security of the comparator. Keep that in mind as you use the library.

Hash Info

The characters that comprise the resultant hash are ./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$.

Resultant hashes will be 60 characters long and they will include the salt among other parameters, as follows:

$[algorithm]$[cost]$[salt][hash]

  • 2 chars hash algorithm identifier prefix. "$2a$" or "$2b$" indicates BCrypt
  • Cost-factor (n). Represents the exponent used to determine how many iterations 2^n
  • 16-byte (128-bit) salt, base64 encoded to 22 characters
  • 24-byte (192-bit) hash, base64 encoded to 31 characters

Example:

$2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |                     |
 |  |  |                     hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |
 |  |  salt = nOUIs5kJ7naTuTFkBy1veu
 |  |
 |  cost-factor => 10 = 2^10 rounds
 |
 hash-algorithm identifier => 2b = BCrypt

Testing

If you create a pull request, tests better pass :)

npm install
npm test

Credits

The code for this comes from a few sources:

Contributors

License

Unless stated elsewhere, file headers or otherwise, the license as stated in the LICENSE file.