bcrypt vs crypto-js vs md5 vs sha1 vs sha256
JavaScript におけるハッシュ関数と暗号化ライブラリの選定ガイド
bcryptcrypto-jsmd5sha1sha256類似パッケージ:

JavaScript におけるハッシュ関数と暗号化ライブラリの選定ガイド

bcryptcrypto-jsmd5sha1sha256 は、JavaScript アプリケーションでデータ整合性の確認やパスワード保護のために使用される主要なパッケージです。bcrypt はパスワードハッシュ化に特化しており、crypto-js は多様な暗号アルゴリズムを提供する包括的なライブラリです。一方、md5sha1sha256 は特定のハッシュアルゴリズムに焦点を当てた軽量パッケージです。ただし、セキュリティの観点から、各アルゴリズムの強度と使用目的(パスワード保存かデータ整合性か)を明確に区別する必要があります。

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
bcrypt07,7991.11 MB331年前MIT
crypto-js016,389487 kB2793年前MIT
md5091421.4 kB13-BSD-3-Clause
sha10107-011年前BSD-3-Clause
sha256048-411年前-

JavaScript におけるハッシュ関数と暗号化ライブラリの選定ガイド:bcrypt, crypto-js, md5, sha1, sha256

JavaScript エコシステムには、ハッシュ化や暗号化を行うための多くのパッケージが存在しますが、その目的とセキュリティ強度は大きく異なります。bcryptcrypto-jsmd5sha1sha256 を比較し、実際の開発現場でどのように使い分けるべきかを解説します。

🔒 主な用途とセキュリティ強度

各パッケージが提供するアルゴリズムは、目的によって明確に区別する必要があります。パスワード保存、データ整合性、暗号化のいずれに使うかで選定が分かれます。

bcrypt はパスワードハッシュ化のために設計されたソルト付きハッシュ関数です。

  • 計算コストを調整できるため、ブルートフォース攻撃に強いです。
  • 主にサーバーサイド(Node.js)で使用されます。
// bcrypt: パスワードのハッシュ化 (Node.js)
const bcrypt = require('bcrypt');
const saltRounds = 10;
const password = 'mySecurePassword';

const hash = await bcrypt.hash(password, saltRounds);
// 検証
const match = await bcrypt.compare(password, hash);

crypto-js は、MD5、SHA-1、SHA-256、AES などを含む包括的な暗号ライブラリです。

  • ブラウザと Node.js の両方で動作します。
  • 特定のアルゴリズムだけを使いたい場合でも、ライブラリ全体をインポートする必要がある場合があります。
// crypto-js: SHA256 ハッシュ化
const CryptoJS = require('crypto-js');
const message = 'Hello World';

const hash = CryptoJS.SHA256(message).toString();

md5 は高速なハッシュ関数ですが、セキュリティ的には破綻しています。

  • 衝突耐性が低く、パスワード保存には使用できません。
  • チェックサムやキャッシュキー生成などに限定して使用します。
// md5: 簡易ハッシュ化
const md5 = require('md5');
const input = 'data_to_hash';

const hash = md5(input);

sha1 も同様に、現在はセキュリティ用途には推奨されません。

  • Git などのバージョン管理システム内部で使用されていますが、新しいセキュリティ設計には避けるべきです。
// sha1: 簡易ハッシュ化
const sha1 = require('sha1');
const input = 'data_to_hash';

const hash = sha1(input);

sha256 は、現在広く推奨される安全なハッシュアルゴリズムです。

  • 仮想通貨(ビットコインなど)やデータ整合性確認に使用されます。
  • パスワード保存にはソルトが必要ですが、一般データのハッシュ化には最適です。
// sha256: 安全なハッシュ化
const sha256 = require('sha256');
const input = 'data_to_hash';

const hash = sha256(input);

🌐 実行環境:サーバーサイド vs フロントエンド

パッケージの選択は、コードがどこで実行されるかによって大きく制約を受けます。

bcrypt はネイティブアドオン(C++)に依存しているため、ブラウザでの使用は困難です。

  • Webpack や Vite でのバンドル時にエラーが発生しやすいです。
  • フロントエンドで同等の機能が必要な場合は、純粋な JavaScript 実装である bcryptjs を検討します。
// bcrypt: Node.js 環境専用
// ブラウザでは動作しない可能性が高い
const bcrypt = require('bcrypt'); 

crypto-js は純粋な JavaScript で書かれているため、環境を選びません。

  • フロントエンドで暗号化処理(例:エンドツーエンド暗号化)が必要な場合に適しています。
// crypto-js: 環境を選ばない
const CryptoJS = require('crypto-js');
// ブラウザでも Node.js でも動作

md5sha1sha256 の各パッケージも、基本的に純粋な JavaScript 実装または軽量ラッパーです。

  • フロントエンドでのデータ整合性チェックに適しています。
// sha256: 環境を選ばない
const sha256 = require('sha256');
// 軽量でバンドルサイズへの影響も比較的少ない

⚠️ 非推奨とセキュリティリスク

セキュリティの進化に伴い、一部のアルゴリズムは使用を避けるべきです。

md5sha1 は、衝突攻撃が実証されており、セキュリティ用途では非推奨です。

  • 悪意のある第三者が同じハッシュ値を持つ別のデータを作成できる可能性があります。
  • 新規プロジェクトでのパスワード保存や署名には使用しないでください。
// 非推奨: セキュリティ用途に使用しない
const md5 = require('md5');
const hash = md5(password); // ❌ 危険

