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


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

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

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

¥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 will display the available digest algorithms.

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

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

示例:生成文件的 sha256 HMAC

¥Example: generating the sha256 HMAC of a file

import {
  createReadStream
} from 'node:fs';
import { argv } from 'node:process';
const {
  createHmac
} = await import('node:crypto');

const filename = argv[2];

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

const input = 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}`);
  }
});const {
  createReadStream,
} = require('node:fs');
const {
  createHmac,
} = require('node:crypto');
const { argv } = require('node:process');

const filename = argv[2];

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

const input = 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}`);
  }
});