Length Extension and Why Hash(secret || message) Fails
An API signs its requests by sending tag = SHA-256(secret || query) along with the query string. It looks reasonable: only someone who knows the secret can compute the tag. Yet anyone who sees one valid request can produce a valid tag for a longer request, for instance one that ends in &role=admin, without knowing the secret. This is the length-extension attack, it broke Flickr's API signatures in 2009, and it is the reason HMAC exists.
The mechanism
SHA-256 is a Merkle–Damgård hash (MD5 and SHA-1): it pads the message to a multiple of 64 bytes, then runs a compression function block by block over a 256-bit state. The final digest is the final state. So a digest is not just a fingerprint: it is everything needed to keep hashing.
Given tag = SHA-256(secret || msg) and the length of secret || msg, an attacker can:
- Recompute the padding SHA-256 added after
secret || msg(it depends only on the length). Call itglue. - Load
tagas the internal state, as if the hash had just processedsecret || msg || glue. - Continue hashing any
extrabytes, with padding for the total length.
The result is SHA-256(secret || msg || glue || extra), a valid tag for the message msg || glue || extra. The attacker needs the secret's length, not its value, and lengths can be guessed by trying a few.
A forgery on a toy API
The example includes a complete SHA-256 in pure Python (about 30 lines, checked against hashlib) because Python's hashlib doesn't let you set the internal state. The "API" is a function the example defines, with a secret it chooses; the attacker part uses only the message, the tag and the secret's length.
import hashlib, struct
K = [0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]
IV = [0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]
rotr = lambda x, n: ((x >> n) | (x << (32 - n))) & 0xffffffff
def compress(state, block):
w = list(struct.unpack(">16I", block))
for i in range(16, 64):
s0 = rotr(w[i-15], 7) ^ rotr(w[i-15], 18) ^ (w[i-15] >> 3)
s1 = rotr(w[i-2], 17) ^ rotr(w[i-2], 19) ^ (w[i-2] >> 10)
w.append((w[i-16] + s0 + w[i-7] + s1) & 0xffffffff)
a, b, c, d, e, f, g, h = state
for i in range(64):
t1 = (h + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) & 0xffffffff
t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) & 0xffffffff
a, b, c, d, e, f, g, h = (t1 + t2) & 0xffffffff, a, b, c, (d + t1) & 0xffffffff, e, f, g
return [(x + y) & 0xffffffff for x, y in zip(state, [a, b, c, d, e, f, g, h])]
def pad(length): # SHA-256 padding for a message of `length` bytes
return b"\x80" + b"\x00" * ((55 - length) % 64) + struct.pack(">Q", length * 8)
def sha256(msg, state=IV, done=0): # done = bytes already absorbed into `state`
data = msg + pad(done + len(msg))
for i in range(0, len(data), 64):
state = compress(state, data[i:i + 64])
return struct.pack(">8I", *state).hex()
print("toy sha256 == hashlib:", sha256(b"abc") == hashlib.sha256(b"abc").hexdigest())
# The toy API, made by this example: tag = SHA-256(secret || message). The secret is 16 bytes.
SECRET = b"lab-secret-16byt"
def api_tag(msg): return hashlib.sha256(SECRET + msg).hexdigest()
def api_accepts(msg, tag): return api_tag(msg) == tag
msg = b"user=alice&role=user"
tag = api_tag(msg) # the attacker sees msg and tag, not SECRET
# Attacker: knows only len(SECRET) (or tries a few lengths), msg and tag.
glue = pad(16 + len(msg))
extra = b"&role=admin"
state = list(struct.unpack(">8I", bytes.fromhex(tag)))
forged_tag = sha256(extra, state, 16 + len(msg) + len(glue))
forged_msg = msg + glue + extra
print("forged message:", msg, "+", len(glue), "bytes of padding +", extra)
print("API accepts forgery:", api_accepts(forged_msg, forged_tag))
import hmac
def hmac_tag(m): return hmac.new(SECRET, m, "sha256").hexdigest()
print("HMAC accepts forgery:", hmac.compare_digest(hmac_tag(forged_msg), forged_tag))toy sha256 == hashlib: True
forged message: b'user=alice&role=user' + 28 bytes of padding + b'&role=admin'
API accepts forgery: True
HMAC accepts forgery: False
The forged request is the original, 28 bytes of padding (0x80, zeros and the 64-bit length of the original 36 bytes), and &role=admin. The toy API accepts it. Many query-string parsers take the last value of a repeated parameter, and many ignore or tolerate the binary bytes in the middle, which is why the attack works against real APIs and not only on paper. The same forgery against an HMAC tag fails.
Which hashes are affected
| Hash | Length extension |
|---|---|
| MD5, SHA-1, SHA-256, SHA-512 | yes: the digest is the whole final state |
| SHA-224, SHA-384, SHA-512/256 | no in practice: the digest is a truncation, so the state is not revealed (SHA-224 only hides 32 bits) |
| SHA-3, BLAKE2, BLAKE3 | no: sponge and HAIFA constructions with finalisation |
Resistant hashes make H(secret || msg) not trivially forgeable, but the standard answer is still HMAC (or KMAC, keyed BLAKE2), which is proven secure as a MAC.
How it is detected
- Code review: any hash of a concatenation that includes a secret:
sha256(key + data),md5($secret . $params),hashlib.sha1(SECRET_SALT + body). AlsoH(msg || secret), which resists extension but is open to collision-based forgeries and is still not a standard MAC. - API documentation: "signature = SHA256(api_secret + sorted parameters)"; this pattern was common in 2000s web APIs (Flickr, several payment gateways).
- Testing your own API (in scope): a tool such as
hash_extenderor HashPump takes a known message, tag and a guessed secret length and prints the forged pair; if the server accepts one, the finding is confirmed.
How it is fixed
- Replace the construction with HMAC-SHA-256 (next lesson) or keyed BLAKE2. Rotate the secret, because old tags may have been collected.
- Verify tags with a constant-time comparison.
- Canonicalise what is signed (sorted parameters, a defined encoding), and reject requests with duplicate parameters or unexpected bytes, so even a mistake elsewhere doesn't become exploitable.
Pitfalls
- Switching to SHA-3 and calling it fixed:
SHA3(secret || msg)is not extendable, but use the standard MAC construction anyway so reviewers and libraries recognise it. - Thinking the secret's length is a defence: it is guessable, and attackers simply try lengths 8 to 64.
- Signing only part of a request (path but not body, body but not method).
Practice
1. In the example, the attacker doesn't know the secret is 16 bytes. How do they find out?
They try each plausible length (for example 1 to 64): compute the glue and forged tag for each and submit them; the length that the API accepts is correct. In the toy they could call api_accepts with each candidate.
2. Would SHA-512/256(secret || msg) be vulnerable to this attack?
Not to length extension: its digest is a truncation of the 512-bit state, so the attacker can't resume hashing. It is still better practice to use HMAC.
3. Why are the 28 padding bytes in the middle of the forged message not a problem for many servers?
Query-string and form parsers split on & and = and often accept arbitrary bytes in values, keeping the last value of a repeated key. The padding ends up inside the original role value, and the second role=admin wins.
Test yourself
What must the attacker know to extend SHA-256(secret || msg)?
- The secret
- The message, its tag and the secret's length
- Only the tag
- The SHA-256 round constants of the secret
Which of these resists length extension?
- SHA-256
- SHA-1
- SHA3-256
- MD5
What is the standard fix for an API that signs requests with SHA-256(secret || params)?
- Use SHA-512
- Put the secret at the end
- Use HMAC-SHA-256 and rotate the secret
- Base64-encode the tag
How many bytes of padding did the forged message contain in the example?
- 0
- 11
- 28
- 64