bcrypt vs crypto-js vs node-forge vs sjcl
Secure Cryptography and Password Hashing in JavaScript
bcryptcrypto-jsnode-forgesjclSimilar Packages:

Secure Cryptography and Password Hashing in JavaScript

bcrypt, crypto-js, node-forge, and sjcl are JavaScript libraries handling security tasks like hashing, encryption, and key management. bcrypt is the industry standard for password hashing but runs only on Node.js servers. crypto-js offers a simple, pure-JavaScript API for general encryption (AES, SHA) that works in both browsers and Node. node-forge is a powerful, native-feeling toolkit for advanced tasks like PKI and TLS, also supporting both environments. sjcl (Stanford JavaScript Crypto Library) focuses on high-security standards but has seen slower development recently. Choosing the right one depends on whether you need server-side password security, client-side data encryption, or advanced certificate management.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
bcrypt07,7961.11 MB35a year agoMIT
crypto-js016,392487 kB2783 years agoMIT
node-forge05,3111.65 MB4623 months ago(BSD-3-Clause OR GPL-2.0)
sjcl07,2052.24 MB1174 months ago(BSD-2-Clause OR GPL-2.0-only)

Secure Cryptography and Password Hashing in JavaScript

When building secure applications, choosing the right cryptographic library is critical. bcrypt, crypto-js, node-forge, and sjcl each solve different parts of the security puzzle. Some are built for servers, some for browsers, and some for specific advanced tasks. Let's break down how they work and where they fit in your architecture.

🖥️ Environment Compatibility: Server vs Browser

Where your code runs dictates which tools you can use. Native dependencies often limit libraries to Node.js, while pure JavaScript versions work everywhere.

bcrypt relies on native C++ bindings for performance and security.

  • Runs only on Node.js servers.
  • Will fail if you try to bundle it for the browser.
// bcrypt: Server-side only
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('myPassword', 10);
// Works in Node.js, crashes in browser bundlers

crypto-js is written in pure JavaScript.

  • Works in Node.js and all modern browsers.
  • Easy to include via CDN or npm.
// crypto-js: Universal
const CryptoJS = require('crypto-js');
const hash = CryptoJS.SHA256('myPassword').toString();
// Works in Node.js and browser console

node-forge is also pure JavaScript.

  • Designed to work in Node and browsers.
  • Heavier than crypto-js but more capable.
// node-forge: Universal
const forge = require('node-forge');
const hash = forge.md.sha256.create().update('myPassword').digest().toHex();
// Works in Node.js and browser

sjcl is pure JavaScript.

  • Works in Node and browsers.
  • Focused on security correctness over ease of use.
// sjcl: Universal
const sjcl = require('sjcl');
const hash = sjcl.hash.sha256.hash('myPassword');
// Works in Node.js and browser

🔐 Password Hashing: The Right Tool for Credentials

Storing passwords requires a slow, salted hash to prevent brute-force attacks. Not all crypto libraries are built for this.

bcrypt is purpose-built for passwords.

  • Automatically handles salting.
  • Allows you to adjust the "cost" factor to slow down hashing as hardware improves.
  • This is the recommended choice for backend user authentication.
// bcrypt: Password hashing
const saltRounds = 10;
const hash = await bcrypt.hash('userPassword', saltRounds);
const match = await bcrypt.compare('userPassword', hash);

crypto-js provides fast hashes like SHA-256.

  • Not suitable for passwords on its own (too fast).
  • You would need to manually implement salting and iteration.
  • Better for data integrity checks than credential storage.
// crypto-js: Fast hashing (Not for passwords)
const hash = CryptoJS.SHA256('userPassword').toString();
// Vulnerable to rainbow tables without manual salting

node-forge offers PBKDF2 implementation.

  • Can be configured for password hashing.
  • Requires more setup than bcrypt to get right.
  • Useful if you need FIPS compliance or specific algorithm control.
// node-forge: PBKDF2 for passwords
const salt = forge.random.getBytesSync(128);
const key = forge.pkcs5.pbkdf2('password', salt, 1000, 16);
// Requires manual management of salt and iterations

sjcl includes a PBKDF2 implementation.

  • Designed with security best practices in mind.
  • Good alternative if you cannot use bcrypt in your environment.
  • Still requires careful configuration of iteration counts.
// sjcl: PBKDF2 for passwords
const key = sjcl.key.derive.pbkdf2('password', 'salt', 1000, 256);
// Secure but requires manual parameter tuning

🔒 General Encryption: AES and Data Privacy

For encrypting data at rest or in transit (beyond TLS), you need symmetric encryption like AES.

bcrypt does not support encryption.

  • It is a hashing function only.
  • You cannot decrypt a bcrypt hash.
// bcrypt: No encryption support
// Cannot encrypt/decrypt data, only hash passwords

crypto-js makes AES encryption very simple.

  • One-liner encryption and decryption.
  • Great for encrypting local storage or small payloads.
// crypto-js: AES Encryption
const ciphertext = CryptoJS.AES.encrypt('my message', 'secret key').toString();
const bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key');
const plaintext = bytes.toString(CryptoJS.enc.Utf8);

node-forge supports AES with more control.

  • Allows you to manage initialization vectors (IV) and modes explicitly.
  • Better for complex protocols or compliance needs.
// node-forge: AES Encryption
const cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({ iv: iv });
cipher.update(forge.util.createBuffer('my message'));
cipher.finish();
const encrypted = cipher.output.getBytes();

sjcl focuses on authenticated encryption.

  • Uses modes that ensure data hasn't been tampered with.
  • Slightly more verbose but safer by default.
// sjcl: Authenticated Encryption
const encrypted = sjcl.encrypt('key', 'my message');
const decrypted = sjcl.decrypt('key', encrypted);
// Returns JSON with iv, salt, and ciphertext

