bcrypt, crypto-js, pbkdf2, and scrypt-js are JavaScript libraries used for cryptographic operations, particularly password hashing and key derivation. bcrypt is a dedicated password-hashing library optimized for server-side use with built-in salting and adaptive cost. crypto-js is a general-purpose cryptography suite that supports various algorithms including PBKDF2, designed primarily for browser environments. pbkdf2 provides a promise-based wrapper around Node.js's native PBKDF2 implementation, making it suitable only for server-side applications. scrypt-js implements the memory-hard scrypt algorithm in pure JavaScript, enabling secure key derivation in both browsers and Node.js without native dependencies. These packages serve overlapping but distinct roles in securing user credentials and sensitive data across different runtime environments.
When building applications that handle user authentication, choosing the right password hashing strategy is critical. The packages bcrypt, crypto-js, pbkdf2, and scrypt-js all offer cryptographic capabilities—but they differ significantly in purpose, security guarantees, browser compatibility, and suitability for frontend use. Let’s break down what each does, where it works, and when to use it.
bcrypt is a dedicated password-hashing library built around the Blowfish cipher. It includes built-in salting and is specifically designed to be slow and resistant to GPU-based cracking attacks.
// bcrypt (Node.js only)
import bcrypt from 'bcrypt';
const saltRounds = 12;
const hashed = await bcrypt.hash('myPassword123', saltRounds);
const isValid = await bcrypt.compare('myPassword123', hashed);
crypto-js is a general-purpose cryptography library supporting many algorithms (AES, SHA, HMAC, etc.), including basic PBKDF2. However, it does not implement bcrypt or scrypt, and its PBKDF2 uses synchronous operations that can block the UI.
// crypto-js (browser-compatible)
import CryptoJS from 'crypto-js';
const salt = CryptoJS.lib.WordArray.random(128/8);
const key = CryptoJS.PBKDF2('password', salt, {
keySize: 256/32,
iterations: 1000
});
// Note: No built-in compare function; you must handle encoding/salting manually
pbkdf2 is a thin wrapper around Node.js’s native crypto.pbkdf2 and crypto.pbkdf2Sync. It provides promise-based APIs but only works in Node.js—it will fail in browsers unless polyfilled.
// pbkdf2 (Node.js only)
import { pbkdf2 } from 'pbkdf2';
const salt = crypto.randomBytes(16);
const key = await pbkdf2('password', salt, 100000, 32, 'sha256');
// Returns Buffer; no helper for comparison or storage format
scrypt-js is a pure-JavaScript implementation of the scrypt key derivation function, designed to be memory-hard and resistant to hardware-accelerated attacks. It works in both browsers and Node.js and supports async operations.
// scrypt-js (browser & Node.js)
import { scrypt, scryptSync } from 'scrypt-js';
const salt = new Uint8Array(32);
crypto.getRandomValues(salt); // in browser
const N = 16384; // CPU/memory cost
const r = 8; // block size
const p = 1; // parallelization
const key = await scrypt(
new TextEncoder().encode('password'),
salt,
N, r, p,
32
);
// Returns Uint8Array; requires manual serialization
This is a major differentiator:
bcrypt: Only works in Node.js. The npm package relies on native C++ bindings via node-gyp. There are browser-compatible forks (like bcryptjs), but the official bcrypt package will not work in the browser.crypto-js: Works everywhere — designed for browsers first, also runs in Node.js.pbkdf2: Node.js only. It wraps Node’s built-in crypto module, which isn’t available in browsers without polyfills.scrypt-js: Pure JavaScript, so it runs in both browsers and Node.js without dependencies.⚠️ If you’re building a frontend app that needs to hash passwords in the browser (e.g., client-side encryption before sending to server), only
crypto-jsandscrypt-jsare viable. But note: hashing passwords in the browser is rarely recommended—more on that below.
All four support configurable work factors, but their resistance to real-world attacks varies:
bcrypt uses a logarithmic cost factor (e.g., 12 = 2^12 rounds). It’s been battle-tested for over 20 years and is widely trusted.scrypt-js uses three parameters (N, r, p) to control CPU, memory, and parallelism. Its memory-hard design makes it harder to crack with ASICs than bcrypt or PBKDF2.pbkdf2 and crypto-js’s PBKDF2 rely solely on iteration count. While secure with high iterations (≥100,000), they’re more vulnerable to GPU cracking than bcrypt or scrypt because they’re not memory-hard.None of these libraries provide built-in protection against timing attacks during comparison—you must use constant-time comparison if comparing hashes manually. Fortunately, bcrypt.compare() handles this internally.
// Safe: bcrypt handles timing-safe compare
const match = await bcrypt.compare(input, storedHash);
// Risky: Manual string comparison (vulnerable to timing attacks)
if (hash1 === hash2) { /* don't do this */ }
bcrypt wins for simplicity in Node.js: automatic salt generation, one-line hash/verify, and safe defaults.scrypt-js gives full control but requires manual handling of salts, encoding, and storage format.crypto-js offers convenience methods but lacks password-hashing-specific helpers (e.g., no compare function).pbkdf2 is minimal—just a promisified wrapper. You manage everything else.Generally, no. Password hashing should happen on the server for these reasons:
The only valid frontend use case is client-side encryption (e.g., zero-knowledge apps like password managers), where the password derives a key to encrypt data before it leaves the device. In those cases, scrypt-js is preferred due to its memory-hard properties and async support.
| Scenario | Recommended Package |
|---|---|
| Standard server-side auth (Node.js) | bcrypt |
| Zero-knowledge encryption in browser | scrypt-js |
| Need PBKDF2 in Node.js with promises | pbkdf2 |
| General crypto (AES, SHA, etc.) in browser | crypto-js |
| Frontend password hashing for auth | Don’t do it |
bcrypt on the server. It’s simple, secure, and industry-standard.scrypt-js to derive keys—its memory-hard design raises the cost of brute-force attacks.crypto-js for password hashing unless you have no alternative; its PBKDF2 implementation is synchronous and lacks ergonomic safety features.pbkdf2 in the browser—it won’t work without heavy polyfilling, and better options exist.Remember: the strongest hash won’t save you if your architecture is flawed. Always use HTTPS, store salts properly, and never roll your own crypto primitives.
Choose bcrypt if you're building a standard server-side authentication system in Node.js and need a battle-tested, easy-to-use password hashing solution with automatic salt management and timing-safe comparison. It’s the go-to choice for most web applications that handle user logins, but note it does not work in browsers due to native C++ dependencies.
Choose crypto-js if you need general-purpose cryptography (like AES encryption or SHA hashing) in the browser and only require basic PBKDF2 for key derivation. Avoid it for primary password hashing in authentication flows—it lacks built-in helpers for safe password handling, uses synchronous operations that can block the UI, and doesn’t implement stronger algorithms like bcrypt or scrypt.
Choose pbkdf2 if you're working exclusively in Node.js and prefer a lightweight, promise-based interface to the native PBKDF2 function without extra dependencies. It’s suitable when you need fine-grained control over key derivation parameters but requires manual handling of salts, encoding, and comparison logic—making it less convenient than bcrypt for typical auth use cases.
Choose scrypt-js if you need memory-hard password-based key derivation that works reliably in both browsers and Node.js, such as in zero-knowledge applications where data is encrypted client-side before transmission. Its async support prevents UI blocking, and scrypt’s resistance to hardware-accelerated attacks offers stronger security than PBKDF2—though it demands more careful parameter tuning and manual salt management.
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
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.
Please upgrade to atleast v5.0.0 to avoid security issues mentioned below.
| Node Version | Bcrypt 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
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.
< 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.< 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.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.
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.
node-gypOpenSSL - 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).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:
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.
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
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.
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
// result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
// result == false
});
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
}
//...
}
import bcrypt from "bcrypt";
// later
await bcrypt.compare(password, hash);
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
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.
// Load hash from your password DB.
bcrypt.compareSync(myPlaintextPassword, hash); // true
bcrypt.compareSync(someOtherPlaintextPassword, hash); // false
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.
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 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
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.
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]
"$2a$" or "$2b$" indicates BCryptExample:
$2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | | |
| | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | |
| | salt = nOUIs5kJ7naTuTFkBy1veu
| |
| cost-factor => 10 = 2^10 rounds
|
hash-algorithm identifier => 2b = BCrypt
If you create a pull request, tests better pass :)
npm install
npm test
The code for this comes from a few sources:
Unless stated elsewhere, file headers or otherwise, the license as stated in the LICENSE file.