Hmac 类


Hmac 类是一个实用工具,用于创建加密的 HMAC 摘要。 它可以通过以下两种方式之一使用:

  • 作为可读写的,其中写入数据以在可读侧生成计算后的 HMAC 摘要。
  • 使用 hmac.update()hmac.digest() 方法生成计算后的 HMAC 摘要。

crypto.createHmac() 方法用于创建 Hmac 实例。 不能使用 new 关键字直接地创建 Hmac 对象。

示例,使用 Hmac 对象作为流:

const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', '密钥');

hmac.on('readable', () => {
  // 哈希流只会生成一个元素。
  const data = hmac.read();
  if (data) {
    console.log(data.toString('hex'));
    // 打印:
    //   d0b5490ab4beb8e6545fe284f484d0d595e46086cb8e6ef2291af12ac684102f
  }
});

hmac.write('要创建哈希的数据');
hmac.end();

示例,使用 Hmac 和管道流:

const crypto = require('crypto');
const fs = require('fs');
const hmac = crypto.createHmac('sha256', '密钥');

const input = fs.createReadStream('要创建哈希的数据.txt');
input.pipe(hmac).pipe(process.stdout);

示例,使用 hmac.update()hmac.digest() 方法:

const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', '密钥');

hmac.update('要创建哈希的数据');
console.log(hmac.digest('hex'));
// 打印:
//   d0b5490ab4beb8e6545fe284f484d0d595e46086cb8e6ef2291af12ac684102f

The Hmac class is a utility for creating cryptographic HMAC digests. It can be used in one of two ways:

  • As a stream that is both readable and writable, where data is written to produce a computed HMAC digest on the readable side, or
  • Using the hmac.update() and hmac.digest() methods to produce the computed HMAC digest.

The crypto.createHmac() method is used to create Hmac instances. Hmac objects are not to be created directly using the new keyword.

Example: Using Hmac objects as streams:

const crypto = require('crypto');
const hmac = crypto.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();

Example: Using Hmac and piped streams:

const crypto = require('crypto');
const fs = require('fs');
const hmac = crypto.createHmac('sha256', 'a secret');

const input = fs.createReadStream('test.js');
input.pipe(hmac).pipe(process.stdout);

Example: Using the hmac.update() and hmac.digest() methods:

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

hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e