Node.jsでSHA256ハッシュ値生成
Windows 10Node.js v8.10.0
もくじ
Crypto | Node.js v12.9.0 Documentation
SHA256ハッシュ生成
const crypto = require('crypto');
const str = 'kiriukun.com';
const hashHex = crypto.createHash('sha256').update(str, 'utf8').digest('hex');
console.log(hashHex);
9dfb421400e94ca00b7b2f3e279744254d5ab011d9b7bfb0a7e329a1b307286f
hexってなに?
Buffer
に指定できる encoding
のひとつ (他にも base64
とかある)
hash.digest()
が返す Buffer
をまんま文字列にしたもの
const crypto = require('crypto');
const str = 'kiriukun.com';
const hashBuf = crypto.createHash('sha256').update(str, 'utf8').digest();
console.log(hashBuf);
<Buffer 9d fb 42 14 00 e9 4c a0 0b 7b 2f 3e 27 97 44 25 4d 5a b0 11 d9 b7 bf b0 a7 e3 29 a1 b3 07 28 6f>
好きなファイルのSHA256ハッシュ値を計算してみよう
hash.update()
の第一引数には Buffer
も渡せる
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const buf = fs.readFileSync(path.resolve(__dirname, './path/to/file'));
const hashHex = crypto.createHash('sha256').update(buf, 'utf8').digest('hex');
console.log(hashHex);
使用可能なハッシュアルゴリズムの確認
SHA256以外にもいろいろあるよ
const crypto = require('crypto');
console.log( crypto.getHashes() );
[ 'DSA',
'DSA-SHA',
'DSA-SHA1',
'DSA-SHA1-old',
'RSA-MD4',
'RSA-MD5',
'RSA-MDC2',
'RSA-RIPEMD160',
'RSA-SHA',
'RSA-SHA1',
'RSA-SHA1-2',
'RSA-SHA224',
'RSA-SHA256',
'RSA-SHA384',
'RSA-SHA512',
'dsaEncryption',
'dsaWithSHA',
'dsaWithSHA1',
'dss1',
'ecdsa-with-SHA1',
'md4',
'md4WithRSAEncryption',
'md5',
'md5WithRSAEncryption',
'mdc2',
'mdc2WithRSA',
'ripemd',
'ripemd160',
'ripemd160WithRSA',
'rmd160',
'sha',
'sha1',
'sha1WithRSAEncryption',
'sha224',
'sha224WithRSAEncryption',
'sha256',
'sha256WithRSAEncryption',
'sha384',
'sha384WithRSAEncryption',
'sha512',
'sha512WithRSAEncryption',
'shaWithRSAEncryption',
'ssl2-md5',
'ssl3-md5',
'ssl3-sha1',
'whirlpool' ]