bcrypt vs crypto vs crypto-js vs jsrsasign vs node-forge vs node-rsa vs openpgp
JavaScript における暗号化とセキュリティ実装の選択ガイド
bcryptcryptocrypto-jsjsrsasignnode-forgenode-rsaopenpgp類似パッケージ:

JavaScript における暗号化とセキュリティ実装の選択ガイド

bcryptcryptocrypto-jsjsrsasignnode-forgenode-rsaopenpgp は、JavaScript 環境でセキュリティ機能を実装するための主要なライブラリ群です。これらはパスワードハッシュ化、対称鍵暗号、公開鍵暗号(RSA)、デジタル署名、PGP などの異なる暗号プリミティブを提供します。crypto は Node.js の標準モジュールであり、高性能な基盤となります。一方、crypto-jsnode-forge はブラウザ環境での動作を可能にする純粋な JavaScript 実装です。bcrypt はパスワード保存に特化し、jsrsasignnode-rsa は特定のアルゴリズムに焦点を当て、openpgp はメールやファイルの暗号化ための完全なプロトコル実装を提供します。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
bcrypt07,8021.11 MB381年前MIT
crypto033-139年前ISC
crypto-js016,399487 kB2783年前MIT
jsrsasign03,371890 kB435日前MIT
node-forge05,3271.65 MB4615ヶ月前(BSD-3-Clause OR GPL-2.0)
node-rsa01,3801.44 MB03ヶ月前MIT
openpgp05,96617.4 MB362ヶ月前LGPL-3.0+

JavaScript 暗号化ライブラリ完全比較:bcrypt, crypto, crypto-js, jsrsasign, node-forge, node-rsa, openpgp

JavaScript でセキュリティ機能を実装する際、どのライブラリを選ぶべきかは「実行環境(Node.js かブラウザか)」と「解決したい課題(パスワード保存か、通信暗号化か)」によって完全に異なります。間違った選択をすると、ビルドエラーになったり、セキュリティホールを作ったり、あるいは必要以上にコードが複雑になったりします。

ここでは、主要な 7 つのパッケージを技術的な観点から深く比較し、具体的なコード例を通じてそれぞれの特徴と使いどころを明確にします。

🔐 パスワード保存:bcrypt の一強体制

ユーザーのパスワードをデータベースに保存する際、平文で保存するのは論外です。必ずハッシュ化する必要があります。この用途において、bcrypt は業界標準であり、他の汎用ライブラリで代用すべきではありません。

bcrypt は、ハッシュ計算に時間をかけることで(キーストレッチング)、総当たり攻撃を困難にします。ソルト(ランダムなデータ)を自動的に生成・埋め込むため、開発者が意識すべきことが少なく、安全です。

// bcrypt: パスワードのハッシュ化と検証
const bcrypt = require('bcrypt');
const saltRounds = 10;

// ハッシュ生成
const hash = await bcrypt.hash('mySecretPassword', saltRounds);

// 検証
const match = await bcrypt.compare('mySecretPassword', hash);
if (match) {
  console.log('パスワードが一致しました');
}

一方、crypto モジュールにもハッシュ機能(SHA-256 など)がありますが、これらは「高速」に作られているため、パスワード保存には不向きです。crypto-js なども同様で、パスワード保存用には設計されていません。

🚀 Node.js サーバー環境:crypto モジュールの活用

Node.js でサーバーサイドの処理を行う場合、外部ライブラリをインストールせずとも強力な暗号機能が使えます。それが標準モジュールの crypto です。

crypto は C++ で書かれた OpenSSL にバインドしているため、処理速度が非常に速く、メモリ効率も優れています。AES による暗号化や、RSA による署名など、幅広いアルゴリズムをサポートします。

// crypto: AES 暗号化(Node.js 環境)
const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 256bit
const iv = crypto.randomBytes(16);  // 初期化ベクトル

const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('sensitive data', 'utf8', 'hex');
encrypted += cipher.final('hex');

console.log('暗号化データ:', encrypted);

ただし、このモジュールはブラウザでは動作しません。フロントエンドで同じ処理をしたい場合は、後述する crypto-jsnode-forge を選ぶ必要があります。

🌐 ブラウザ環境での暗号化:crypto-js vs node-forge

ブラウザ上でデータを暗号化したい場合(例:エンドツーエンド暗号化チャット、ローカルストレージの保護)、純粋な JavaScript で書かれたライブラリが必要です。

crypto-js は、最もシンプルで軽量な選択肢です。AES、DES、Rabbit、SHA、HMAC などの主要アルゴリズムをカバーしており、API が非常に直感的です。

// crypto-js: ブラウザでの AES 暗号化
const CryptoJS = require('crypto-js');

const message = 'secret message';
const password = 'shared-secret';

