跳转到内容

HMAC

本页使用了标题或全文手工转换
维基百科,自由的百科全书
SHA-1 HMAC产生过程

HMAC (有时扩展为 英语:keyed-hash message authentication code, 密钥散列消息认证码, 或 英语:hash-based message authentication code,散列消息认证码),是一种通过特别计算方式之后产生的消息认证码(MAC),使用密码散列函数,同时结合一个加密密钥。它可以用来保证资料的完整性,同时可以用来作某个消息的身份验证。

定义

[编辑]

根据RFC 2104,HMAC的数学公式为: 𝐻𝑀𝐴𝐶(K,m)=H((K′⊕opad)||H((K′⊕ipad)||m))

其中:

H为密码散列函数(如SHA家族)
K为密钥(secret key)
m是要认证的消息
K'是从原始密钥K导出的另一个秘密密钥(如果K短于散列函数的输入块大小,则向右填充(Padding)零;如果比该块大小更长,则对K进行散列)
|| 代表串接
⊕ 代表异或(XOR)
opad 是外部填充(0x5c5c5c…5c5c,一段十六进制常量)
ipad 是内部填充(0x363636…3636,一段十六进制常量)

RFC 2104将底层杂凑函数的区块长度记为B、输出长度记为L;其建议HMAC密钥至少为L字节,并不鼓励使用短于L字节的密钥。超过B字节的密钥会先经底层杂凑函数处理。[1]

实现

[编辑]

下面的伪代码展示了如何实现HMAC。当使用以下散列函数之一时,块大小为64(字节):SHA-1、MD5、RIPEMD-128/160[2]。

 function hmac (key, message) {
    if (length(key) > blocksize) {
        key = hash(key) // keys longer than blocksize are shortened
    }
    if (length(key) < blocksize) {
        // keys shorter than blocksize are zero-padded (where ∥ is concatenation)
        key = key ∥ [0x00 * (blocksize - length(key))] // Where * is repetition.
    }
   
    o_key_pad = [0x5c * blocksize] ⊕ key // Where blocksize is that of the underlying hash function
    i_key_pad = [0x36 * blocksize] ⊕ key // Where ⊕ is exclusive or (XOR)
   
    return hash(o_key_pad ∥ hash(i_key_pad ∥ message)) // Where ∥ is concatenation
}

相关条目

[编辑]

参考文献

[编辑]
  1. ^ RFC 2104: HMAC: Keyed-Hashing for Message Authentication, Section 3. RFC Editor. 1997-02 [2026-10-04] (英语). 
  2. ^ RFC 2104, section 2, "Definition of HMAC", page 3.