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


创建并返回一个使用指定 algorithm 和 key 的 Hmac 对象。可选的 options 参数用于控制流的行为。

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

可用的算法取决于平台上 OpenSSL 的版本和配置。例子有 'sha256' 和 'sha512'。 crypto.getHashes() 列出了哈希 API 可用的算法,但 HMAC 有额外的限制,所以并不是每个列出的算法都适用。

🌐 The available algorithms depend on the version and configuration of OpenSSL on the platform. Examples are 'sha256' and 'sha512'. crypto.getHashes() lists algorithms available to the hashing APIs, but HMAC imposes additional restrictions, so not every listed algorithm is suitable.

key 是用于生成加密 HMAC 哈希的 HMAC 密钥。如果它是 KeyObject,则其类型必须为 secret。如果它是一个字符串,请考虑 将字符串用作加密 API 输入时的注意事项。如果它是从密码学安全的熵源获取的,例如 crypto.randomBytes() 或 crypto.generateKey(),其长度不应超过 algorithm 的块大小(例如,对于 SHA-256 为 512 位)。

🌐 The key is the HMAC key used to generate the cryptographic HMAC hash. If it is a KeyObject, its type must be secret. If it is a string, please consider caveats when using strings as inputs to cryptographic APIs. If it was obtained from a cryptographically secure source of entropy, such as crypto.randomBytes() or crypto.generateKey(), its length should not exceed the block size of algorithm (e.g., 512 bits for SHA-256).

示例:生成文件的 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}`);
  }
});