bcrypt vs crypto vs crypto-js vs jsrsasign vs node-forge vs node-rsa vs openpgp
前端与 Node.js 环境下的加密、哈希与密钥管理方案选型
bcryptcryptocrypto-jsjsrsasignnode-forgenode-rsaopenpgp类似的npm包:

前端与 Node.js 环境下的加密、哈希与密钥管理方案选型

本文对比了七种主流的 JavaScript 加密与安全库,涵盖了从底层的哈希算法(bcrypt, crypto-js)到复杂的公钥基础设施(node-forge, jsrsasign, openpgp)。crypto 是 Node.js 内置的核心模块,提供高性能的原生支持;bcrypt 是密码哈希的行业标准;crypto-js 专注于浏览器端的算法实现;而 node-forge、jsrsasign 和 openpgp 则分别针对 TLS/PKI、数字签名验证以及 PGP 邮件/文件加密等特定高阶场景。开发者需根据运行环境(Node.js vs 浏览器)、性能需求及具体的安全协议标准来做出架构决策。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
bcrypt07,8041.11 MB381 年前MIT
crypto034-139 年前ISC
crypto-js016,409487 kB2793 年前MIT
jsrsasign03,369890 kB361 个月前MIT
node-forge05,3321.65 MB4656 个月前(BSD-3-Clause OR GPL-2.0)
node-rsa01,3801.44 MB14 个月前MIT
openpgp05,96617.4 MB364 个月前LGPL-3.0+

前端与 Node.js 加密库深度对比:从密码哈希到 PGP 实战

在构建现代 Web 应用时,安全是架构设计的基石。JavaScript 生态系统提供了多种加密库,但它们的应用场景截然不同。有些专为服务端密码存储设计,有些则是为了在浏览器中实现复杂的公钥基础设施。本文将深入对比 bcrypt、crypto、crypto-js、jsrsasign、node-forge、node-rsa 和 openpgp,帮助你根据实际工程需求做出正确选择。

🔐 核心定位:它们到底解决什么问题?

这七个包并非相互竞争,而是各自占据生态位的一角。

  • bcrypt:专为密码哈希设计。它的核心目的是让密码存储变得“慢”且“难”,防止数据库泄露后密码被瞬间破解。
  • crypto:Node.js 的原生瑞士军刀。它基于 OpenSSL,性能极高,适合服务端的所有通用加密需求(AES, RSA, Hash, HMAC)。
  • crypto-js:浏览器端的轻量级算法集。它让前端也能轻松使用 AES、SHA 等算法,常用于本地数据加密或接口签名。
  • jsrsasign:签名与证书专家。专注于 JWT、X.509 证书解析和各种签名算法(RSA, ECDSA),是身份认证领域的重型武器。
  • node-forge:纯 JS 实现的 PKI 工厂。它不依赖原生模块,能在浏览器中生成证书、处理 ASN.1,功能极深但 API 较复杂。
  • node-rsa:简易 RSA 封装。提供了比原生 crypto 更简单的 API 来处理 RSA 密钥对,适合快速原型开发。
  • openpgp:端到端加密标准。完整实现了 OpenPGP 协议,用于邮件加密、文件加密等需要高度互操作性的场景。

🚫 重要警示:已弃用或需谨慎使用的库

在开始代码对比前,必须明确一个关键事实:node-rsa 目前处于维护停滞状态。虽然它仍在许多旧项目中运行,但其 GitHub 仓库已多年未进行重大更新,且不再推荐用于新的安全敏感项目。

架构建议:在新项目中,如果需要 RSA 功能,Node.js 环境请直接用内置的 crypto 模块,全平台环境请使用 node-forge 或 jsrsasign。避免引入 node-rsa 以免未来面临安全补丁缺失的风险。

🛠️ 场景一:用户密码存储(哈希)

这是 Web 开发中最常见的安全需求。绝对不要使用 AES 或 RSA 来存储密码,必须使用专用的哈希算法。

✅ 正确做法:使用 bcrypt

bcrypt 会自动处理盐值(Salt)并调整计算成本(Cost),使得暴力破解极其耗时。

// 安装:npm install bcrypt
const bcrypt = require('bcrypt');

async function hashPassword(password) {
  // 生成盐值并哈希,10 是成本因子
  const hash = await bcrypt.hash(password, 10);
  return hash;
}

async function verifyPassword(password, hash) {
  // 验证密码
  const match = await bcrypt.compare(password, hash);
  return match; // true 或 false
}

❌ 错误做法:使用 crypto-js 或 crypto 做简单哈希

