crypto.createHmac(algorithm, key[, options])
algorithm<string>key<string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>options<Object>stream.transform选项encoding<string> 当key是字符串时使用的字符串编码。
- 返回:<Hmac>
创建并返回一个使用指定 algorithm 和 key 的 Hmac 对象。可选的 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。如果它是一个字符串,请考虑 将字符串用作加密 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}`);
}
});