The idea: a tag that is the hash's state

A MAC (message authentication code) is a short tag that only holders of a secret key can make. Alice sends a message and its tag; Bob, who has the same key, computes the tag again and compares. The obvious recipe is tag = H(K ‖ m): put the key in front of the message and hash. With MD5, SHA-1 or SHA-256 this recipe is broken, and the reason is how those hashes are built.

The TOY16 chain for the naive MAC: IV 5a3c and block k3Y9 TEA give h1 59ae; h1 and block AT 5 80 00 00 0C give the tag 6f2d, shaded as public. Eve, with no key, feeds 6f2d and her block space OR9 80 00 15 into f and gets 1da7, a valid tag for m, glue and OR 9.
The published tag is the state after the last block, so anyone can keep hashing from it without the key.

These hashes follow the Merkle–Damgård design. The padded input is cut into fixed-size blocks, and one small state is carried from block to block through a compression function f: hi+1 = f(hi, blocki). The output is simply the last state. So the tag is not a summary of the computation; it is the computation's state, ready to be continued.

TOY16, the page's hash

To see every value, the page uses TOY16, a hash invented for this page. It has the same shape as SHA-256 but tiny sizes. It has no security at all: 16 bits can be guessed in 65,536 tries.

TOY16SHA-256
block8 bytes64 bytes
state and output16 bits (4 hex digits)256 bits
start value IV5a3c8 fixed 32-bit words
f(h, block)for each byte b: h = ((h ⊕ b) × 157 + 81) mod 65536, then h = h ⊕ (h >> 7)64 rounds of additions, rotations and XORs
padding80, zeros, then 1 byte: the number of bytes hashed80, zeros, then 8 bytes: the number of bits hashed

The key is K = k3Y9 (4 bytes) and the message is m = TEA AT 5 (8 bytes). On the canvas, blue cells are bytes made from the key, grey cells are padding, green cells are HMAC's inner result and red cells are bytes Eve adds. A ? is a value Eve cannot know. See Inside AES-128 and SHA-256 for what SHA-256's real compression function does inside.

Why H(K ‖ m) fails: length extension

Alice hashes k3Y9TEA␣ (block 1) and AT␣5 80 00 00 0C (block 2; 0C = 12 bytes hashed). The states are 5a3c → 59ae → 6f2d, so the tag is 6f2d. Bob does the same with his key and accepts (Demo: naive MAC, honest message). If Eve changes the message to TEA AT 9 and keeps the old tag, Bob gets 3ca6 ≠ 6f2d and rejects (Demo: naive MAC, Eve edits the message). So far the MAC works.

But Eve can add to the message. She cannot redo blocks 1 and 2, because they start with the key. She does not need to: their result is the state after block 2, which is the tag 6f2d she just read. She appends a block with her text ␣OR␣9, pads it as if 21 bytes had been hashed, and runs one more step herself: f(6f2d, ␣OR␣9 80 00 15) = 1da7. Her message is m' = TEA AT 5 ‖ 80 00 00 0C ‖ ␣OR␣9: Alice's old padding becomes ordinary "glue" bytes in the middle. Bob hashes K ‖ m' and passes through 59ae and 6f2d on the way to 1da7. The tags match and he accepts a message Alice never sent (Demo: naive MAC, length extension works).

  • Eve needed the key's length (to build the padding), not the key. She can try every likely length.
  • She cannot choose the glue: m' always contains the old padding bytes. That rarely stops anything, because many parsers skip or tolerate strange bytes.
  • H(m ‖ K) (key at the end) avoids this particular trick but has other weaknesses (a collision in H for two messages gives a forgery). Don't invent MAC constructions.

HMAC: two hashes, two padded keys

HMAC (RFC 2104) is H((K ⊕ opad) ‖ H((K ⊕ ipad) ‖ m)). The key is padded with zeros to one block and XORed with two different constants: ipad = 36 and opad = 5c in every byte. On TOY16, K ⊕ ipad = 5D 05 6F 0F 36 36 36 36 and K ⊕ opad = 37 6F 05 65 5C 5C 5C 5C.

  1. Inner hash over (K ⊕ ipad) ‖ m: 5a3c → f192 → ea60 → b1ea. The result ih = b1ea is never sent.
  2. Outer hash over (K ⊕ opad) ‖ ih, a fresh chain: 5a3c → 37a3 → d7ed. The tag is d7ed (Demo: HMAC, honest message).

Eve can still continue the outer chain from the tag: f(d7ed, ␣OR␣9 80 00 15) = 46bc. But that is the hash of a three-block outer input, and Bob's outer input is always exactly one key block plus a 2-byte inner result: two blocks. Bob first runs the inner hash over m' (passing the old b1ea on the way, then 4528), then the outer hash, and gets 0a5e ≠ 46bc. Rejected (Demo: HMAC, length extension fails). To forge, Eve would need the inner state, and the inner state is never published.

