# HMAC explained

In cryptography, HMAC (Hash-based Message Authentication Code) is a specific construction for calculating a message authentication code (MAC) involving a cryptographic hash function in combination with a secret key. As with any MAC, it may be used to simultaneously verify both the data integrity and the authenticity of a message. Any cryptographic hash function, such as MD5 or SHA-1, may be used in the calculation of an HMAC; the resulting MAC algorithm is termed HMAC-MD5 or HMAC-SHA1 accordingly. The cryptographic strength of the HMAC depends upon the cryptographic strength of the underlying hash function, the size of its hash output length in bits, and on the size and quality of the cryptographic key.

An iterative hash function breaks up a message into blocks of a fixed size and iterates over them with a compression function. For example, MD5 and SHA-1 operate on 512-bit blocks. The size of the output of HMAC is the same as that of the underlying hash function (128 or 160 bits in the case of MD5 or SHA-1, respectively), although it can be truncated if desired.

The definition and analysis of the HMAC construction was first published in 1996 by Mihir Bellare, Ran Canetti, and Hugo Krawczyk, who also wrote RFC 2104. This paper also defined a variant called NMAC that is rarely if ever used. FIPS PUB 198 generalizes and standardizes the use of HMACs. HMAC-SHA-1 and HMAC-MD5 are used within the IPsec and TLS protocols.

## Definition (from RFC 2104)

Let:

• H(·) be a cryptographic hash function
• K be a secret key padded to the right with extra zeros to the input block size of the hash function, or the hash of the original key if it's longer than that block size
• m be the message to be authenticated
• ∥ denote concatenation
• ⊕ denote exclusive or (XOR)

Then HMAC(K,m) is mathematically defined by

## Implementation

The following pseudocode demonstrates how HMAC may be implemented. Blocksize is 64 (bytes) when using one of the following hash functions: SHA-1, MD5, RIPEMD-128/160.[1]

function hmac (key, message) if (length(key) > blocksize) then key = hash(key)

// keys longer than blocksize are shortened end if if (length(key) < blocksize) then key = key ∥ [0x00 * (blocksize - length(key))] // keys shorter than blocksize are zero-padded ('∥' is concatenation) end if 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 end function

The following is a Python implementation of HMAC-MD5:

python

```#!/usr/bin/env python
from hashlib import md5
class HMAC:
def __init__(self, key, msg):
self.outer = md5
self.inner = md5
self.digest_size = self.inner.digest_size
blocksize = 64
if len(key) > blocksize:
key = md5(key).digest
key = key + chr(0) * (blocksize - len(key))
trans_5C = "".join ([chr (x ^ 0x5c) for x in xrange(256)])
trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)])
self.outer.update(key.translate(trans_5C))
self.inner.update(key.translate(trans_36))
if msg:
self.inner.update(msg)
self.h = self.outer.copy
self.h.update(self.inner.digest)

def hexdigest(self):
return self.h.hexdigest

if __name__=="__main__":
h = HMAC("key","The quick brown fox jumps over the lazy dog")
print h.hexdigest #80070713463e7749b90c2dc24911e275
```

## Example usage

A business that suffers from attackers that place fraudulent Internet orders may insist that all its customers deposit a secret key with them. Along with an order, a customer must supply the order's HMAC digest, computed using the customer's symmetric key. The business, knowing the customer's symmetric key, can then verify that the order originated from the stated customer and has not been tampered with.

## Design principles

The design of the HMAC specification was motivated by the existence of attacks on more trivial mechanisms for combining a key with a hash function. For example, one might assume the same security that HMAC provides could be achieved with MAC = H(keymessage). However, this method suffers from a serious flaw: with most hash functions, it is easy to append data to the message without knowing the key and obtain another valid MAC. The alternative, appending the key using MAC = H(messagekey), suffers from the problem that an attacker who can find a collision in the (unkeyed) hash function has a collision in the MAC. Using MAC = H(keymessagekey) is better, however various security papers have suggested vulnerabilities with this approach, even when two different keys are used.