bcryptsha256crypto-js (SHA256 使用時) は、現時点で安全とされています。

  • ただし、bcrypt はパスワード専用であり、sha256 はデータ整合性専用という役割分担があります。
// 推奨: 目的に合わせた使用
const bcrypt = require('bcrypt'); // パスワード用
const sha256 = require('sha256'); // データ整合性用

📦 機能比較と API の使いやすさ

各パッケージは API デザインが異なり、開発体験(DX)に影響します。

bcrypt は非同期処理を前提とした API を提供します。

  • Promise ベースまたはコールバックベースで使用できます。
  • ソルトの生成からハッシュ化までを内部で処理するため、実装ミスが起きにくいです。
// bcrypt: 非同期 API
await bcrypt.hash(password, 10);

crypto-js はオブジェクト指向的なチェーン処理をサポートします。

  • 複数のアルゴリズムに統一されたインターフェースを提供します。
  • 設定オプション(例:イテレーション数)を細かく制御できます。
// crypto-js: チェーン処理
CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });

md5sha1sha256 は単一関数呼び出しが基本です。

  • 引数に文字列またはバッファを渡して、ハッシュ値(文字列)を受け取ります。
  • 学習コストが低く、すぐに導入できます。
// sha256: 同期関数
const hash = sha256('message');

🤝 共通点:データ変換と出力形式

これらのライブラリは、入力データを固定長の文字列に変換するという点で共通しています。

1. 📝 入力データの扱い

  • すべて文字列またはバッファ(Buffer)を受け取ります。
  • Unicode 処理についてはライブラリによって挙動が異なる場合があるため、テストが必要です。
// どのパッケージも文字列を入力として受け取る
const input = '日本語テキスト';
// bcrypt, crypto-js, md5, sha1, sha256 すべてで処理可能

2. 🔢 出力形式

  • 通常は 16 進数(Hex)文字列として出力されます。
  • crypto-js などは Base64 出力などもサポートしています。
// crypto-js: 出力形式の選択
const hashHex = CryptoJS.SHA256('msg').toString();
const hashBase64 = CryptoJS.SHA256('msg').toString(CryptoJS.enc.Base64);

3. 🛡️ ソルトの必要性

  • bcrypt は自動的にソルトを生成します。
  • sha256 などはソルトを自分で管理する必要があります。
// bcrypt: 自動ソルト
const hash = await bcrypt.hash(password, 10);

// sha256: 手動ソルト管理が必要
const salt = generateRandomSalt();
const hash = sha256(salt + password);

📊 選定サマリー

特徴bcryptcrypto-jsmd5sha1sha256
主用途パスワード保存多目的暗号チェックサムレガシー互換データ整合性
セキュリティ🔒 高🔒 高 (アルゴリズム依存)❌ 低❌ 低🔒 高
実行環境Node.js汎用汎用汎用汎用
速度遅い (故意)普通高速高速普通
ソルト管理自動手動手動手動手動
推奨度✅ パスワード用✅ 多機能用⚠️ 制限付き⚠️ 制限付き✅ 一般用

💡 最終的な推奨事項

プロジェクトの要件に応じて、以下のように選択してください。

bcrypt は、ユーザーのパスワードをデータベースに保存する必要がある場合の唯一の正解です(Node.js 環境)。フロントエンドでハッシュ化してから送信するのはセキュリティ的に意味がないため、必ず HTTPS 経由で生パスワードを送り、サーバーで bcrypt 処理を行ってください。

crypto-js は、ブラウザ上でデータを暗号化したい場合(例:クライアントサイド暗号化ストレージ)や、複数のアルゴリズムをまとめて管理したい場合に便利です。

sha256 は、ファイルの改ざん検知や、パスワード以外の機密データのハッシュ化に使用します。現代的な標準です。

md5sha1 は、既存システムとの互換性維持以外での使用は避けてください。セキュリティリスクが高すぎます。

重要な注意点: フロントエンドでのパスワードハッシュ化は、通信経路の保護(HTTPS)の代わりにはなりません。中間者攻撃のリスクがあるため、認証にはサーバーサイドでの処理が不可欠です。

選び方: bcrypt vs crypto-js vs md5 vs sha1 vs sha256

  • bcrypt:

    パスワードを安全に保存する必要があるサーバーサイド Node.js アプリケーションでは bcrypt を選択します。ただし、これはネイティブモジュールを含むため、フロントエンドバンドルには適していません。ブラウザ環境では bcryptjs の使用を検討してください。

  • crypto-js:

    複数の暗号機能(AES, SHA, MD5 など)を単一の依存関係で管理したい場合や、ポリフィルとしてブラウザで暗号処理が必要な場合に選択します。包括的ですが、コードサイズが大きくなる点に注意が必要です。

  • md5:

    セキュリティが不要なデータ整合性チェック(例:ファイルの破損検知)や、レガシーシステムとの互換性が必要な場合にのみ使用します。パスワードや機密データには絶対に使用しないでください。

  • sha1:

    Git のハッシュ計算など、衝突耐性がセキュリティクリティカルでない用途、または古いシステムとの互換性維持のために使用します。セキュリティ用途では推奨されません。

  • sha256:

    データ整合性やデジタル署名など、現代的なセキュリティ基準を満たすハッシュ化が必要な場合に選択します。パスワード保存には bcryptargon2 の方が適していますが、一般データのハッシュ化には最適です。

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.