bcrypt、crypto-js、pbkdf2、scrypt-js はいずれもJavaScript環境でパスワードやデータのハッシュ化・暗号化を行うためのnpmパッケージですが、それぞれ異なるアルゴリズムと設計思想を持っています。bcrypt はパスワード専用のアダプティブハッシュ関数で、saltの自動管理が特徴です。crypto-js はAESやSHA-256を含む汎用暗号ライブラリで、PBKDF2などの鍵導出関数も提供します。pbkdf2 はNIST標準の鍵導出関数を実装し、Web Crypto APIと連携して非同期処理をサポートします。scrypt-js はメモリ強度が高いscryptアルゴリズムを純粋なJavaScriptで実装し、ブルートフォース攻撃への耐性を重視しています。これらのパッケージは、フロントエンドでの使用可否、同期/非同期の動作、セキュリティ特性、および実装の容易さにおいて大きく異なります。
フロントエンドアプリケーションでユーザー認証を実装する際、パスワードの安全なハッシュ化は不可欠です。しかし、ブラウザ環境では適切なアルゴリズムとライブラリの選択が重要になります。ここでは bcrypt、crypto-js、pbkdf2、scrypt-js の4つのnpmパッケージを、実際の開発者の視点から比較します。
まず、各パッケージが提供する暗号アルゴリズムの基本的な性質を確認しましょう。
bcrypt:パスワード専用に設計されたアダプティブハッシュ関数。内部でsaltを自動生成し、計算コスト(ラウンド数)を調整可能。crypto-js:汎用暗号ライブラリ。AES、SHA-256、HMACなど多数のアルゴリズムを含むが、パスワードハッシュにはPBKDF2やその他のKDF(鍵導出関数)を明示的に使う必要がある。pbkdf2:NIST標準の鍵導出関数。任意のハッシュ関数(例:SHA-256)と反復回数を指定して使用。scrypt-js:メモリ強度が高いアルゴリズム。ASICやGPUによるブルートフォース攻撃に対して特に強い。⚠️ 重要な注意点:フロントエンドでパスワードをハッシュ化するのは、通常推奨されません。サーバーサイドでハッシュ化すべきです。ただし、特定のユースケース(例:完全クライアントサイドのアプリ、オフライン認証)ではフロントエンドハッシュが必要になる場合があります。
ブラウザ環境では、長時間実行される処理がUIをフリーズさせるため、非同期処理が必須です。
bcrypt(Node.js向けのネイティブバインディング版)は、ブラウザでは動作しません。代わりに、純粋なJavaScript実装である bcryptjs を使う必要がありますが、これは同期的であり、高コスト設定ではUIをブロックします。
// bcryptjs(同期的 — UIをブロックする可能性あり)
import bcrypt from 'bcryptjs';
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync('password123', salt);
crypto-js も同期的です。PBKDF2を使用する場合も同様です。
// crypto-js(同期的)
import CryptoJS from 'crypto-js';
const salt = CryptoJS.lib.WordArray.random(128/8);
const hash = CryptoJS.PBKDF2('password123', salt, {
keySize: 256/32,
iterations: 10000
});
pbkdf2 パッケージ(node-forge 由来のもの)は、Web Crypto API を利用した非同期実装を提供します。
// pbkdf2(非同期)
import { pbkdf2 } from 'pbkdf2';
pbkdf2('password123', 'somesalt', 10000, 32, 'sha256', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex'));
});
// Promiseベースの使用も可能(ドキュメント参照)
scrypt-js も非同期で動作し、プログレスコールバックをサポートします。
// scrypt-js(非同期)
import scrypt from 'scrypt-js';
const password = new TextEncoder().encode('password123');
const salt = new TextEncoder().encode('somesalt');
scrypt.scrypt(password, salt, 16384, 8, 1, 32).then((key) => {
console.log(new TextDecoder().decode(key));
});
💡 結論:UIをブロックしたくないなら、
pbkdf2またはscrypt-jsを選ぶべきです。bcrypt(およびcrypto-js)は同期的で、高コスト設定ではUXを損ないます。
bcrypt / bcryptjs:saltを自動生成・埋め込み。検証時にsaltを別途保存不要。crypto-js:saltを自分で生成・保存する必要あり。pbkdf2:saltを明示的に渡す必要あり。scrypt-js:saltを明示的に渡す必要あり。// bcryptjs:saltがハッシュ内に含まれる
const hash = bcrypt.hashSync('pass', 10);
// 後で検証
bcrypt.compareSync('pass', hash); // true
// crypto-js:saltを別管理
const salt = CryptoJS.lib.WordArray.random(16);
const hash = CryptoJS.PBKDF2('pass', salt, { iterations: 10000 });
// 検証時は同じsaltが必要
bcrypt は compare メソッドで簡単に検証可能。bcrypt:ラウンド数10〜12(2024年現在)。PBKDF2:反復回数10,000以上(NIST推奨は最低10,000)。scrypt:N=16384, r=8, p=1 が一般的な起点。ただし、フロントエンドでは計算リソースが限られているため、過剰なコスト設定は避けるべきです。ユーザー体験を損なうだけでなく、DoS攻撃のベクトルにもなり得ます。
bcrypt(公式パッケージ):Node.js専用。ブラウザでは動作しない。代わりに bcryptjs を使う必要あり(重い)。crypto-js:純粋なJavaScript。古いブラウザでも動作。pbkdf2:現代のブラウザ(Web Crypto API対応)で最適化。古い環境ではポリフィルが必要。scrypt-js:純粋なJavaScript実装。Web Workerとの併用が推奨。scrypt-jscrypto-js + PBKDF2pbkdf2bcrypt(ネイティブ版)bcrypt 公式パッケージをブラウザで使おうとしないこと。動作しません。crypto-js のMD5やSHA-1をパスワードハッシュに使わないこと。これらはKDFではなく、脆弱です。pbkdf2 または scrypt-js を選びましょう。bcrypt 以外の場合)。// Web Worker内でscrypt-jsを使う例(main.js)
const worker = new Worker('hash-worker.js');
worker.postMessage({ password: '...', salt: '...' });
worker.onmessage = (e) => console.log(e.data.hash);
// hash-worker.js
importScripts('scrypt-js/umd/scrypt.js');
onmessage = (e) => {
const { password, salt } = e.data;
scrypt.scrypt(
new TextEncoder().encode(password),
new TextEncoder().encode(salt),
16384, 8, 1, 32
).then(key => postMessage({ hash: key }));
};
セキュリティとユーザーエクスペリエンスのバランスを取ることが、フロントエンド開発者の責任です。適切なツールを選び、正しく実装しましょう。
bcrypt 公式パッケージはNode.js環境専用であり、ブラウザでは動作しません。フロントエンドで使う場合は bcryptjs という代替パッケージが必要ですが、これは同期処理のため高コスト設定でUIをブロックします。完全クライアントサイドアプリで簡易実装が必要で、かつUIフリーズが許容できる場合にのみ検討してください。通常はサーバーサイドでの使用を想定しています。
crypto-js は軽量で古いブラウザでも動作する汎用暗号ライブラリです。PBKDF2機能を使ってパスワードハッシュ化が可能ですが、同期処理のため高コスト設定ではUIが固まります。バンドルサイズを最小限に抑えたい簡易認証システムや、オフライン用途でセキュリティ要件が中程度のケースに向いています。ただし、MD5やSHA-1など脆弱なハッシュ関数を誤って使わないよう注意が必要です。
pbkdf2 パッケージはWeb Crypto APIを活用した非同期実装を提供し、UIをブロックせずに安全な鍵導出が可能です。現代のブラウザ環境で標準ベースのアプローチをとりたい場合や、サーバーとの連携前提でフロントエンドで事前ハッシュ処理が必要なケースに最適です。NIST標準に基づく信頼性と、Promise対応による使いやすさが大きなメリットです。
scrypt-js はメモリ強度が高いscryptアルゴリズムを純粋なJavaScriptで実装し、非同期処理とプログレスコールバックをサポートします。完全オフラインのパスワードマネージャーや、高いセキュリティが求められるクライアントサイドアプリに最適です。Web Workerと組み合わせればUIブロッキングを完全に回避でき、ブルートフォース攻撃への耐性も高いため、セキュリティを最優先するプロジェクトで選択すべきです。
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.