at backyard

Color my life with the chaos of trouble.

Node.jsにおけるHMAC生成について

Node.jsでのHMAC生成方法

自分用の備忘録。下記のドキュメントを参考にした。

nodejs.org

まずは最も一般的かと思われるやり方

const crypto = require('crypto');

const secret = 'abcdefg';

const sampleText = 'I love cupcakes';
const hash = crypto.createHmac('sha256', secret)
                   .update(sampleText)
                   .digest('hex');
console.log(hash);
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e

stream を使ったやり方。
下記のようなやり方で実現できる

const crypto = require('crypto');

const secret = 'abcdefg';

const hmac = crypto.createHmac('sha256', secret);

const sampleText = 'I love cupcakes';

hmac.on('readable', () => {
  const data = hmac.read();
  if(data) {
    console.log(data.toString('hex'))
  }
});

hmac.on('error', function (err) {
    console.error(err);
    process.exit(1);
});

hmac.write(sampleText);
hmac.end();

下記のようなやり方でも実現できる

const crypto = require('crypto');

const secret = 'abcdefg';

const hmac = crypto.createHmac('sha256', secret);

const sampleText = 'I love cupcakes';

hmac.on('data', function (data) {
    console.log(data.toString('hex'));
});

hmac.on('error', function (err) {
    console.error(err);
    process.exit(1);
});

hmac.write(sampleText);
hmac.end();