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_sizeAt a glance
| Output | Same as the underlying hash (e.g. 256 bits for HMAC-SHA-256) |
|---|---|
| Key size | Any; normalized internally to block_size |
| Standards | RFC 2104; FIPS 198-1; RFC 4231 (test vectors) |
| Status | Modern, 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-SHA-256 , JWT (HS256), AWS Signature v4, OAuth 1.0a.
- HMAC-SHA-512 , JWT (HS512), TLS 1.3 record-layer (with SHA-384).
- HMAC-SHA-1 , TOTP (RFC 6238), legacy TLS, IPsec.
- HMAC-MD5 , legacy IPsec, CHAP , not for new designs.
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
- RFC 2104 , HMAC
- NIST FIPS 198-1 , HMAC Standard
- RFC 4231 , HMAC-SHA2 test vectors
- KMAC · Poly1305 · CMAC
Quick quiz
Test yourself on hmac
10 multiple-choice questions. Pick an answer for each, then submit to see explanations.
Q1.Who designed HMAC?
Q2.Which RFC standardizes HMAC?
Q3.What are HMAC's two pad bytes?
Q4.Why two passes?
Q5.Is HMAC-MD5 known broken?
Q6.JWT HS256 algorithm:
Q7.TOTP underlying primitive (RFC 6238):
Q8.If the key is longer than block size, HMAC...
Q9.If the key is shorter than block size, HMAC...
Q10.Generic security level of HMAC over an n-bit hash: