Section 5.8

HMAC

Full name: Keyed-hash message authentication code (the name in FIPS 198-1); also expanded as hash-based message authentication code.

Definition

HMAC is a message authentication code §5.7 built from a cryptographic hash function §5.1. A message authentication code turns a secret key and a message into a short value, the tag, that only key holders can compute; a receiver with the key recomputes the tag to detect, with overwhelming probability, any change to the message. A cryptographic hash function is a public algorithm §14.1 mapping any input to a fixed-length value, the digest. HMAC hashes twice, the second time over the first digest, each time with a different variant of the key. RFC 2104 defines HMAC.

The idea

A sender transmits the command pay 10 to account 7 over a radio link that an attacker can rewrite. A plain hash attached to the command does not protect it: the attacker changes the command to pay 900 to account 3, computes the hash of the new text with the same public algorithm, and attaches that instead. The check must depend on a secret the attacker lacks.

The obvious fix, hashing the key followed by the message, is broken for SHA-256 §5.2 (Secure Hash Algorithm with a 256-bit output). SHA-256 publishes its final internal state, the working value that it updates as it reads each block of input, as the digest. Anyone who sees the digest can therefore continue the computation over more bytes and obtain the correct value for a longer message, made of the original message, the padding bytes that SHA-256 appends and further bytes, without the key. The Length-extension attack §5.11 entry works this out with real values.

HMAC avoids the problem by nesting two hash runs. The inner run mixes the key with the message and condenses everything into one digest. The outer run mixes the key again, in a different form, with that one digest. The tag that the world sees is the output of the outer run, whose input is always one key block followed by exactly one digest. Continuing the outer run gives the hash of a longer outer input, which no receiver ever computes. The inner digest, which an attacker would need to continue the inner run, is never shown.

How it works

HMAC works with any hash function HH that processes its input in fixed-size blocks. FIPS 198-1, the United States standard for HMAC [313], names the parts as follows.

  1. Bring the key to block length. If KK is exactly BB bytes long, K0K_0 is KK. If KK is longer, hash it and append B−LB - L zero bytes to the LL-byte result. If KK is shorter, append zero bytes until it is BB bytes long.

  2. Inner run. Combine K0K_0 with ipad by bitwise XOR (exclusive or: each output bit is 1 exactly when the two input bits differ). Append the message and hash the result. The output is the inner digest, LL bytes long.

  3. Outer run. Combine K0K_0 with opad by bitwise XOR. Append the inner digest and hash the result. The output, LL bytes long, is the tag.

The receiver holds the same key. It recomputes the tag over the message bytes it received and accepts the message only if the recomputed tag equals the received tag in every byte. The comparison should be a constant-time comparison §4.33, one whose running time does not depend on where the first differing byte is. Python’s §12.23 documentation, for example, tells programs to compare tags with hmac.compare_digest instead of == to reduce exposure to timing attacks, which infer secret values from how long an operation takes. An application may also keep only the first tt bits of the tag; the Tag truncation §5.12 entry covers that choice.

Both hash inputs begin with one full block that depends only on the key. RFC 2104 therefore allows an implementation to run the hash compression function §15.9, the step that mixes one block into the hash’s internal state, on these two blocks once per key and to store the two resulting states. Each later tag then costs two fewer runs of the compression function. Whoever obtains the two stored states can compute the tag of any message without knowing KK, so RFC 2104 says they must be protected like the key.

Worked example

This is test case 1 of RFC 4231, which publishes test values for HMAC-SHA-256 §5.9, that is, HMAC with SHA-256 as HH.

Key. The key is 20 bytes long, shorter than 64, so 64−20=4464 - 20 = 44 zero bytes are appended to make the 64-byte K0K_0.

