crypto-js vs pbkdf2 vs bcrypt vs scrypt-js
Secure Password Hashing and Key Derivation in JavaScript
crypto-jspbkdf2bcryptscrypt-jsSimilar Packages:
Secure Password Hashing and Key Derivation in JavaScript

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.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
crypto-js7,297,70516,369487 kB2752 years agoMIT
pbkdf25,949,13519942.5 kB33 months agoMIT
bcrypt2,169,2967,7541.11 MB268 months agoMIT
scrypt-js709,842145-126 years agoMIT

Secure Password Hashing in JavaScript: bcrypt vs crypto-js vs pbkdf2 vs scrypt-js

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.

🔐 Core Purpose: What Each Package Is Designed For

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

🖥️ Environment Compatibility: Browser vs Node.js

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-js and scrypt-js are viable. But note: hashing passwords in the browser is rarely recommended—more on that below.

🛡️ Security Model: Adaptive Cost and Side-Channel Resistance

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 */ }

🧩 Developer Experience: Ease of Use and Built-in Features

  • 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.

🚫 Critical Architectural Guidance: Should You Hash in the Frontend?

Generally, no. Password hashing should happen on the server for these reasons:

  1. Secret exposure: If you hash in the browser, the resulting hash becomes the effective password. If intercepted, it grants access just like the original password.
  2. No added security: Without TLS, an attacker can still steal credentials. With TLS, server-side hashing is sufficient.
  3. Performance: Browsers vary in CPU power. A strong hash might freeze low-end devices.

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.

📊 When to Use Which Package

ScenarioRecommended Package
Standard server-side auth (Node.js)bcrypt
Zero-knowledge encryption in browserscrypt-js
Need PBKDF2 in Node.js with promisespbkdf2
General crypto (AES, SHA, etc.) in browsercrypto-js
Frontend password hashing for authDon’t do it

💡 Final Recommendations

  • For most web apps, use bcrypt on the server. It’s simple, secure, and industry-standard.
  • If you’re building a privacy-focused app that encrypts data in the browser (e.g., notes, files), use scrypt-js to derive keys—its memory-hard design raises the cost of brute-force attacks.
  • Avoid crypto-js for password hashing unless you have no alternative; its PBKDF2 implementation is synchronous and lacks ergonomic safety features.
  • Never use 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.

How to Choose: crypto-js vs pbkdf2 vs bcrypt vs scrypt-js
  • crypto-js:

    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.

  • pbkdf2:

    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.

  • bcrypt:

    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.

  • scrypt-js:

    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.

README for crypto-js

crypto-js

JavaScript library of crypto standards.

Discontinued

Active development of CryptoJS has been discontinued. This library is no longer maintained.

Nowadays, NodeJS and modern browsers have a native Crypto module. The latest version of CryptoJS already uses the native Crypto module for random number generation, since Math.random() is not crypto-safe. Further development of CryptoJS would result in it only being a wrapper of native Crypto. Therefore, development and maintenance has been discontinued, it is time to go for the native crypto module.

Node.js (Install)

Requirements:

  • Node.js
  • npm (Node.js package manager)
npm install crypto-js

Usage

ES6 import for typical API call signing use case:

import sha256 from 'crypto-js/sha256';
import hmacSHA512 from 'crypto-js/hmac-sha512';
import Base64 from 'crypto-js/enc-base64';

const message, nonce, path, privateKey; // ...
const hashDigest = sha256(nonce + message);
const hmacDigest = Base64.stringify(hmacSHA512(path + hashDigest, privateKey));

Modular include:

var AES = require("crypto-js/aes");
var SHA256 = require("crypto-js/sha256");
...
console.log(SHA256("Message"));

Including all libraries, for access to extra methods:

var CryptoJS = require("crypto-js");
console.log(CryptoJS.HmacSHA1("Message", "Key"));

Client (browser)

Requirements:

  • Node.js
  • Bower (package manager for frontend)
bower install crypto-js

Usage

Modular include:

require.config({
    packages: [
        {
            name: 'crypto-js',
            location: 'path-to/bower_components/crypto-js',
            main: 'index'
        }
    ]
});

require(["crypto-js/aes", "crypto-js/sha256"], function (AES, SHA256) {
    console.log(SHA256("Message"));
});