Left, naive tag H(K ‖ m): the chain IV, K ‖ m ‖ pad, tag; the tag is public and Eve's f(tag, extra) is the tag of m ‖ glue ‖ extra, so Bob computes the same chain and accepts the forgery, marked with a cross. Right, HMAC: an inner chain over K xor ipad ‖ m gives ih, which is never sent; an outer chain over K xor opad ‖ ih gives the tag; Eve's f(tag, extra) is a 3-block outer hash that Bob never computes, so the forgery is rejected, marked with a tick.
With HMAC the public tag ends a fixed-length outer hash; continuing it gives a value that no HMAC computation produces.

A MAC gives integrity and authenticity between parties who share a key. If a third party must be able to check who signed, use a digital signature instead. For how hashing, encryption and MACs differ in general, see Encryption vs Hashing.

Checking the tag: constant time

A correct tag is useless if checking it leaks it. A normal string compare stops at the first different character, so a wrong guess with more correct leading digits takes a little longer. In Demo: early-exit compare leaks timing, the guesses 0000, d000 and d700 against d7ed take 1, 2 and 3 digit checks: each longer time tells Eve one more digit is right, so 16 tries per digit (64 in all) replace 65,536 blind tries. A constant-time compare XORs every pair of digits, ORs the results together and tests once: always 4 steps (Demo: constant-time compare). Real code compares bytes, not hex digits, and the differences are nanoseconds, but they can be measured over many tries. See Timing Attacks and Constant-Time Comparison for the attack and the defence in detail.

What to use in practice

  • Use your language's library HMAC and its compare function, for example Python's hmac.new(key, msg, hashlib.sha256) with hmac.compare_digest, Java's Mac.getInstance("HmacSHA256") with MessageDigest.isEqual, or Node's crypto.createHmac with crypto.timingSafeEqual.
  • Check your library with the RFC 4231 test vectors. Test case 2: key Jefe, message what do ya want for nothing?, HMAC-SHA256 = 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843.
  • Hashes that are not plain Merkle–Damgård do not have the length-extension property: SHA-3 (a sponge that never outputs its whole state), BLAKE2/BLAKE3, and truncated SHA-2 such as SHA-512/256 (the output hides half of the state). SHA-3 even has a keyed mode, KMAC. HMAC is still the safe default with SHA-256.
  • Use a random key of at least the hash's output size, keep it secret, and compare the full tag.

See OWASP Cryptographic Failures for how home-made crypto goes wrong in real applications.

See also Intrusion Detection: Signature Rules vs Anomaly Baselines for how suspicious traffic is noticed on the network.

What the page leaves out

Real SHA-1, SHA-256 and MD5 internals (TOY16 only has their chain shape); the exact padding and length fields of real hashes; keys longer than one block (HMAC hashes them first); the security proofs of HMAC; tag truncation (HMAC-SHA256-128); other MACs such as CMAC, Poly1305 and GMAC inside AEAD ciphers; key derivation (HKDF); and replay protection, which needs a nonce, counter or timestamp inside the MAC'd message.

On the mind map

Open the Web & Security mind mapWeb & SecurityCrypto building blocks: keys, hashes, signaturesCrypto building blocksStoring passwords: slow salted hash, never plaintextStoring passwordsBrowser rules: which request carries whatBrowser rulesRequest attacks: trick a browser or a serverRequest attacksLogin & identity: prove who you areLogin & identityOWASP Top 10 2025: common flaws, then the fixOWASP Top 10 2025OWASP: supply chain & ops: dependencies, logs and error pathsOWASP: supply chain & opsSymmetric vs asymmetricSymmetric vs asymmetricone shared key vs a public/private pairEncryption vs hashingEncryption vs hashinga key undoes encryption; a hash is one-wayInside AES and SHA-256Inside AES and SHA-256AES rounds on 4x4 bytes; SHA: 64 roundsHMAC vs Length ExtensionTag = hash state; HMAC hides inner stateDiffie-HellmanDiffie-Hellmang^ab mod p: same secret, never sentDigital signatureDigital signaturesign with private key, check with publicBlock cipher modesBlock cipher modesECB leaks patterns; GCM adds an auth tagDES and FeistelDES and FeistelSame network decrypts, keys reversedElliptic curve cryptoElliptic curve cryptoPoint adding is easy, undoing it is hardTiming attacksTiming attacksEarly-exit compare leaks a secret bytewiseOpen the Web & Security mind mapWeb & Securitykeys, hashes, signaturesCrypto building blocksSymmetric vs asymmetricSymmetric vs asymmetricone shared key vs a public/private pairEncryption vs hashingEncryption vs hashinga key undoes encryption; a hash is one-wayInside AES and SHA-256Inside AES and SHA-256AES rounds on 4x4 bytes; SHA: 64 roundsHMAC vs Length ExtensionTag = hash state; HMAC hides inner stateDiffie-HellmanDiffie-Hellmang^ab mod p: same secret, never sentDigital signatureDigital signaturesign with private key, check with publicBlock cipher modesBlock cipher modesECB leaks patterns; GCM adds an auth tagDES and FeistelDES and FeistelSame network decrypts, keys reversedElliptic curve cryptoElliptic curve cryptoPoint adding is easy, undoing it is hardTiming attacksTiming attacksEarly-exit compare leaks a secret bytewise
This page on the Web & Security mind map · 40 pages in 7 branches · open it to see the whole map and test yourself in recall mode.