许多开发者误以为 SHA256 就够了,这是危险的。简单的哈希速度太快,容易被 GPU 集群破解。

// 不推荐用于密码存储,仅用于数据完整性校验
const CryptoJS = require('crypto-js');
const hash = CryptoJS.SHA256("user_password").toString();
// 这种哈希几秒钟就能被破解数百万次

🔑 场景二:通用数据加密与解密(对称加密)

当你需要加密数据库中的敏感字段(如身份证号、银行卡号)或在网络上传输机密数据时,通常使用 AES 算法。

Node.js 环境:首选内置 crypto

原生模块性能最好,无需额外依赖。

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 256 位密钥
const iv = crypto.randomBytes(16);  // 初始化向量

function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

function decrypt(encryptedText) {
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

浏览器环境:使用 crypto-js

浏览器没有内置 crypto 模块(Web Crypto API 较底层且异步,使用麻烦),crypto-js 提供了同步且易用的 API。

const CryptoJS = require('crypto-js');

const key = CryptoJS.lib.WordArray.random(256/8);

// 加密
const encrypted = CryptoJS.AES.encrypt("Secret Message", key).toString();

// 解密
const bytes = CryptoJS.AES.decrypt(encrypted, key);
const originalMessage = bytes.toString(CryptoJS.enc.Utf8);

全平台兼容方案:node-forge

如果你需要在浏览器和 Node.js 中使用同一套逻辑处理复杂的加密原语。

const forge = require('node-forge');

const key = forge.random.getBytesSync(32);
const iv = forge.random.getBytesSync(16);

// 加密
const cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({ iv: iv });
cipher.update(forge.util.createBuffer('Secret Message', 'utf8'));
cipher.finish();
const encrypted = cipher.output.toHex();

// 解密
const decipher = forge.cipher.createDecipher('AES-CBC', key);
decipher.start({ iv: iv });
decipher.update(forge.util.createBuffer(encrypted, 'hex'));
decipher.finish();
const decrypted = decipher.output.toString('utf8');

📝 场景三:JWT 签名与验证(非对称加密)

在微服务架构中,服务间常通过 JWT 传递身份。这涉及私钥签名和公钥验证。

功能最全:jsrsasign

它支持极其丰富的密钥格式(PEM, JWK, Hex)和算法(RS256, ES256 等),是处理 JWT 的利器。

const KJUR = require('jsrsasign');

// 生成密钥对 (实际生产中应从安全存储读取)
const prvKey = KJUR.KEYUTIL.generateKeypair("RSA", 2048);

// 签名 JWT
const sHeader = JSON.stringify({ alg: "RS256", typ: "JWT" });
const sPayload = JSON.stringify({ sub: "user123", exp: 1999999999 });
const sJWT = KJUR.jws.JWS.sign("RS256", sHeader, sPayload, prvKey.prvKeyObj);

// 验证 JWT
const isValid = KJUR.jws.JWS.verify(sJWT, prvKey.pubKeyObj, ["RS256"]);
// isValid === true

底层控制:node-forge

如果你需要手动构建 JWT 或处理自定义的签名逻辑。

const forge = require('node-forge');
const jwt = require('jsonwebtoken'); // 通常配合使用,此处演示 forge 签名

// 使用 forge 处理密钥转换
const pem = {
  privateKey: '-----BEGIN RSA PRIVATE KEY-----...',
  publicKey: '-----BEGIN PUBLIC KEY-----...'
};

// node-forge 常用于将 PEM 转换为其他格式或进行底层签名操作
const pki = forge.pki;
const privateKey = pki.privateKeyFromPem(pem.privateKey);
// 进行签名操作...

📜 场景四:证书管理与 PKI(高阶场景)

当你需要动态生成 SSL 证书、解析 .crt 文件或实现类似 Let's Encrypt 的功能时。

唯一选择:node-forge

它是 JavaScript 中极少数能完整处理 X.509 证书生成和解析的库。

const forge = require('node-forge');
const pki = forge.pki;

// 生成密钥对
const keys = pki.rsa.generateKeyPair(2048);

// 创建自签名证书
const cert = pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = '01';
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);

const attrs = [{
  name: 'commonName',
  value: 'example.com'
}];
cert.setSubject(attrs);
cert.setIssuer(attrs); // 自签名

// 使用私钥签名证书
cert.sign(keys.privateKey, forge.md.sha256.create());

// 导出为 PEM 格式
const pem = pki.certificateToPem(cert);
console.log(pem);

📧 场景五:端到端加密(PGP)

