HMAC (有时扩展为 , 金鑰雜湊訊息鑑別碼, 或 ,雜湊訊息鑑別碼),是一種通過特別計算方式之後產生的訊息鑑別碼(MAC),使用密碼雜湊函數,同時結合一個加密金鑰。它可以用來保證資料的完整性,同時可以用來作某個訊息的身份驗證。
定義
根據RFC 2104,HMAC的數學公式為:
\textit{HMAC}(K, m) = H \Bigl( (K' \oplus opad) \;||\; H \bigl( (K' \oplus ipad) \;||\; m \bigr) \Bigr)
其中:
:H為密碼雜湊函數(如SHA家族)
:K為密鑰(secret key)
:m是要认证的消息
:K是从原始密钥K*导出的另一个秘密密钥(如果K短于散列函数的输入块大小,则向右填充(Padding)零;如果比该块大小更长,则对K进行散列)
:|| 代表串接
:⊕ 代表異或(XOR)
:opad 是外部填充(0x5c5c5c…5c5c,一段十六进制常量)
: 是内部填充(0x363636…3636,一段十六进制常量)
实现
下面的伪代码展示了如何实现HMAC。当使用以下散列函数之一时,块大小为64(字节):SHA-1、MD5、RIPEMD-128/160。
function hmac (key, message) {
if (length(key) > blocksize) {
key = hash(key) // keys longer than blocksize are shortened
}
if (length(key) // 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
}
相關條目
*SHA家族
参考文献
评论 (0)