Including all libraries, for access to extra methods:

// Above-mentioned will work or use this simple form
require.config({
    paths: {
        'crypto-js': 'path-to/bower_components/crypto-js/crypto-js'
    }
});

require(["crypto-js"], function (CryptoJS) {
    console.log(CryptoJS.HmacSHA1("Message", "Key"));
});

Usage without RequireJS

<script type="text/javascript" src="path-to/bower_components/crypto-js/crypto-js.js"></script>
<script type="text/javascript">
    var encrypted = CryptoJS.AES(...);
    var encrypted = CryptoJS.SHA256(...);
</script>

API

See: https://cryptojs.gitbook.io/docs/

AES Encryption

Plain text encryption

var CryptoJS = require("crypto-js");

// Encrypt
var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123').toString();

// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var originalText = bytes.toString(CryptoJS.enc.Utf8);

console.log(originalText); // 'my message'

Object encryption

var CryptoJS = require("crypto-js");

var data = [{id: 1}, {id: 2}]

// Encrypt
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123').toString();

// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));

console.log(decryptedData); // [{id: 1}, {id: 2}]

List of modules

  • crypto-js/core
  • crypto-js/x64-core
  • crypto-js/lib-typedarrays

  • crypto-js/md5
  • crypto-js/sha1
  • crypto-js/sha256
  • crypto-js/sha224
  • crypto-js/sha512
  • crypto-js/sha384
  • crypto-js/sha3
  • crypto-js/ripemd160

  • crypto-js/hmac-md5
  • crypto-js/hmac-sha1
  • crypto-js/hmac-sha256
  • crypto-js/hmac-sha224
  • crypto-js/hmac-sha512
  • crypto-js/hmac-sha384
  • crypto-js/hmac-sha3
  • crypto-js/hmac-ripemd160

  • crypto-js/pbkdf2

  • crypto-js/aes
  • crypto-js/tripledes
  • crypto-js/rc4
  • crypto-js/rabbit
  • crypto-js/rabbit-legacy
  • crypto-js/evpkdf

  • crypto-js/format-openssl
  • crypto-js/format-hex

  • crypto-js/enc-latin1
  • crypto-js/enc-utf8
  • crypto-js/enc-hex
  • crypto-js/enc-utf16
  • crypto-js/enc-base64

  • crypto-js/mode-cfb
  • crypto-js/mode-ctr
  • crypto-js/mode-ctr-gladman
  • crypto-js/mode-ofb
  • crypto-js/mode-ecb

  • crypto-js/pad-pkcs7
  • crypto-js/pad-ansix923
  • crypto-js/pad-iso10126
  • crypto-js/pad-iso97971
  • crypto-js/pad-zeropadding
  • crypto-js/pad-nopadding

Release notes

4.2.0

Change default hash algorithm and iteration's for PBKDF2 to prevent weak security by using the default configuration.

Custom KDF Hasher

Blowfish support

4.1.1

Fix module order in bundled release.

Include the browser field in the released package.json.

4.1.0

Added url safe variant of base64 encoding. 357

Avoid webpack to add crypto-browser package. 364

4.0.0

This is an update including breaking changes for some environments.

In this version Math.random() has been replaced by the random methods of the native crypto module.

For this reason CryptoJS might not run in some JavaScript environments without native crypto module. Such as IE 10 or before or React Native.

3.3.0

Rollback, 3.3.0 is the same as 3.1.9-1.

The move of using native secure crypto module will be shifted to a new 4.x.x version. As it is a breaking change the impact is too big for a minor release.

3.2.1

The usage of the native crypto module has been fixed. The import and access of the native crypto module has been improved.

3.2.0

In this version Math.random() has been replaced by the random methods of the native crypto module.

For this reason CryptoJS might does not run in some JavaScript environments without native crypto module. Such as IE 10 or before.

If it's absolute required to run CryptoJS in such an environment, stay with 3.1.x version. Encrypting and decrypting stays compatible. But keep in mind 3.1.x versions still use Math.random() which is cryptographically not secure, as it's not random enough.

This version came along with CRITICAL BUG.

DO NOT USE THIS VERSION! Please, go for a newer version!

3.1.x

The 3.1.x are based on the original CryptoJS, wrapped in CommonJS modules.