Merkle-Damgård, Length Extension and HMAC
How do you hash a gigabyte with a function that only mixes a few dozen bytes at a time? The Merkle-Damgård construction chains a fixed-size compression function over the message blocks. It is simple and provably preserves collision resistance, but it has a structural quirk, length extension, which breaks naive MACs and is the reason HMAC exists.
The construction
Split the padded message into blocks and iterate a compression function from a fixed initial value:
The padding appends a 1 bit, zeros and the message length ("MD strengthening"). With that, any collision of yields a collision of , so a collision-resistant gives a collision-resistant . MD5, SHA-1 and SHA-2 are all Merkle-Damgård hashes.
import hashlib
BLOCK = 16 # toy block size in bytes
def compress(h, block): # toy compression: 8-byte state
return hashlib.sha256(h + block).digest()[:8]
def md_pad(msg_len):
zeros = (BLOCK - (msg_len + 1 + 8) % BLOCK) % BLOCK
return b"\x80" + b"\x00" * zeros + (8 * msg_len).to_bytes(8, "big")
def toy_hash(msg, iv=b"\x01" * 8):
data = msg + md_pad(len(msg))
h = iv
for i in range(0, len(data), BLOCK):
h = compress(h, data[i:i + BLOCK])
return h
print(toy_hash(b"abc").hex())
print(toy_hash(b"a much longer message that spans several blocks").hex())
print("padded length of 'abc':", len(b"abc" + md_pad(3)))f308f5f72ff6e70f
c5c0bc52a2cc6dd4
padded length of 'abc': 16
Length extension
The final digest is the internal state after the last block. So anyone who knows and the length of , but not itself, can continue hashing: they compute for any of their choice.
This breaks the tempting MAC with a secret key : given one valid tag, an attacker forges a tag for , for example appending &admin=true to a signed URL.
import hashlib
BLOCK = 16
def compress(h, block):
return hashlib.sha256(h + block).digest()[:8]
def md_pad(n):
return b"\x80" + b"\x00" * ((BLOCK - (n + 9) % BLOCK) % BLOCK) + (8 * n).to_bytes(8, "big")
def toy_hash(msg, iv=b"\x01" * 8, prefix_len=0):
data = msg + md_pad(prefix_len + len(msg))
h = iv
for i in range(0, len(data), BLOCK):
h = compress(h, data[i:i + BLOCK])
return h
key = b"s3cr3t-key" # server's secret, 10 bytes
msg = b"user=alice&amount=10"
tag = toy_hash(key + msg) # naive MAC: H(key || msg)
# Attacker knows msg, tag and len(key), but not key.
glue = md_pad(len(key) + len(msg))
extra = b"&amount=10000"
forged_msg = msg + glue + extra
done = len(key) + len(msg) + len(glue) # bytes already absorbed
forged_tag = toy_hash(extra, iv=tag, prefix_len=done)
print("server accepts forgery:", toy_hash(key + forged_msg) == forged_tag)
print(forged_msg)server accepts forgery: True
b'user=alice&amount=10\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0&amount=10000'
The attacker never learned the key, yet the server's check passes. Exactly this broke Flickr's API signatures in 2009.
HMAC
HMAC (Bellare, Canetti, Krawczyk, 1996) hashes twice with two derived keys:
The outer hash hides the inner state, so length extension no longer works, and HMAC is a secure MAC (a pseudorandom function) under mild assumptions on the compression function, even for MD5 and SHA-1, whose collision resistance is broken.
import hashlib, hmac
def my_hmac(key, msg):
block = 64 # SHA-256 block size in bytes
if len(key) > block:
key = hashlib.sha256(key).digest()
key = key.ljust(block, b"\x00")
inner = hashlib.sha256(bytes(k ^ 0x36 for k in key) + msg).digest()
return hashlib.sha256(bytes(k ^ 0x5C for k in key) + inner).hexdigest()
key, msg = b"s3cr3t-key", b"user=alice&amount=10"
print(my_hmac(key, msg))
print(hmac.new(key, msg, hashlib.sha256).hexdigest())
print("constant-time compare:", hmac.compare_digest(my_hmac(key, msg), hmac.new(key, msg, hashlib.sha256).hexdigest()))6de1c1abe34d151cff9fbacdad6274fe1414e74e97a2d173b7d948151d06238b
6de1c1abe34d151cff9fbacdad6274fe1414e74e97a2d173b7d948151d06238b
constant-time compare: True
Always compare MACs with a constant-time function (hmac.compare_digest); an early-exit == leaks how many leading bytes matched.
Other fixes
- SHA-3 uses a sponge: its output reveals only part of the internal state, so it has no length extension and is a valid MAC (KMAC).
- Truncated SHA-2 variants (SHA-512/256) also hide part of the state.
In software
- JWT
HS256, AWS request signing (SigV4), webhook signatures (Stripe, GitHub) and TLS 1.3's HKDF all use HMAC-SHA-256. See HMAC for the protocol side.
Exercises
Exercise 1: Padding length
With SHA-256 (64-byte blocks, 8-byte length field), how many bytes does padding add to a 55-byte message? To a 56-byte message?
Answer
9 bytes (one block total); 72 bytes (two blocks total).
Solution
Padding needs at least bytes. fits exactly. , so the padding grows to fill a second block: bytes.
Exercise 2: Why does HMAC stop length extension?
Explain in one sentence.
Answer
The tag is a hash of the inner hash under a secret outer key, so knowing it does not give the state needed to continue hashing .
Solution
Extending would require the internal state after , which is the inner digest; it is never revealed, only hashed again with the secret outer key.
Exercise 3: Verify a webhook (code)
A service sends body = b'{"event":"paid","id":42}' with signature sig computed as HMAC-SHA-256 under the shared key b"whsec_demo". Write the receiver's check and show that a modified body is rejected.
Answer
Recompute the HMAC and compare with hmac.compare_digest.
Solution
import hmac, hashlib
key = b"whsec_demo"
body = b'{"event":"paid","id":42}'
sig = hmac.new(key, body, hashlib.sha256).hexdigest()
def check(body, sig):
return hmac.compare_digest(hmac.new(key, body, hashlib.sha256).hexdigest(), sig)
print(check(body, sig), check(body.replace(b"42", b"43"), sig))True False
Go further: Length Extension and Why Hash(secret || message) Fails forges a tag on a toy API using the Merkle–Damgård structure.
Test yourself
Which hashes are vulnerable to length extension when used as ?
- SHA-3
- Merkle-Damgård hashes such as SHA-256
- HMAC
- none
Merkle-Damgård padding includes the message length so that…
- the hash is longer
- a collision of the hash implies a collision of the compression function
- hashing is faster
- it supports Unicode
How should a server compare a received MAC with the expected one?
- with
== - with a constant-time comparison such as
hmac.compare_digest - by comparing the first 4 bytes
- by hashing both again