// 簡易的な暗号化(実際は Salt や IV の管理に注意が必要)
const encrypted = CryptoJS.AES.encrypt(message, password).toString();
const decrypted = CryptoJS.AES.decrypt(encrypted, password).toString(CryptoJS.enc.Utf8);

console.log('復号結果:', decrypted);

一方、node-forge は、より低レベルで広範な機能を提供します。特に、証明書の生成(X.509)、CSR の作成、TLS ハンドシェイクのシミュレーションなど、PKI(公開鍵基盤)に関わる処理が必要な場合は node-forge 一択です。

// node-forge: 自己署名証明書の生成(ブラウザでも動作)
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();
const notAfter = new Date();
notAfter.setFullYear(notAfter.getFullYear() + 1);
cert.validity.notAfter = notAfter;

// 署名(自己署名)
cert.sign(keys.privateKey, forge.md.sha256.create());

console.log('証明書 PEM:', pki.certificateToPem(cert));

crypto-js が「手軽に使いたい」場合に適しているのに対し、node-forge は「証明書を扱いたい」「細かく制御したい」場合の道具箱と言えます。

🔑 公開鍵暗号と JWT:jsrsasign vs node-rsa

公開鍵暗号(RSA)やデジタル署名、JWT(JSON Web Token)の処理に特化したライブラリも重要です。

node-rsa は、その名の通り RSA アルゴリズムに特化しています。鍵の生成から暗号化、復号、署名まで、非常に読みやすいコードで記述できます。

// node-rsa: RSA 暗号化と復号
const NodeRSA = require('node-rsa');

const key = new NodeRSA({ b: 512 }); // 512bit の鍵生成(実験用)
key.setOptions({ encryptionScheme: 'pkcs1' });

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

console.log('復号:', decrypted);

一方、jsrsasign は、RSA だけでなく ECDSA など様々なアルゴリズムをサポートし、特に JWT の扱いに強みを持ちます。また、ASN.1 というデータ形式の解析機能も備えており、証明書の中身を読み解くような高度な処理が可能です。

// jsrsasign: JWT の署名と検証
const KJUR = require('jsrsasign');

const sHeader = JSON.stringify({ alg: 'HS256', typ: 'JWT' });
const sPayload = JSON.stringify({ sub: 'user123', exp: 4600000000 });

// 署名生成
const sJWT = KJUR.jws.JWS.sign('HS256', sHeader, sPayload, 'secret-key');

// 検証
const isValid = KJUR.jws.JWS.verify(sJWT, 'secret-key', ['HS256']);

console.log('JWT 有効:', isValid);

単純な RSA 操作なら node-rsa で十分ですが、JWT や証明書解析など幅広い要件がある場合は jsrsasign が適しています。

📧 完全なプロトコル実装:openpgp

openpgp は、他のライブラリとは次元が異なります。これは単なるアルゴリズムの集合ではなく、「OpenPGP」という通信プロトコル(RFC 4880)の完全な実装です。

メールの暗号化や、ファイルの署名・検証など、鍵の管理から実際の通信までを一貫して行いたい場合に使用します。

// openpgp: メッセージの暗号化と復号
const openpgp = require('openpgp');

// 公開鍵と秘密鍵の読み込み(文字列)
const publicKeyArmored = '-----BEGIN PGP PUBLIC KEY BLOCK...';
const privateKeyArmored = '-----BEGIN PGP PRIVATE KEY BLOCK...';
const passphrase = 'my-secret-passphrase';

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

async function decryptMessage(encryptedData) {
  const privateKey = (await openpgp.readKey({ armoredKey: privateKeyArmored })).keys[0];
  await privateKey.decrypt(passphrase);

  const message = await openpgp.readMessage({ armoredMessage: encryptedData });
  const { data: decrypted } = await openpgp.decrypt({
    message,
    decryptionKeys: privateKey,
  });
  return decrypted;
}

特定のアルゴリズムを個別に組み合わせて自作することも可能ですが、セキュリティリスクが高まります。PGP 標準が必要な場合は、実績のある openpgp ライブラリを使うのが賢明です。

⚠️ 重要な注意点と非推奨パッケージ

比較対象に含まれている crypto(npm パッケージ版)には注意が必要です。Node.js には標準で crypto モジュールが含まれています。npm にある crypto パッケージは、かつてブラウザ互換のために存在しましたが、現在はメンテナンスが停止しており、新規プロジェクトで使用すべきではありません

ブラウザで暗号化が必要な場合は、前述の crypto-jsnode-forge、あるいは最新のブラウザ標準 API である SubtleCrypto (window.crypto.subtle) を使用してください。

// ❌ 非推奨:npm の 'crypto' パッケージ
// const crypto = require('crypto'); // これは使わない

// ✅ 推奨:Node.js 標準
// const crypto = require('crypto'); 

