类:Hmac
¥Class: Hmac
-
¥Extends: <stream.Transform>
Hmac
类是用于创建加密 HMAC 摘要的实用工具。它可以通过以下两种方式之一使用:
¥The Hmac
class is a utility for creating cryptographic HMAC digests. It can
be used in one of two ways:
-
作为可读可写的 流,写入数据以在可读端生成计算的 HMAC 摘要,或者
¥As a stream that is both readable and writable, where data is written to produce a computed HMAC digest on the readable side, or
-
使用
hmac.update()
和hmac.digest()
方法生成计算出的 HMAC 摘要。¥Using the
hmac.update()
andhmac.digest()
methods to produce the computed HMAC digest.
crypto.createHmac()
方法用于创建 Hmac
实例。Hmac
对象不能直接使用 new
关键字创建。
¥The crypto.createHmac()
method is used to create Hmac
instances. Hmac
objects are not to be created directly using the new
keyword.
示例:使用 Hmac
对象作为流:
¥Example: Using Hmac
objects as streams:
const {
createHmac
} = await import('node:crypto');
const hmac = createHmac('sha256', 'a secret');
hmac.on('readable', () => {
// Only one element is going to be produced by the
// hash stream.
const data = hmac.read();
if (data) {
console.log(data.toString('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
}
});
hmac.write('some data to hash');
hmac.end();
const {
createHmac,
} = require('node:crypto');
const hmac = createHmac('sha256', 'a secret');
hmac.on('readable', () => {
// Only one element is going to be produced by the
// hash stream.
const data = hmac.read();
if (data) {
console.log(data.toString('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
}
});
hmac.write('some data to hash');
hmac.end();
示例:使用 Hmac
和管道流:
¥Example: Using Hmac
and piped streams:
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const {
createHmac
} = await import('node:crypto');
const hmac = createHmac('sha256', 'a secret');
const input = createReadStream('test.js');
input.pipe(hmac).pipe(stdout);
const {
createReadStream,
} = require('node:fs');
const {
createHmac,
} = require('node:crypto');
const { stdout } = require('node:process');
const hmac = createHmac('sha256', 'a secret');
const input = createReadStream('test.js');
input.pipe(hmac).pipe(stdout);
示例:使用 hmac.update()
和 hmac.digest()
方法:
¥Example: Using the hmac.update()
and hmac.digest()
methods:
const {
createHmac
} = await import('node:crypto');
const hmac = createHmac('sha256', 'a secret');
hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
const {
createHmac,
} = require('node:crypto');
const hmac = createHmac('sha256', 'a secret');
hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e