当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Node.js crypto.createHmac(algorithm, key[, options])用法及代码示例

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

历史
版本变化
v15.0.0

key 也可以是ArrayBuffer 或 CryptoKey。添加了编码选项。 key 不能包含超过 2 ** 32 - 1 个字节。

v11.6.0

key 参数现在可以是 KeyObject

v0.1.94

添加于:v0.1.94


参数

创建并返回使用给定 algorithmkeyHmac 对象。可选的 options 参数控制流行为。

algorithm 取决于平台上OpenSSL 版本支持的可用算法。例如 'sha256''sha512' 等。在 OpenSSL 的最新版本中,openssl list -digest-algorithms 将显示可用的摘要算法。

key 是用于生成加密 HMAC 哈希的 HMAC key 。如果是 KeyObject ,则其类型必须是 secret

示例:生成文件的 sha256 HMAC

import {
  createReadStream
} from '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}`);
  }
});

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 crypto.createHmac(algorithm, key[, options])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。