TExcelTAD
Home › Number Theory & Cryptography › Merkle-Damgård, Length Extension and HMAC

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 m1,…,mLm_1, \ldots, m_L and iterate a compression function ff from a fixed initial value:

h0=IV,hi=f(hi−1,mi),H(m)=hLh_0 = IV, \qquad h_i = f(h_{i-1}, m_i), \qquad H(m) = h_L

The padding appends a 1 bit, zeros and the message length ("MD strengthening"). With that, any collision of HH yields a collision of ff, so a collision-resistant ff gives a collision-resistant HH. MD5, SHA-1 and SHA-2 are all Merkle-Damgård hashes.

python · try it yourself
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 H(m)H(m) and the length of mm, but not mm itself, can continue hashing: they compute H(m∥pad∥x)H(m \parallel \text{pad} \parallel x) for any xx of their choice.

This breaks the tempting MAC t=H(k∥m)t = H(k \parallel m) with a secret key kk: given one valid tag, an attacker forges a tag for m∥pad∥xm \parallel \text{pad} \parallel x, for example appending &admin=true to a signed URL.

python · try it yourself
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:

HMAC⁡(k,m)=H((k⊕opad)∥H((k⊕ipad)∥m))\operatorname{HMAC}(k, m) = H\big((k \oplus \text{opad}) \parallel H((k \oplus \text{ipad}) \parallel m)\big)

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.

python · try it yourself
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 H(k∥m)H(k \parallel m) 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 1+8=91 + 8 = 9 bytes. 55+9=6455 + 9 = 64 fits exactly. 56+9=65>6456 + 9 = 65 > 64, so the padding grows to fill a second block: 128−56=72128 - 56 = 72 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 mm.

Solution

Extending would require the internal state after (k⊕ipad)∥m(k \oplus \text{ipad}) \parallel m, 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
python · try it yourself
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 H(k∥m)H(k \parallel m)?

  1. SHA-3
  2. Merkle-Damgård hashes such as SHA-256
  3. HMAC
  4. none

Merkle-Damgård padding includes the message length so that…

  1. the hash is longer
  2. a collision of the hash implies a collision of the compression function
  3. hashing is faster
  4. it supports Unicode

How should a server compare a received MAC with the expected one?

  1. with ==
  2. with a constant-time comparison such as hmac.compare_digest
  3. by comparing the first 4 bytes
  4. by hashing both again