菜单
文档breadcrumb arrow Grafana k6breadcrumb arrow JavaScript APIbreadcrumb arrow k6/cryptobreadcrumb arrow hmac( algorithm, secret, data, outputEncoding )
开源

hmac( algorithm, secret, data, outputEncoding )

注意

存在一个提供更好、更标准 API 的模块。

crypto 模块部分实现了 WebCrypto API,它比 k6/crypto 支持更多特性。

使用 HMAC 来使用共享密钥对一段数据进行签名。

参数类型描述
algorithmstring要使用的哈希算法。可以是 md4, md5, sha1, sha256, sha384, sha512, sha512_224, sha512_256ripemd160 中的一个。
secretstring / ArrayBuffer用于对数据签名的共享密钥。
datastring / ArrayBuffer要签名的数据。
outputEncodingstring描述用于哈希值的编码类型。可以是 "base64", "base64url", "base64rawurl", "hex" 或 "binary"。

返回值

类型描述
string / Array哈希摘要(对于 "base64", "base64url", "base64rawurl", "hex" outputEncoding)或原始整数数组(对于 "binary" outputEncoding)。

示例

JavaScript
import crypto from 'k6/crypto';

export default function () {
  let hash = crypto.hmac('sha256', 'mysecret', 'hello world!', 'hex');
  console.log(hash);
  const binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
  hash = crypto.hmac('sha256', 'mysecret', new Uint8Array(binArray).buffer, 'hex');
  console.log(hash);
}

以上脚本在执行时应打印以下内容

bash
INFO[0000] 893a72d8cab129e5ba85aea4599fd53f59bfe652cff4098a3780313228d8c20f
INFO[0000] 893a72d8cab129e5ba85aea4599fd53f59bfe652cff4098a3780313228d8c20f