bcrypt、crypto、crypto-js、node-forge、sjcl は、JavaScript アプリケーションでセキュリティ機能を構築するための主要なライブラリ群です。Node.js 組み込みの crypto モジュールは、サーバーサイドでの高性能な暗号化操作の基盤となります。一方、bcrypt はパスワード保存に特化した事実上の標準ライブラリです。ブラウザ環境やユニバーサル JavaScript を目指す場合、crypto-js、node-forge、sjcl といった純粋な JavaScript 実装(Pure JS)が選択されます。これらはそれぞれ、使いやすさ、機能の網羅性、あるいはセキュリティへの厳格なアプローチにおいて異なる特徴を持っています。
現代の Web 開発において、ユーザーデータの保護は最も重要な責務の一つです。パスワードの保存、通信の暗号化、トークンの生成など、セキュリティに関わる処理を「自作」することは絶対に避けるべきです。代わりに、コミュニティで検証された信頼性の高いライブラリを使用する必要があります。
ここでは、JavaScript エコシステムで広く使われる 5 つの主要なパッケージ(bcrypt、crypto、crypto-js、node-forge、sjcl)を、実務的な観点から深く比較します。それぞれの「得意分野」と「落とし穴」を理解し、あなたのプロジェクトに最適な選択ができるようになりましょう。
bcrypt 一択なのかパスワードをデータベースに保存する際、平文で保存してはなりません。また、単なる SHA-256 などのハッシュ関数も高速すぎて総当たり攻撃(ブルートフォースアタック)に弱いため不適切です。ここでは、意図的に計算コストを高く設定し、攻撃を困難にする「キー導出関数」が必要です。
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 や crypto-js など)で bcrypt アルゴリズムを実装することも技術的には可能ですが、それらは汎用ツールであり、タイミング攻撃への対策やソルト管理のベストプラクティスが bcrypt パッケージほど徹底的に組み込まれていません。パスワード処理に関しては、迷わず bcrypt を選ぶべきです。
注意点:
bcryptはネイティブモジュール(C++)に依存しているため、ビルド環境が必要です。もし純粋な JavaScript 実装が必須の場合は、bcryptjsという代替パッケージを検討してください(本比較の対象外ですが、API は互換性があります)。
cryptoNode.js でサーバーサイド開発を行っている場合、外部ライブラリをインストールする前にまず確認すべきが、標準搭載の crypto モジュールです。これは OpenSSL にバインドされており、非常に高速で信頼性が高いのが特徴です。
AES によるデータ暗号化、RSA による署名、SHA-256 などのハッシュ計算など、あらゆる暗号操作をカバーしています。ただし、これは Node.js 環境専用であり、ブラウザの JavaScript では直接動作しません。
// crypto (Node.js): AES-256-GCM による暗号化
const crypto = require('crypto');
const algorithm = 'aes-256-gcm';
// キーと IV(初期化ベクトル)の生成
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// 暗号化
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('sensitive data', 'utf8', 'hex');
encrypted += cipher.final('hex');
// 認証タグの取得
const authTag = cipher.getAuthTag();
console.log('暗号化データ:', encrypted);
パフォーマンスが最優先されるバックエンドシステムや、マイクロサービス間の通信セキュリティを確保する際には、このネイティブモジュールが第一選択となります。余計な依存関係を増やさず、OS レベルのセキュリティ更新の恩恵も受けられるため、保守性も高いです。
フロントエンド、あるいは Node.js とブラウザの両方で動くコード(ユニバーサル JavaScript)を書く場合、ネイティブモジュールに依存しない「純粋な JavaScript」で書かれたライブラリが必要です。ここで登場するのが crypto-js、node-forge、sjcl の 3 つです。これらは環境を選びませんが、設計思想と得意分野が明確に異なります。
crypto-jscrypto-js は、最も広く使われている純粋 JavaScript 暗号化ライブラリの一つです。API が非常にシンプルで、直感的に使えるよう設計されています。「AES で暗号化したい」「SHA-256 でハッシュ化したい」と思ったときに、ドキュメントを見ずに書けるレベルの使いやすさがあります。
// crypto-js: AES 暗号化
const CryptoJS = require('crypto-js');
const message = "Secret Message";
const passphrase = "Secret Passphrase";
// 暗号化(ワンライナーで完結)
const encrypted = CryptoJS.AES.encrypt(message, passphrase).toString();
// 復号化
const bytes = CryptoJS.AES.decrypt(encrypted, passphrase);
const decrypted = bytes.toString(CryptoJS.enc.Utf8);
console.log('復号結果:', decrypted);
しかし、その手軽さの裏側として、メンテナンスの頻度が他のライブラリに比べて低いという指摘があります。最新の暗号攻撃への対策や、新しいアルゴリズムのサポートが遅れる可能性があるため、極めて機密性の高いデータを扱う場合は、実装の古さを意識しておく必要があります。
node-forgenode-forge は、単なる暗号化アルゴリズムの集合を超え、TLS、SSL、PKI(公開鍵基盤)、ASN.1 といった複雑なプロトコルまでをサポートする「ツールキット」です。ブラウザで証明書を扱ったり、CSR(証明書署名依頼)を生成したりするような特殊な要件がある場合、これ一択となることが多いです。
// 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();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
// 署名(自己署名)
cert.sign(keys.privateKey);
const pem = pki.certificateToPem(cert);
console.log('証明書:', pem);
機能が豊富な反面、ライブラリサイズは大きくなりがちです。また、API が多機能すぎて初学者には少し複雑に映るかもしれません。しかし、「ブラウザで PKI を扱いたい」というニッチかつ重要な要件に対しては、圧倒的な強さを発揮します。
sjclsjcl (Stanford JavaScript Crypto Library) は、その名が示す通りスタンフォード大学によって開発・監査されたライブラリです。その設計思想は「便利さ」よりも「数学的な正しさと安全性」に重きを置いています。実装の各部分が慎重にレビューされており、サイドチャネル攻撃などへの耐性を重視しています。
// sjcl: AES による暗号化
const sjcl = require('sjcl');
const key = new sjcl.codec.utf8String.toBits("my-secret-key");
const plaintext = "sensitive data";
// 暗号化(ビット列として処理)
const ciphertext = sjcl.encrypt(key, plaintext);
// 復号化
const decrypted = sjcl.decrypt(key, ciphertext);
console.log('復号結果:', decrypted);
API はビット列(BitArray)を基本単位としており、crypto-js のような文字列ベースの直感的な操作とは少し勝手が異なります。これは、開発者に暗号の基礎的な理解を促す設計とも言えます。機能は AES、SHA-256、HMAC などに絞られており、「必要十分な機能だけを、最も安全に実装する」という方針が貫かれています。
それぞれのライブラリの特徴を踏まえ、具体的なシナリオごとに最適な選択をまとめます。
| シナリオ | 推奨ライブラリ | 理由 |
|---|---|---|
| パスワードの保存 | bcrypt | ソルト管理、コスト調整、タイミング攻撃対策が自動化されており、この目的専用の最適解だから。 |
| Node.js サーバーでの汎用暗号化 | crypto | 標準搭載で最速、OpenSSL ベースの信頼性、追加依存なしで済むため。 |
| ブラウザでの手軽な暗号化 | crypto-js | API がシンプルで導入が容易。一般的な AES やハッシュ用途であれば十分すぎる機能を持つため。 |
| ブラウザでの証明書/PKI 操作 | node-forge | TLS や ASN.1 など、他のライブラリがサポートしていない高度なプロトコルを扱える唯一の選択肢だから。 |
| 極めて高いセキュリティ要件 | sjcl | 学術的に監査された実装であり、セキュリティリスクを理論的に最小化したい場合に最適だから。 |
暗号化ライブラリの選択は、単に「機能があるか」だけでなく、「どこで動かすか(Node.js かブラウザか)」と「何を保護したいか(パスワードか通信データか)」によって決まります。
bcrypt です。crypto を使いこなしましょう。crypto-js がバランス良く、証明書などの特殊操作が必要なら node-forge が不可欠です。sjcl の堅牢な実装が頼りになります。セキュリティは「運」で守るものではありません。適切なツールを選び、その設計思想を理解して使うことが、堅牢なアプリケーション構築への第一歩です。
パスワードのハッシュ化と検証のみが必要な場合、特に Node.js サーバー環境では bcrypt を選択すべきです。ソルト生成やコストファクターの管理が自動化されており、タイミング攻撃に対する耐性も備えています。他の汎用暗号化ライブラリでパスワード処理を自作するのは危険であり、この専用ライブラリ一択です。
Node.js サーバーサイドで開発しており、AES、RSA、ハッシュ関数など多様な暗号化プリミティブを最高性能で利用したい場合は、組み込みの crypto モジュールを使用します。追加インストールが不要で、OS のネイティブ機能を利用するため信頼性と速度の面で優れています。ただし、ブラウザでは利用できないため、ユニバーサルコードには不向きです。
ブラウザ環境で動作し、AES や SHA などの標準アルゴリズムを手軽に使いたい場合に crypto-js が適しています。API が直感的で学習コストが低く、ドキュメントも充実しています。ただし、メンテナンス頻度は他のライブラリに比べて低く、最新の暗号標準への追従が遅れる可能性があるため、重要なシステムでは慎重な評価が必要です。
ブラウザと Node.js の両方で動作し、TLS/SSL、PKI、ASN.1 といった高度なプロトコルや証明書操作までサポートが必要な場合は node-forge を採用します。機能の幅が非常に広く、純粋な JavaScript で書かれているため環境を選びません。その分ライブラリサイズは大きくなりますが、複雑なセキュリティ要件を満たす唯一の選択肢となることが多いです。
セキュリティ上のリスクを最小限に抑えるため、数学的に証明された堅牢な実装のみを必要とする場合に sjcl (Stanford JavaScript Crypto Library) が推奨されます。スタンフォード大学によって監査されており、実装の正しさが重視されます。機能は基本的なものに絞られており、使いやすさよりも「正しさ」を優先するプロジェクトに向いています。
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.