No known extensions attacks have been found against the current HMAC specification which is defined as H(key1H(key2message)) because the outer application of the hash function masks the intermediate result of the internal hash. The values of ipad and opad are not critical to the security of the algorithm, but were defined in such a way to have a large Hamming distance from each other and so the inner and outer keys will have fewer bits in common.

## Security

The cryptographic strength of the HMAC depends upon the size of the secret key that is used. The most common attack against HMACs is brute force to uncover the secret key. HMACs are substantially less affected by collisions than their underlying hashing algorithms alone.[2] [3] .[4] Therefore, HMAC-MD5 does not suffer from the same weaknesses that have been found in MD5.

In 2006, Jongsung Kim, Alex Biryukov, Bart Preneel, and Seokhie Hong showed how to distinguish HMAC with reduced versions of MD5 and SHA-1 or full versions of HAVAL, MD4, and SHA-0 from a random function or HMAC with a random function. Differential distinguishers allow an attacker to devise a forgery attack on HMAC. Furthermore, differential and rectangle distinguishers can lead to second-preimage attacks. HMAC with the full version of MD4 can be forged with this knowledge. These attacks do not contradict the security proof of HMAC, but provide insight into HMAC based on existing cryptographic hash functions.[5]

At least theoretically a timing attack could be performed to find out a HMAC digit by digit.[6]

## Examples of HMAC (MD5, SHA1, SHA256)

Here are some empty HMAC values - HMAC_MD5("", "") = 0x74e6f7298a9c2d168935f58c001bad88 HMAC_SHA1("", "") = 0xfbdb1d1b18aa6c08324b7d64b71fb76370690e1d HMAC_SHA256("", "") = 0xb613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad

Here are some non-empty HMAC values - HMAC_MD5("key", "The quick brown fox jumps over the lazy dog") = 0x80070713463e7749b90c2dc24911e275 HMAC_SHA1("key", "The quick brown fox jumps over the lazy dog") = 0xde7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9 HMAC_SHA256("key", "The quick brown fox jumps over the lazy dog") = 0xf7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

Note: Input data+key are of the single-byte ANSI variety, and not two-byte Unicode characters

## References

Notes
• Mihir Bellare, Ran Canetti and Hugo Krawczyk, Keying Hash Functions for Message Authentication, CRYPTO 1996, pp1 - 15 (PS or PDF).
• Mihir Bellare, Ran Canetti and Hugo Krawczyk, Message authentication using hash functions: The HMAC construction, CryptoBytes 2(1), Spring 1996 (PS or PDF).

## Notes and References

1. http://tools.ietf.org/html/rfc2104 RFC 2104
2. Web site: SHA-1 Broken. although it doesn't affect applications such as HMAC where collisions aren't important. Bruce Schneier. August 2005. 2009-01-09.
3. Web site: RFC 2104. The strongest attack known against HMAC is based on the frequency of collisions for the hash function H ("birthday attack") [PV,BCK2], and is totally impractical for minimally reasonable hash functions.. IETF. February 1997. 2009-12-03.
4. Mihir. Bellare. New Proofs for NMAC and HMAC: Security without Collision-Resistance. Advances in Cryptology – Crypto 2006 Proceedings. This paper proves that HMAC is a PRF under the sole assumption that the compression function is a PRF. This recovers a proof based guarantee since no known attacks compromise the pseudorandomness of the compression function, and it also helps explain the resistance-to-attack that HMAC has shown even when implemented with hash functions whose (weak) collision resistance is compromised.. Dwork. Cynthia. Lecture Notes in Computer Science 4117. 2006. Springer-Verlag. June 2006. 2010-05-25.
5. Jongsung. Kim. Biryukov, Alex; Preneel, Bart; Hong, Seokhie. 2006. On the Security of HMAC and NMAC Based on HAVAL, MD4, MD5, SHA-0 and SHA-1. ..
6. Briefly mentioned at the end of this session Sebastian Schinzel:Time is on my Side - Exploiting Timing Side Channel Vulnerabilities on the Web 28th Chaos Communication Congress, 2011.