MAC 和 HMAC 的区别

MAC

message authentication code
the propurse of MAC is to verify the intergrity of the message

sender

  1. use the hash function to get H(m)
  2. concate message and H(m)
  3. send the H(m) + m to the receiver

receiver

  1. get the H(m) + mfrom the sender
  2. caculate the hash value of mH(m)
  3. compare whether the hash value from the sendr equal to the value we just caculate

MAC only can verify the intergrity of the data

HMAC

HMAC is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key. It may be used to simultaneously verify both the data integrity and
HMAC 是MAC的一个子集元素

HMAC能够同时确保数据的完整性以及数据的身份验证

MAC 和 HMAC 的区别
where
H is a cryptographic hash function
m is the message to be authenticated
K is the secret key
K’ is a block-sized key derived from the secret key, K; either by padding to the right with 0s up to the block size, or by hashing down to less than the block size first and then padding to the right with zeros
∥ denotes concatenation
⊕ denotes bitwise exclusive or (XOR)
opad is the block-sized outer padding, consisting of repeated bytes valued 0x5c
ipad is the block-sized inner padding, consisting of repeated bytes valued 0x36

当secret key 的长度不够,用这0x00来补全
0x5c,0x36为16进制分别代表一个字节

至于为什么要加这两个ipad和opad

让他们的和K异或后的值不一样

To make the two starting values different.

The HMAC security proof requires two different hash start states;
that’s why the pads are a full block size. It’s just a simple way to
get two different states out of a single master key.

To clarify: your simpler scheme is probably secure, but you haven’t
shown a proof. With different keys, a security proof is possible.

The exact pad patterns don’t matter at all. All-zeros and all-ones
would also be fine as far as the security proof is concerned; using
ones with 50% ones density whose XOR also is 50% ones is just “general
principles”.

HMAC的应用
  hmac主要应用在身份验证中,它的使用方法是这样的:
  1. 客户端发出登录请求(假设是浏览器的GET请求)
  2. 服务器返回一个随机值(nonce),并在会话中记录这个随机值
  3. 客户端将该随机值作为**,用户密码(key)进行hmac运算,然后提交给服务器
  4. 服务器读取用户数据库中的用户密码和步骤2中发送的随机值做与客户端一样的hmac运算,然后与用户发送的结果比较,如果结果一致则验证用户合法
  在这个过程中,可能遭到安全攻击的是服务器发送的随机值和用户发送的hmac结果,而对于截获 了这两个值的黑客而言这两个值是没有意义的,绝无获取用户密码的可能性,随机值的引入使hmac只在当前会话中有效,大大增强了安全性和实用性。大多数的 语言都实现了hmac算法,比如php的mhash、python的hmac.py、java的MessageDigest类,在web验证中使用 hmac也是可行的,用js进行md5运算的速度也是比较快的。