Hash Lab

Keyed cryptographic (MAC)

HMAC

Hash-based Message Authentication Code. Designed by Bellare, Canetti, and Krawczyk in 1996; standardized as RFC 2104 (1997) and FIPS 198-1 (2008). HMAC turns any cryptographic hash function into a keyed MAC, with security that survives even when the underlying hash has collision weaknesses.

The construction

HMAC(K, m) = H( (K_0 XOR opad) || H( (K_0 XOR ipad) || m ) )

where
  ipad = 0x36 repeated to one block
  opad = 0x5C repeated to one block
  K_0  = K           if |K| == block_size
       = pad(K, 0)   if |K| <  block_size
       = pad(H(K),0) if |K| >  block_size

At a glance

OutputSame as the underlying hash (e.g. 256 bits for HMAC-SHA-256)
Key sizeAny; normalized internally to block_size
StandardsRFC 2104; FIPS 198-1; RFC 4231 (test vectors)
StatusModern, recommended; the default MAC for new designs

Why two passes

Naive H(K || m) with a Merkle-Damgård hash leaks length-extension. The nested HMAC structure binds the key on both ends, so an attacker who sees one tag cannot extend the message. HMAC also has a clean security proof: HMAC is a PRF as long as the underlying hash’s compression function is a PRF.

Common instantiations

HMAC survives broken hashes

Even though MD5 and SHA-1 are collision-broken, HMAC-MD5 and HMAC-SHA-1 have no known practical attacks. The collision attacks don’t translate through HMAC’s nested structure. That said, new designs should still pick HMAC-SHA-256 or better.

Try it

The HMAC playground computes HMAC over any input with multiple base hashes and shows the ipad / opad construction byte-by-byte.

References

Quick quiz

Test yourself on hmac

10 multiple-choice questions. Pick an answer for each, then submit to see explanations.

  1. Q1.Who designed HMAC?

  2. Q2.Which RFC standardizes HMAC?

  3. Q3.What are HMAC's two pad bytes?

  4. Q4.Why two passes?

  5. Q5.Is HMAC-MD5 known broken?

  6. Q6.JWT HS256 algorithm:

  7. Q7.TOTP underlying primitive (RFC 6238):

  8. Q8.If the key is longer than block size, HMAC...

  9. Q9.If the key is shorter than block size, HMAC...

  10. Q10.Generic security level of HMAC over an n-bit hash:

0 of 10 answered