crypto.createHmac(algorithm, key[, options])
-
algorithm<string> -
key<string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey> -
options<Object>stream.transform选项¥
options<Object>stream.transformoptions -
返回:<Hmac>
¥Returns: <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}`);
}
});