Node.jsのcryptoモジュールでハッシュ化を行う
Node.jsで文字列をハッシュ化する
cryptoモジュールを使う
モジュールのインポート
まず、crypto
モジュールをインポートする必要があります。
const crypto = require('crypto');
ハッシュアルゴリズムの選択
次に、使用するハッシュアルゴリズムを選択します。代表的なアルゴリズムは以下の通りです。
'sha256'
:256ビット長のハッシュ値を生成
ハッシュオブジェクトの作成
ハッシュアルゴリズムを選択したら、ハッシュオブジェクトを作成します。
const hash = crypto.createHash('sha256');
文字列のハッシュ化
ハッシュオブジェクトに文字列を更新し、ハッシュ値を生成します。
hash.update('ハッシュ化したい文字列');
const hashValue = hash.digest('hex');
ハッシュ値の出力
生成されたハッシュ値は、16進文字列で出力されます。
console.log(hashValue); // 例: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
その他のハッシュ化方法
crypto-js
ライブラリを使う
ハッシュ化の用途
- パスワードの保存
- データの改ざん防止
- ファイルの重複チェック
注意点
- ハッシュ化は不可逆変換です。ハッシュ値から元の文字列を復元することはできません。
- ハッシュ衝突が起こる可能性があります。異なる文字列が同じハッシュ値になることです。
const crypto = require('crypto');
// パスワードのハッシュ化
const password = 'password123';
const salt = 'somesalt';
const hash = crypto.createHash('sha256');
hash.update(password + salt);
const hashedPassword = hash.digest('hex');
console.log(hashedPassword); // 例: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
// ファイルのハッシュ化
const fs = require('fs');
const filePath = './sample.txt';
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(filePath);
stream.on('data', (data) => {
hash.update(data);
});
stream.on('end', () => {
const fileHash = hash.digest('hex');
console.log(fileHash); // 例: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
});
- ハッシュアルゴリズムは、用途に応じて適切なものを選択してください。
- ハッシュ化された文字列は、安全な場所に保管してください。
Node.jsで文字列をハッシュ化する他の方法
crypto-js
ライブラリは、さまざまなハッシュアルゴリズムを実装したライブラリです。
const CryptoJS = require('crypto-js');
const hashValue = CryptoJS.SHA256('ハッシュ化したい文字列').toString();
console.log(hashValue); // 例: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
bcryptjs
ライブラリは、パスワードのハッシュ化に特化したライブラリです。
const bcrypt = require('bcryptjs');
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync('password123', salt);
console.log(hashedPassword); // 例: '$2a$10$e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
各方法の比較
方法 | メリット | デメリット |
---|---|---|
crypto モジュール | 標準ライブラリなのでインストール不要 | アルゴリズムの種類が少ない |
crypto-js ライブラリ | アルゴリズムの種類が多い | 標準ライブラリではないのでインストールが必要 |
bcryptjs ライブラリ | パスワードのハッシュ化に特化している | 他の用途には使いにくい |
Node.jsで文字列をハッシュ化する方法はいくつかあります。それぞれの特徴を理解して、用途に合った方法を選択してください。
hash node.js