🛠️ Advanced Features: Certificates and Keys

Some projects need to handle X.509 certificates, public/private key pairs, or PKI structures.

bcrypt has no support for keys or certificates.

  • Strictly for password hashing.
// bcrypt: No key management
// Feature not available

crypto-js has limited key support.

  • Focuses on symmetric keys and passphrases.
  • Does not handle X.509 or RSA key generation well.
// crypto-js: Basic key derivation
// No built-in RSA or Certificate support

node-forge excels at PKI tasks.

  • Can generate RSA keys, CSRs, and self-signed certificates in the browser.
  • Unique capability among pure-JS libraries.
// node-forge: Generate RSA Keys
const keys = forge.pki.rsa.generateKeyPair(2048);
const cert = forge.pki.createCertificate();
cert.publicKey = keys.publicKey;
// Can create actual X.509 certificates client-side

sjcl supports elliptic curve cryptography (ECC).

  • Good for modern key exchange protocols.
  • Less focus on legacy X.509 certificates.
// sjcl: ECC Keys
const keypair = sjcl.ecc.elGamal.generateKeys();
// Focused on curve-based cryptography

📉 Maintenance and Future Proofing

Security libraries need active maintenance to stay safe as new vulnerabilities are discovered.

bcrypt is stable and widely maintained.

  • The standard for Node.js backends.
  • Unlikely to be replaced soon.
// bcrypt: Stable
// Regularly updated for Node compatibility

crypto-js is in maintenance mode.

  • Very stable, but new features are rare.
  • Still safe for standard use cases.
// crypto-js: Maintenance
// Codebase is mature and stable

node-forge is actively used in enterprise tools.

  • Maintained for complex use cases.
  • Larger codebase means larger attack surface, but well-audited.
// node-forge: Active
// Used in many security appliances

sjcl has slower development activity.

  • Code is high quality, but updates are infrequent.
  • Consider Web Crypto API for new browser-only projects.
// sjcl: Slow updates
// Check repository for recent commits before adopting

🤝 Similarities: Shared Security Goals

Despite their differences, these libraries share common ground in how they approach security.

1. 🔒 Focus on Data Protection

  • All aim to protect sensitive information from unauthorized access.
  • Use established algorithms like SHA-256 and AES.
// All support SHA-256 hashing
// bcrypt: via internal logic
// crypto-js: CryptoJS.SHA256()
// node-forge: forge.md.sha256()
// sjcl: sjcl.hash.sha256()

2. 📦 npm Distribution

  • All are installed via npm for easy integration.
  • Support CommonJS and often ES modules.
// Installation
npm install bcrypt crypto-js node-forge sjcl

3. 🧩 Configurable Security Levels

  • Allow developers to tune security (iterations, key sizes).
  • Higher security settings mean slower performance.
// Configuring cost/iterations
// bcrypt: bcrypt.hash(data, 10)
// crypto-js: Custom loops for PBKDF2
// node-forge: pbkdf2(password, salt, iterations, size)
// sjcl: pbkdf2(password, salt, iterations, size)

📊 Summary: Key Differences

Featurebcryptcrypto-jsnode-forgesjcl
Environment🖥️ Node.js Only🌐 Browser & Node🌐 Browser & Node🌐 Browser & Node
Primary Use🔑 Password Hashing🔒 General Encryption🛠️ PKI & Advanced Crypto🛡️ High-Security Crypto
Encryption❌ No✅ AES, RC4, etc.✅ AES, DES, etc.✅ AES, ECC
Certificates❌ No❌ No✅ X.509, CSR⚠️ Limited
Maintenance✅ Active✅ Stable✅ Active⚠️ Slow

💡 The Big Picture

bcrypt is the non-negotiable choice for server-side password storage. Do not try to replace it with a general crypto library for user credentials.

crypto-js is the go-to for simple frontend encryption. If you need to hide data in local storage or sign a quick request, this is the easiest path.

node-forge is the powerhouse for advanced needs. If you are building a certificate authority in the browser or need to parse ASN.1 structures, this is your only pure-JS option.

sjcl is a specialized tool. It is excellent for specific security-critical applications, but for most general web development, crypto-js or the native Web Crypto API are more practical choices today.

Final Thought: Security is not one-size-fits-all. Use bcrypt for passwords on the server, and pick a pure-JS library like crypto-js or node-forge for client-side data protection based on complexity needs.

How to Choose: bcrypt vs crypto-js vs node-forge vs sjcl

  • bcrypt:

    Choose bcrypt if you are building a Node.js backend and need to hash user passwords securely. It is the industry standard for password storage due to its built-in salting and adaptive cost factor. Do not use it in the browser because it relies on native C++ bindings that only run on servers. For frontend password hashing (though generally discouraged), use bcryptjs instead.

  • crypto-js:

    Choose crypto-js if you need a lightweight, easy-to-use library for general encryption and hashing in the browser or Node. It supports AES, SHA, HMAC, and more with a simple API. It is ideal for encrypting local data, securing API payloads, or quick hashing tasks where you don't need advanced PKI features.

  • node-forge:

    Choose node-forge if you need advanced cryptographic features like generating X.509 certificates, handling PKCS#7, or implementing custom TLS logic in JavaScript. It is pure JavaScript, so it works in browsers, but it is heavier than crypto-js. Use it when you need server-grade crypto tools in a client-side or server-side environment without native dependencies.

  • sjcl:

    Choose sjcl if you require a library designed with a strong focus on security best practices and audited code, particularly for legacy projects already using it. However, be aware that development activity has slowed compared to others. It is suitable for specific high-security needs in the browser, but for new projects, crypto-js or Web Crypto API might be more sustainable choices.

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.