哈希器
注意
存在一个具有更好、更标准 API 的模块。
crypto 模块 部分实现了 WebCrypto API,支持的功能比 k6/crypto 更多。
此对象由 crypto.createHash() 返回,允许用户连续添加更多字符串数据进行哈希处理,并在过程中提取摘要。
名称 | 类型 | 描述 |
---|---|---|
Hasher.update(string) | 函数 | 向我们要创建哈希的字符串添加更多数据。接受一个字符串参数,即要添加的新数据。 |
Hasher.digest(string) | 函数 | 返回到目前为止添加到 Hasher 对象的数据(使用 update() )的摘要。接受一个字符串参数,即要返回的编码格式。可以是“base64”、“base64url”、“base64rawurl”、“hex”或“binary”。详情请参阅下面的示例。 |
示例
import crypto from 'k6/crypto';
export default function () {
console.log(crypto.sha256('hello world!', 'hex'));
const hasher = crypto.createHash('sha256');
hasher.update('hello ');
hasher.update('world!');
console.log(hasher.digest('hex'));
// Other encodings
console.log('base64:', hasher.digest('base64'));
console.log('base64url:', hasher.digest('base64url'));
console.log('base64rawurl:', hasher.digest('base64rawurl'));
console.log('binary:', new Uint8Array(hasher.digest('binary')));
}
上述代码示例应在其输出中产生以下结果
INFO[0000] 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9
INFO[0000] 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9
INFO[0000] base64: dQnlvaDHYtK6x/kNdYtbImP6Acy8VCq1498WO+CObKk=
INFO[0000] base64url: dQnlvaDHYtK6x_kNdYtbImP6Acy8VCq1498WO-CObKk=
INFO[0000] base64rawurl: dQnlvaDHYtK6x_kNdYtbImP6Acy8VCq1498WO-CObKk
INFO[0000] binary: 117,9,229,189,160,199,98,210,186,199,249,13,117,139,91,34,99,250,1,204,188,84,42,181,227,223,22,59,224,142,108,169