// ✅ 推奨:ブラウザ標準 API
// const subtle = window.crypto.subtle;

また、node-rsa はメンテナンス頻度が低下している傾向にあります。RSA 処理のみであれば問題ありませんが、より現代的なアルゴリズム(Ed25519 など)や長期サポートを考慮すると、crypto (Node.js) や jsrsasignnode-forge への移行を検討する価値があります。

📊 選定サマリー

パッケージ主な用途実行環境特徴
bcryptパスワードハッシュNode.jsパスワード保存の事実上の標準。遅いことが逆に安全。
crypto汎用暗号化Node.js標準モジュール。最速。ブラウザ不可。
crypto-js軽量暗号化ブラウザ/NodeAPI が簡単。AES や SHA を手軽に使いたい時に。
jsrsasignJWT, 署名, PKIブラウザ/Node多機能。JWT や ASN.1 処理に強い。
node-forge証明書, PKIブラウザ/Node証明書生成など高度な機能。純粋 JS。
node-rsaRSA 特化Node.jsRSA 操作に特化したシンプルな API。
openpgpPGP 通信ブラウザ/NodeOpenPGP プロトコルの完全実装。メール等。

💡 アーキテクトからのアドバイス

セキュリティライブラリの選定で最も重要なのは、「何を防ぎたいか」を明確にすることです。

  1. パスワードを保存したいだけなら、迷わず bcrypt を使ってください。他のもので自作ハッシュ関数を作るのは危険です。
  2. Node.js サーバーで通信データを暗号化したいなら、追加インストール不要の crypto モジュールが最強です。
  3. ブラウザで機密データを扱いたいならcrypto-js で手軽に始めるか、証明書処理が必要なら node-forge を選びます。可能であれば、最新の SubtleCrypto API の採用も検討してください。
  4. JWT や電子署名が必要ならjsrsasign が包括的なサポートを提供します。
  5. メールやファイルの暗号化など、特定のプロトコルが必要ならopenpgp のような専門ライブラリに頼るべきです。

セキュリティは「便利さ」よりも「確実性」が求められます。ドキュメントが整備され、コミュニティで長く使われ続けているライブラリを選ぶことが、結果として最も近道となります。

選び方: bcrypt vs crypto vs crypto-js vs jsrsasign vs node-forge vs node-rsa vs openpgp

  • bcrypt:

    パスワードの保存と認証に特化して選択します。ソルト付きハッシュ生成と、計算コストを調整できる機能により、総当たり攻撃への耐性が高いため、ユーザー認証システムにはほぼ必須です。Node.js 環境での使用を前提としており、ネイティブモジュールを含むためビルド環境の準備が必要です。

  • crypto:

    Node.js サーバー環境で開発しており、追加の依存関係を増やしたくない場合に選択します。OS の OpenSSL バインディングを利用するため、パフォーマンスが最も高く、AES や RSA などの標準的な暗号操作を広くカバーします。ブラウザでは動作しないため、フロントエンド単独での利用はできません。

  • crypto-js:

    ブラウザ環境だけで完結する軽量な暗号化(AES, SHA, HMAC など)が必要な場合に選択します。API がシンプルで学習コストが低く、バンドルサイズも比較的小さいため、クライアントサイドでのデータ難読化や簡易的なセキュリティ要件に適しています。ただし、秘密鍵をクライアントに保持する必要があるため、設計上の注意が必要です。

  • jsrsasign:

    JWT の署名・検証や、RSA/ECDSA などの公開鍵暗号をブラウザまたは Node.js で柔軟に扱いたい場合に選択します。ASN.1 の解析や証明書の扱いなど、他のライブラリでは難しい低レベルな操作もサポートしています。多機能ですが、API がやや複雑であるため、特定の暗号処理に特化した利用が推奨されます。

  • node-forge:

    ブラウザで証明書(X.509)の生成や PKI 関連の高度な操作を行う必要がある場合に選択します。純粋な JavaScript で書かれているため環境依存性がなく、TLS ソケットの実装など非常に幅広い機能を持ちます。機能が多岐にわたるため、特定の機能のみを使いたい場合にはオーバーヘッドになる可能性があります。

  • node-rsa:

    RSA 暗号に特化したシンプルで直感的な API を求める場合に選択します。鍵の生成、暗号化、復号、署名までのフローが非常に分かりやすく書けるため、学習用やプロトタイピングに適しています。ただし、機能範囲が RSA に限定されており、他のアルゴリズムが必要な場合には向きません。

  • openpgp:

    OpenPGP 標準に準拠したメール暗号化やファイル署名を行う必要がある場合に選択します。鍵の管理、暗号化、復号、署名、検証までをワンセットで提供しており、他のシステムとの相互運用性が重視されるプロジェクトで真価を発揮します。機能が高機能である分、設定と理解には一定の暗号知識が必要です。

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.