Pads, one byte at a time. The key byte 0x0b is 00001011 in binary. XOR with the inner pad byte 0x36, which is 00110110, gives 00111101, which is 0x3d. XOR with the outer pad byte 0x5c, which is 01011100, gives 01010111, which is 0x57. XOR with a zero byte leaves the other byte unchanged, so the 44 appended zero bytes become 0x36 on the inner side and 0x5c on the outer side. The inner block is 20 bytes 0x3d followed by 44 bytes 0x36. The outer block is 20 bytes 0x57 followed by 44 bytes 0x5c.

Inner run. The input is the 64-byte inner block followed by the 8 message bytes, 64+8=7264 + 8 = 72 bytes. Its SHA-256 digest, the inner digest, is

92ab4d9a1f3b6152bca9dd9e69af43f4ce99e42fd4e30ff972c48025b9f9cfef

Outer run. The input is the 64-byte outer block followed by the 32-byte inner digest, 64+32=9664 + 32 = 96 bytes. Its SHA-256 digest is the tag:

b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7

This is the value RFC 4231 publishes. A receiver that holds the key and receives Hi There with this tag computes the same 32 bytes and accepts. If any byte of the message was changed on the way, the recomputed tag differs from the received one, except with negligible probability, and the receiver rejects.

Cost. SHA-256 adds its own padding and processes whole 64-byte blocks, so the 72-byte input and the 96-byte input each become 128 bytes, 2 blocks. The tag of this short message costs 2+2=42 + 2 = 4 runs of the compression function, or 2 when the states after the two key blocks are precomputed.

Stated precisely

