Hash Length Extension
A hash is not a MAC. When a developer writes the key in front of the message and hashes the concatenation, the digest they publish is also a valid starting state for the next block — so an attacker who knows the digest can append data and produce a signature the server will accept.
What this attack is not
The construction is the vulnerability
MD5, SHA-1 and the SHA-2 family are built the same way. The message is padded to a block boundary, then compressed block by block through a fixed compression function, each block receiving the previous block's output as its state. The published digest is the final state.
The padding is deterministic: a 0x80 byte, then zeros, then the message length in bits as a fixed-width integer. That means the attacker knows exactly what the last block looked like — and the digest told them the state it produced. Feeding that state back into the compression function with new data is not an attack on the primitive. It is the primitive, used as documented.
| Construction | Length extension | Why |
|---|---|---|
| MD5, SHA-1, SHA-224/256/384/512, RIPEMD-160 | Vulnerable | Merkle–Damgård: the digest is a resumable state |
| HMAC over any of the above | Not vulnerable | The keyed inner hash is hidden; the outer hash sees fixed-length input |
| SHA-3 (Keccak) | Not vulnerable | Sponge construction: the state is not resumable from the output |
| BLAKE2, BLAKE3 | Not vulnerable | Different construction, and both ship a keyed mode natively |
The shape of the attack
The attacker knows a message and its digest. They construct a new message that consists of the original message, the padding the hash function would have applied, and their appended data. They then compute the digest of the appended data starting from the known digest as the initial state. The result is a valid signature for a message the server has never seen.
The forged message contains bytes the application would not normally accept, so whether it works depends on how the message is parsed. In a query string or a serialised object the garbage sits between the original data and the suffix, and many parsers skip it. That detail is what turns a cryptographic curiosity into an access-control bypass.
import hmac, hashlib
SECRET = b'correct-horse-battery-staple'
def sign(message: bytes) -> str:
# secret PREFIX, plain hash, no HMAC
return hashlib.sha256(SECRET + message).hexdigest()
def verify(message: bytes, signature: str) -> bool:
return sign(message) == signature # and a non-constant-time compareimport hmac, hashlib
SECRET = b'correct-horse-battery-staple'
def sign(message: bytes) -> str:
# secret PREFIX, plain hash, no HMAC
return hashlib.sha256(SECRET + message).hexdigest()
def verify(message: bytes, signature: str) -> bool:
return sign(message) == signature # and a non-constant-time compareimport hmac, hashlib
SECRET = b'correct-horse-battery-staple'
def sign(message: bytes) -> str:
# keyed mode: the key is absorbed by the construction, not prepended
return hmac.new(SECRET, message, hashlib.sha256).hexdigest()
def verify(message: bytes, signature: str) -> bool:
expected = sign(message)
# compare_digest, because == leaks a timing signal
return hmac.compare_digest(expected, signature)import hmac, hashlib
SECRET = b'correct-horse-battery-staple'
def sign(message: bytes) -> str:
# keyed mode: the key is absorbed by the construction, not prepended
return hmac.new(SECRET, message, hashlib.sha256).hexdigest()
def verify(message: bytes, signature: str) -> bool:
expected = sign(message)
# compare_digest, because == leaks a timing signal
return hmac.compare_digest(expected, signature)hash_extender
The tool by Ron Bowes implements the attack for every Merkle–Damgård hash the format flag knows. It does not know
the secret length, so it either takes it as an argument or sweeps a range. Note that the signature in the first
command below is the project's own worked example — it is a digest of the eight-byte secret plus the string
data, chosen to
make the arithmetic reproducible, and it is not a token from any real application.
# The project's own documented example. The signature below is for the data
# string "data" with an 8-byte secret - it is a worked example, not a real MAC.
./hash_extender \
--data data \
--secret 8 \
--append append \
--format md5 \
--signature 6036708eba0d11f6ef52ad44e8b74d5b
# Unknown secret length: sweep a range instead of guessing one value.
# --secret-min and --secret-max are mutually exclusive with --secret.
./hash_extender \
--data "user=guest" \
--secret-min 4 --secret-max 32 \
--append "&admin=1" \
--format sha256 \
--signature "ORIGINAL_HEX_DIGEST_HERE"Sweep the length, do not assume it
Why HMAC is immune
HMAC is a hash of a hash, and the structure is chosen precisely to defeat this. The inner hash is H((K XOR ipad) || message) and its value is never published. The outer hash is H((K XOR opad) || inner), and the inner value is a fixed-length string — so there is no attacker-chosen tail to extend, and the state the attacker would need is the outer prefix's state, which they cannot compute without the key.
That is the whole reason HMAC exists in the form it does. An earlier design, H(K || message), is what this page attacks; H(message || K) has other problems; HMAC's nested double hash is the construction that survives both.
import hashpumpy
import requests
original = b'user=guest'
signature = 'ORIGINAL_HEX_DIGEST_HERE'
for length in range(4, 33):
new_sig, new_msg = hashpumpy.hashpump(
signature, original, b'&admin=1', length, raw=False
)
r = requests.get('https://target.example/verify',
params={'msg': new_msg.decode('latin-1'), 'sig': new_sig})
if r.status_code == 200:
print(f'secret length {length}, forged signature {new_sig}')
breakPrefix versus suffix
The position of the key decides which attack applies, and confusing the two wastes time in both directions.
| Construction | Length extension | The real weakness |
|---|---|---|
| H(key || message) | Yes — this page | Attacker appends and re-signs without the key |
| H(message || key) | No | Collision attacks on the hash extend to the MAC; secret recovery in weak cases |
| HMAC(key, message) | No | None known — this is the recommended construction |
| AEAD tag | No | Nonce reuse, if the caller gets it wrong |
Where else the pattern appears
The same mistake ships in more places than signed cookies. Anywhere a digest is used as a proof of knowledge — a download token, a password reset link, an API signature, a cache key — the question is the same: is the key inside a construction, or is it concatenated.
| Surface | Why it appears | What to check |
|---|---|---|
| Signed cookies and tokens | Hand-rolled before a framework library was adopted | HMAC or a signed-cookie helper, not a hash of a concatenation |
| API request signatures | A digest of the canonical request provides integrity | Canonicalisation must be unambiguous, and the MAC keyed |
| Password reset links | The token is a digest of the user id and a secret | A random stored token is simpler and has no construction to get wrong |
| File download signatures | A path plus an expiry, signed to prevent editing | Extending the signed path is exactly the attack — check it first |
| Check | Expected | Where to look |
|---|---|---|
| The MAC is a plain hash over secret then data | A single hash call, no HMAC, no AEAD tag — confirmed in source | The signing function |
| The verifier recomputes and compares the full digest | No parsing of a length prefix, no split on a delimiter | The verification function |
| The forged message is accepted with appended data | The server returns 200 for a message the attacker extended | The request |
| The secret length used by the tool is confirmed, not guessed | A range sweep that produces exactly one signature the server accepts | The hash_extender output |
| The fix is HMAC or a keyed mode, with a constant-time comparison | Not a change of hash function — SHA-256 is equally vulnerable | The patch |
What to Record
Length extension is easy to claim and hard to prove. These five make the finding real:
The verification code: The exact lines that hash and compare. A single hash call over a concatenation is the defect; anything else needs a different explanation.
The original and forged messages: Both, byte-for-byte, with the padding in the middle made visible. The forged message will look like garbage before the appended suffix — that is expected and worth explaining to the reader.
The recovered secret length: The length is revealed by the attack, so state it. A sweep that succeeds at exactly one length is a stronger result than a guess that happened to work.
What the appended data changes: Adding a parameter is only interesting if it alters authorisation, price, or role. Otherwise the finding is a broken MAC, not an access-control bypass.
The hash and its construction: MD5, SHA-1 and SHA-256 are all Merkle–Damgård. Do not record SHA-256 as the mitigation.
Four Reasons the Attack Fails
Each of these closes it, and each is a different check:
- HMAC is in use: Structurally immune. Confirmed by the presence of an HMAC call, not by the hash name.
- The secret is a suffix: H(message || secret) cannot be extended, because the attacker would have to append after the secret to control the tail. It has its own weaknesses, but not this one.
- The verifier is not just a hash comparison: A length prefix, a delimiter check, or a parse of the message before verification can independently block the forged value.
- The hash is not Merkle–Damgård: SHA-3, BLAKE2 and BLAKE3 have different constructions and do not extend this way. Verify the primitive before the claim.
Length Extension Checklist
Run this before and after writing the exploit:
- ☐ The MAC is a single hash over secret concatenated with message
- ☐ The hash is MD5, SHA-1, SHA-256/512 or another Merkle–Damgård construction
- ☐ The verifier compares the whole digest and does not parse a length prefix
- ☐ The secret length was swept, not assumed
- ☐ The forged message was accepted by the real verifier
- ☐ The appended data changes something the application acts on
- ☐ The fix is HMAC or a keyed mode, not a different hash
- ☐ The comparison is constant-time
- ☐ A regression test sends a forged extended message and expects rejection
The Fix and Its Migration
Replacing the construction invalidates every token already issued. Plan for that before shipping the patch:
Why the fix is not a longer hash
Moving from MD5 to SHA-256 changes nothing about this attack, because SHA-256 is also Merkle–Damgård — the construction is the issue, not the output size. Teams often make that change after a collision scare and consider the finding closed. The verifier still hashes a concatenation, the state is still resumable, and the forged message still validates. The only fixes that remove the class are a keyed construction (HMAC, KMAC, BLAKE2's keyed mode) or an authenticated-encryption tag.
Length Extension Practice
Cryptopals challenge 29 asks you to implement the attack yourself; the tool is for confirming it, not for learning it.
Related Cryptography Guides
Crypto Fundamentals
Hashing primitives and why a digest is not a MAC.
Weak Crypto
The other reasons a digest choice fails: collisions, unsalted storage and fast hashes.
Key Management
Where the secret in a secret-prefix MAC usually comes from, and how it leaks.
Cryptography Remediation
MAC and authentication patterns across languages.