如果你的应用需要让用户互相发送只有彼此能解密的邮件或文件(类似 ProtonMail)。

标准实现:openpgp

const openpgp = require('openpgp');

// 生成用户密钥对
async function generateKeys() {
  const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
    type: 'ecc', // 使用椭圆曲线,更短更安全
    curve: 'curve25519',
    userIDs: [{ name: 'Alice', email: '[email protected]' }],
    passphrase: 'super secret'
  });
  return { privateKey, publicKey };
}

// 加密消息
async function encryptMessage(publicKeyArmored, text) {
  const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
  const encrypted = await openpgp.encrypt({
    message: await openpgp.createMessage({ text: text }),
    encryptionKeys: publicKey
  });
  return encrypted;
}

📊 总结与选型指南

特性bcryptcryptocrypto-jsjsrsasignnode-forgenode-rsaopenpgp
运行环境Node.jsNode.js浏览器/Node浏览器/Node浏览器/NodeNode.js浏览器/Node
核心用途密码哈希通用加密/哈希前端轻量加密JWT/证书验证PKI/证书生成简单 RSAPGP 加密
性能慢 (有意)⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
API 难度低中低高极高低中
维护状态✅ 活跃✅ 原生✅ 活跃✅ 活跃✅ 活跃⚠️ 停滞✅ 活跃

💡 架构师建议

  1. 密码存储:别犹豫,直接用 bcrypt。不要尝试自己发明哈希算法。
  2. Node.js 后端:优先使用内置的 crypto。它最快、最安全且没有依赖地狱。
  3. 前端加密:如果是简单的本地数据保护或接口签名,crypto-js 足够好用。如果需要处理证书或复杂签名,考虑 jsrsasign。
  4. 证书与 PKI:如果你需要在 JS 中玩转证书(生成、解析、转换),node-forge 是唯一成熟的方案,尽管它的学习曲线较陡峭。
  5. 避免使用:除非是在维护十年前的老代码,否则不要在新项目中引入 node-rsa。
  6. 特殊需求:只有当你真的需要兼容 GPG 生态或实现真正的端到端加密通信时,才引入 openpgp,因为它的包体积较大且计算密集。

安全无小事,选择经过时间考验、维护活跃的库,并严格遵循“不要在客户端存储密钥”、“不要重复使用 IV”等基本原则,比选择哪个库更重要。

如何选择: bcrypt vs crypto vs crypto-js vs jsrsasign vs node-forge vs node-rsa vs openpgp

  • bcrypt:

    当你在 Node.js 服务端需要存储用户密码时,首选 bcrypt。它是业界标准的自适应哈希算法,能有效抵御彩虹表攻击和暴力破解。不要用它来加密传输数据或处理大文件,它专为短字符串(密码)的单向哈希设计。

  • crypto:

    如果你在开发纯 Node.js 后端应用且追求极致性能,直接使用内置的 crypto 模块。它无需安装额外依赖,支持最新的 OpenSSL 算法,适合处理 HTTPS、流式加密和高吞吐量的数据签名场景。

  • crypto-js:

    当你需要在浏览器端进行轻量级的加密操作(如 AES 加密本地存储数据、生成 HMAC 签名)时,选择 crypto-js。它提供了友好的 API 且兼容性好,但请注意不要在前端进行密码哈希(如 bcrypt),因为这会暴露盐值且不安全。

  • jsrsasign:

    如果你的主要需求是验证 JWT 令牌、处理 X.509 证书或进行复杂的 RSA/ECDSA 签名验证,jsrsasign 是功能最全面的选择。它特别擅长处理各种格式的密钥转换和标准的签名算法,适合身份认证中间件的开发。

  • node-forge:

    当你需要在 JavaScript 环境中实现完整的 PKI 功能(如生成 CSR、自签名证书、操作 ASN.1 结构)或在浏览器中模拟 TLS 握手时,node-forge 是无可替代的工具。它的 API 较底层,适合构建需要深度控制加密原语的基础设施库。

  • node-rsa:

    仅当你需要快速实现简单的 RSA 加解密且不希望处理复杂的密钥格式转换时,才考虑 node-rsa。对于新项目,建议优先使用 crypto(Node.js)或 node-forge(通用),因为 node-rsa 的功能相对单一且更新频率较低。

  • openpgp:

    当你的应用场景涉及端到端加密邮件、加密文件存储或需要兼容 GPG 生态系统的互操作性时,必须选择 openpgp。它是 OpenPGP 标准的完整实现,适合构建隐私优先的通信应用,但不适合用于常规的 Web 会话管理。

bcrypt的README

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.