Let HH be the hash function, BB its block length and LL its output length in bytes, KK the key, mm the message and |K||K| the length of KK in bytes. Write a‖ba \mathbin{\Vert} b for the byte string aa followed by the byte string bb, ⊕\oplus for bitwise XOR, 0n0^{n} for nn zero bytes, and ipad\mathrm{ipad} and opad\mathrm{opad} for the bytes 0x36 and 0x5c, each repeated BB times. FIPS 198-1 defines K0={Kif |K|=B,H(K)‖0B−Lif |K|>B,K‖0B−|K|if |K|<B,K_0 = \begin{cases} K & \text{if } |K| = B, \\ H(K) \mathbin{\Vert} 0^{B-L} & \text{if } |K| > B, \\ K \mathbin{\Vert} 0^{B-|K|} & \text{if } |K| < B, \end{cases} HMAC(K,m)=H((K0⊕opad)‖H((K0⊕ipad)‖m)).\mathrm{HMAC}(K, m) = H\bigl((K_0 \oplus \mathrm{opad}) \mathbin{\Vert} H((K_0 \oplus \mathrm{ipad}) \mathbin{\Vert} m)\bigr). A truncated tag of tt bits is the leftmost tt bits of this value.

Keys. RFC 2104 says the key should be chosen at random, or by a cryptographically strong pseudorandom generator, an algorithm that expands a random seed into a long sequence of bytes that no feasible computation can predict. A key shorter than LL bytes is strongly discouraged because it lowers the strength of the function. A key longer than LL bytes adds little strength, and a key longer than BB bytes is replaced by its LL-byte hash.

Security goal. An attacker who does not know KK and has a feasible amount of computing time, even after obtaining the tags of many messages of its choice, cannot produce a valid tag for any message whose tag it has not obtained, except with very small probability.

Assumptions. RFC 2104 states that this rests on two properties of HH.

  1. HH resists collision finding in the case where its starting value is secret and random and its output is not shown to the attacker. A collision is two different inputs with the same output.

  2. The compression function of HH, applied to a single block and keyed through its starting value, is itself a secure message authentication code.

Bellare, Canetti and Krawczyk proved in 1996 that a nested construction is secure when these two properties hold: an attacker’s chance of forging is at most the sum of its chances of breaking property 1 and property 2 [314]. Their nested construction replaces the fixed starting value of HH by a random secret key, with independent keys for the inner run and the outer run. HMAC is that construction with the two keys derived from one key: they are the internal states of HH after the blocks K0⊕ipadK_0 \oplus \mathrm{ipad} and K0⊕opadK_0 \oplus \mathrm{opad}. Applying the proof to HMAC therefore needs one more assumption: those two derived states cannot be told apart from two independent random keys.

Generic limits. Two limits hold however good HH is. A random guess of a tt-bit tag is right with probability 2−t2^{-t}. And, with nn the output length of HH in bits, the 1996 analysis names as the best known forgery an attack based on the birthday bound §5.6 (among about 2n/22^{n/2} random nn-bit values, two are likely to be equal). That attack needs the tags of about 2n/22^{n/2} messages under one key; for HMAC-SHA-256 that is 21282^{128} messages.

Limits and common mistakes

HMAC shows that exactly the bytes it covers come from a key holder (authenticity) and are unchanged (integrity §1.9), and nothing more. It does not encrypt: the message travels readable. It does not stop a replay attack §1.26, in which an attacker resends an old message with its old, still valid tag. Defeating replay needs a counter or another freshness value inside the covered bytes.

Every key holder can compute every tag. HMAC therefore cannot show which of the holders produced a message, and it cannot settle a dispute between them. That needs a digital signature §5.14.

Every field that changes the meaning of a message must be inside the bytes HMAC covers, and the fields must be encoded so that two different messages never give the same bytes. The Authentication coverage §5.41 entry lists those fields.

The key limits the strength. A 256-bit tag does not make a guessable key strong. If the key comes from a short password, an attacker who has seen one message and its tag tries candidate keys on its own computer until one reproduces the tag.

The receiver must compare the full expected tag length. A receiver that compares only as many bytes as arrived accepts an empty tag at once.

Do not replace HMAC by a home-made rule. The key followed by the message falls to the length-extension attack. The message followed by the key has another weakness, shown by Bellare, Canetti and Krawczyk: two equal-length messages that drive the hash to the same internal state have the same tag under every key, and such pairs can be searched for without the key.

Questions answered

Why is HMAC different from hashing key concatenated with message?

HMAC (keyed-hash message authentication code) differs because hashing the key followed by the message publishes a value that an attacker can extend into a valid tag for a longer message, while HMAC publishes nothing that can be extended into a tag a receiver accepts. A tag is the short value sent with a message to show that a holder of the secret key produced it. Write HH for the hash function, KK for the secret key and mm for the message. SHA-256 (Secure Hash Algorithm with a 256-bit output) processes its input block by block, updating a working value called its internal state, and outputs its whole final state as the digest. Given the tag H(K‖m)H(K \mathbin{\Vert} m) of mm, where ‖\Vert means followed by, an attacker can continue the hash over extra bytes of its choice. The result is a valid tag for a longer message: mm, then the padding SHA-256 added, then the attacker’s bytes. The attacker never learns KK. This is the length-extension attack.

HMAC runs the hash twice. The inner run hashes one key-derived block followed by the message, and its digest is never shown. The outer run hashes a second, different key-derived block followed by exactly that inner digest, and its output is the tag. Continuing the outer run from the tag gives the hash of a longer outer input, which no receiver ever computes, so the extension gains the attacker nothing. HMAC also has a security proof (Bellare, Canetti and Krawczyk, 1996) with stated assumptions about the hash function; H(K‖m)H(K \mathbin{\Vert} m) has none, and with SHA-256 it is broken.

Related entries: Message authentication code (MAC) (§5.7), SHA-256 (§5.2), Length-extension attack (§5.11), Authentication coverage (§5.41), HMAC-SHA-256 (§5.9), HMAC inner and outer pads (§5.10), Tag truncation (§5.12), Constant-time comparison (§4.33), Pseudorandom function (PRF) (§15.1), Merkle–Damgård construction (§15.8), Bit operations: truth tables, masks, shifts, and rotations (§4.50). Further reading: [7, 8, 10, 46, 167, 313, 314].