crypto.createHmac(algorithm, key[, options])


创建并返回使用给定的 algorithmkeyHmac 对象。 可选的 options 参数控制流的行为。

algorithm 取决于平台上 OpenSSL 版本支持的可用算法。 例如 'sha256''sha512' 等。 在 OpenSSL 的最新版本中,openssl list -digest-algorithms(在 OpenSSL 的旧版本中为 openssl list-message-digest-algorithms)将显示可用的摘要算法。

key 是用于生成加密 HMAC 哈希的 HMAC 密钥。 如果是 KeyObject,则其类型必须是 secret

示例:生成文件的 sha256 HMAC

const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');

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

const input = fs.createReadStream(filename);
input.on('readable', () => {
  // 哈希流只生成
  // 一个元素。
  const data = input.read();
  if (data)
    hmac.update(data);
  else {
    console.log(`${hmac.digest('hex')} ${filename}`);
  }
});

Creates and returns an Hmac object that uses the given algorithm and key. Optional options argument controls stream behavior.

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms (openssl list-message-digest-algorithms for older versions of OpenSSL) will display the available digest algorithms.

The key is the HMAC key used to generate the cryptographic HMAC hash. If it is a KeyObject, its type must be secret.

Example: generating the sha256 HMAC of a file

const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');

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

const input = fs.createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hmac.update(data);
  else {
    console.log(`${hmac.digest('hex')} ${filename}`);
  }
});