hmac( algorithm, secret, data, outputEncoding )
注意
存在一个提供更好、更标准 API 的模块。
crypto 模块部分实现了 WebCrypto API,它比 k6/crypto 支持更多特性。
使用 HMAC 来使用共享密钥对一段数据进行签名。
| 参数 | 类型 | 描述 |
|---|---|---|
| algorithm | string | 要使用的哈希算法。可以是 md4, md5, sha1, sha256, sha384, sha512, sha512_224, sha512_256 或 ripemd160 中的一个。 |
| secret | string / ArrayBuffer | 用于对数据签名的共享密钥。 |
| data | string / ArrayBuffer | 要签名的数据。 |
| outputEncoding | string | 描述用于哈希值的编码类型。可以是 "base64", "base64url", "base64rawurl", "hex" 或 "binary"。 |
返回值
| 类型 | 描述 |
|---|---|
| string / Array | 哈希摘要(对于 "base64", "base64url", "base64rawurl", "hex" outputEncoding)或原始整数数组(对于 "binary" outputEncoding)。 |
示例
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);
}以上脚本在执行时应打印以下内容
INFO[0000] 893a72d8cab129e5ba85aea4599fd53f59bfe652cff4098a3780313228d8c20f
INFO[0000] 893a72d8cab129e5ba85aea4599fd53f59bfe652cff4098a3780313228d8c20f

