HMAC 消息认证码
HMAC(Hash-based Message Authentication Code,基于哈希的消息认证码)是一种利用密钥和哈希算法生成消息摘要的技术,常用于校验数据在传输过程中是否被篡改,或用于接口签名。
说明:HMAC 与普通哈希(如
hasher)的区别在于引入了密钥,只有持有相同密钥的一方才能够计算出相同的结果。
hmac.compute(text, key[, algorithm[, outputEncoding]])
新增于:Hamibot 1.7.3
使用指定的算法计算 HMAC 摘要。
参数
| 名称 | 类型 | 描述 |
|---|---|---|
text | string | byte[] | 要计算摘要的文本;也可直接传入字节数组 |
key | string | byte[] | 密钥;也可直接传入字节数组 |
algorithm | string | 算法,默认为 sha256。支持 md5 / sha1 / sha224 / sha256 / sha384 / sha512,也可直接传入原生算法名(如 HmacSHA256) |
outputEncoding | string | 输出编码,默认为十六进制(小写);传入 base64 时输出 Base64 字符串 |
返回值
| 类型 | 描述 |
|---|---|
| string | HMAC 摘要字符串 |
示例
js
var key = 'mySecretKey12345';
var text = 'Hello Hamibot!';
// 默认使用 sha256,输出十六进制
log(hmac.compute(text, key)); // => 十六进制字符串
// 指定算法与输出编码
log(hmac.compute(text, key, 'sha1', 'base64')); // => Base64 字符串
hamibot.exit();hmac.verify(text, key, expected[, algorithm[, outputEncoding]])
新增于:Hamibot 1.7.3
校验 HMAC 摘要是否与预期值一致,内部采用常量时间比较,避免时序攻击。
参数
| 名称 | 类型 | 描述 |
|---|---|---|
text | string | byte[] | 要计算摘要的文本 |
key | string | byte[] | 密钥 |
expected | string | 预期的摘要值 |
algorithm | string | 算法,默认为 sha256,同 hmac.compute |
outputEncoding | string | 输出编码,默认为十六进制;传入 base64 时按 Base64 比较 |
返回值
| 类型 | 描述 |
|---|---|
| boolean | 一致返回 true,否则 false |
示例
js
var key = 'mySecretKey12345';
var text = 'Hello Hamibot!';
var digest = hmac.compute(text, key);
log(hmac.verify(text, key, digest)); // => true
log(hmac.verify(text, key, 'invalid')); // => false
hamibot.exit();快捷方法
新增于:Hamibot 1.7.3
以下方法等价于 hmac.compute 并固定了算法,签名均为 (text, key[, outputEncoding]):
| 方法 | 等价算法 |
|---|---|
hmac.md5(text, key[, encoding]) | HmacMD5 |
hmac.sha1(text, key[, encoding]) | HmacSHA1 |
hmac.sha224(text, key[, encoding]) | HmacSHA224 |
hmac.sha256(text, key[, encoding]) | HmacSHA256 |
hmac.sha384(text, key[, encoding]) | HmacSHA384 |
hmac.sha512(text, key[, encoding]) | HmacSHA512 |
示例
js
var key = 'mySecretKey12345';
var text = 'Hello Hamibot!';
log(hmac.sha256(text, key)); // => 十六进制
log(hmac.sha256(text, key, 'base64')); // => Base64
log(hmac.md5(text, key)); // => 十六进制
hamibot.exit();