Nodeのcryptoモジュールで AES algorithmの暗号・復号
例えば秘密鍵が 123456789key で、Hello worldという文字列を暗号・復号すると下記のようになる。
var crypto = require('crypto'); var secretKey = '123456789key'; var text = 'Hello world'; var hash = crypto.createHash('md5'); hash.update(secretKey, 'utf8'); var key = hash.digest(); hash = crypto.createHash('md5'); hash.update(secretKey + 'randomToken'); var ive = hash.digest(); var cipher = crypto.createCipheriv('aes-128-cbc', key, ive); var crypted = cipher.update(text, 'utf8', 'hex'); crypted += cipher.final('hex'); console.log('暗号結果: ' + crypted); var decipher = crypto.createDecipheriv('aes-128-cbc', key, ive); var dec = decipher.update(crypted, 'hex', 'utf8'); dec += decipher.final('utf8'); console.log('復号結果: ' + dec);
cipher.update と decipher.update とで引数の input/outputが逆になるのが注意。
また、ivとはCBCモードで必要になるinitialization vector (初期化ベクトル)のこと。
暗号ブロックを使い回して暗号処理をするCBCでは、初期化の値が必要なのでそれを用意してあげる。
このivは第3者に見られても問題はない。
- 作者: David Mark Clements,和田祐一郎
- 出版社/メーカー: オライリージャパン
- 発売日: 2013/02/23
- メディア: 大型本
- 購入: 2人 クリック: 4回
- この商品を含むブログ (5件) を見る