19. Birthday Attacks & Hash Collisions
When mathematical inevitability meets cryptographic assumptions
The hashing article introduced collision resistance and mentioned the birthday paradox in passing — enough to explain why SHA-256 gives 128-bit security, not 256-bit. But the birthday paradox is not just a footnote. It is the engine behind some of the most consequential attacks in cryptographic history: the MD5 collision that broke certificate authorities, the SHAttered attack that shook Git's foundations, and a class of structural weaknesses in the Merkle-Damgård construction that let attackers forge authenticated requests without knowing the secret key.
This article goes deep. We cover the full mathematics of the birthday problem, show how it maps onto hash functions, walk through real-world collisions that changed industry practice, and explain length extension attacks from first principles.
The Birthday Paradox: Full Treatment
The birthday problem asks: how many people must be in a room before the probability of a shared birthday exceeds 50%? The answer — 23 — surprises almost everyone. The intuition collapses once you count pairs: 23 people contain pairs, and each pair has a 1-in-365 shot at matching. The probabilities compound quickly.
The exact formula for the probability of at least one collision among items chosen from equally likely possibilities is:
For large and moderate , this simplifies to the approximation:
Plugging in gives , a 39% chance. At , the probability crosses 50%. At , it exceeds 90%.
Birthday problem at a glance
Birthdays (H = 365):
n = 23 people → P(collision) ≈ 50.7%
n = 57 people → P(collision) ≈ 99.0%
A 16-bit hash (H = 65,536 possible values):
n ≈ 300 hashes → P(collision) ≈ 50%
n ≈ 1000 hashes → P(collision) ≈ 99.9%
A 64-bit hash (H ≈ 1.8 × 10¹⁹ possible values):
n ≈ 5 × 10⁹ hashes → P(collision) ≈ 50%
The threshold scales with the square root of the output space, not the space itself. Double the hash output from 64 bits to 128 bits, and the collision threshold jumps from ~232 to ~264 — a factor of four billion, not two.
The square root principle
For any hash function with an n-bit output, a collision is expected after approximately 2n/2 evaluations. This is not a flaw in any particular algorithm — it is an information-theoretic lower bound. No hash function can do better. Every cryptographic hash function's collision resistance is exactly half its output length in bits.
Applying the Birthday Bound to Hash Functions
The birthday bound cuts every hash function's effective collision resistance in half. A 128-bit hash does not give you 128 bits of collision resistance — it gives you 64. That matters enormously when computing power is available.
| Hash function | Output size | Collision resistance | Status |
|---|---|---|---|
| MD5 | 128 bits | ~264 | Broken — collisions in seconds |
| SHA-1 | 160 bits | ~280 | Broken — practical collision demonstrated |
| SHA-256 | 256 bits | ~2128 | Secure |
| SHA-512 | 512 bits | ~2256 | Secure (overkill for most uses) |
| SHA3-256 | 256 bits | ~2128 | Secure |
| BLAKE3 | 256 bits | ~2128 | Secure |
In 2004, 264 operations sounded like a lot. By 2004 it was a research project; by 2008 it was a weekend. Computing power only moves in one direction. The birthday bound turns what looks like a generous safety margin into a dangerously thin one.
The MD5 Collision
MD5 was designed by Ron Rivest in 1991 and dominated the 1990s. By 1996, differential cryptanalysis had found weaknesses in its compression function. By 2004, Xiaoyun Wang and colleagues found full collisions — two distinct inputs that produce identical 128-bit digests — in under an hour on a standard PC. By 2008, Marc Stevens and colleagues demonstrated chosen-prefix collisions: given two completely different documents, they could construct suffixes that brought both documents to the same MD5 hash.
A collision alone is interesting. A chosen-prefix collision is devastating.
Classic MD5 collision
Input A (hex):
d131dd02c5e6eec4693d9a0698aff95c 2fcab50712467eab4004583eb8fb7f89
55ad340609f4b30283e488832571415a 085125e8f7cdc99fd91dbdf280373c5b
d8823e3156348f5bae6dacd436c919c6 dd53e2b487da03fd02396306d248cda0
e99f33420f577ee8ce54b67080a80d1e c69821bcb6a8839396f9652b6ff72a70
Input B (hex):
d131dd02c5e6eec4693d9a0698aff95c 2fcab50712467eab4004583eb8fb7f89
55ad340609f4b30283e4888325f1415a 085125e8f7cdc99fd91dbdf280373c5b
d8823e3156348f5bae6dacd436c919c6 dd53e23487da03fd02396306d248cda0
e99f33420f577ee8ce54b67080280d1e c69821bcb6a8839396f965ab6ff72a70
Both produce:
MD5: 79054025255fb1a26e4bc422aef54eb4
Two 128-byte inputs, differing in only a few bits, produce an identical MD5 hash. To a system that uses MD5 for integrity verification, these files are indistinguishable.
The practical damage came in 2008 when Stevens, Sotirov, and collaborators exploited chosen-prefix MD5 collisions to forge a rogue certificate authority certificate. They purchased a legitimate certificate from RapidSSL, then used the chosen-prefix collision to construct a rogue CA certificate that shared the same MD5 hash. Browsers at the time trusted that CA — which meant the attackers could sign certificates for any domain on the internet. This was not a theoretical exercise. It ran on a cluster of 200 PlayStation 3 consoles over two weeks.
The fallout forced all major certificate authorities to stop issuing MD5-signed certificates within months.
The SHA-1 Collision (SHAttered)
SHA-1 survived a decade longer than MD5, partly because theoretical attacks took longer to materialize into practical ones. Wang et al. had found SHA-1 weaknesses in 2005, reducing the attack from 280 to 263 in theory. But demonstrating an actual collision required resources that took another twelve years to marshal.
In February 2017, researchers from Google and the Centrum Wiskunde & Informatica published SHAttered: two different PDF files with identical SHA-1 hashes. The computation required approximately 9.2 × 1018 SHA-1 evaluations — roughly 6,500 CPU-years and 110 GPU-years, estimated at around $110,000 in cloud compute at the time.
SHAttered: two PDFs, one SHA-1
File: shattered-1.pdf
SHA-1: 38762cf7f55934b34d179ae6a4c80cadccbb7f0a
File: shattered-2.pdf
SHA-1: 38762cf7f55934b34d179ae6a4c80cadccbb7f0a
SHA-256 of shattered-1.pdf:
2bb787a73e37352f92383abe7e2902936d1059ad9f1ba6daaa9c1e58ee6970d0
SHA-256 of shattered-2.pdf:
d4488775d29bdef7993367d541064dbdda50d383f89f0aa13a6ff2e0894ba5ff
The files look different to humans and to SHA-256.
They are identical to SHA-1.
Before SHAttered
SHA-1 was still widely used in TLS certificates, code signing, and Git. Attacks were theoretical. Many organizations deferred migration.
After SHAttered
Chrome and Firefox began marking SHA-1 certificates as invalid. Git began adding SHA-256 support. The migration that had been advised for twelve years finally became urgent.
Git's use of SHA-1 deserves special mention. Every commit, tree, and blob in a Git repository is named by its SHA-1 hash. Git uses SHA-1 as a content-addressed identifier — the hash is the identity. A SHA-1 collision in a Git repository allows an attacker to swap one object for another with the same identifier. In practice, Git's object model provides some additional protection (objects include their type and size in the hashed content), but the team began migrating to SHA-256 as the object hash after SHAttered. The transition has been long; SHA-256 Git repositories are available today but not yet universally supported.
Length Extension Attacks
The birthday bound is a mathematical inevitability. Length extension attacks are a structural flaw — a consequence of how the Merkle-Damgård construction works, not just how large the output is.
Recall that SHA-256 processes a message by padding it, splitting it into 512-bit blocks, and passing each block through a compression function that updates a running state. After the final block, the current state is the hash output.
Here is the problem: the hash output is the internal state of the algorithm. If you know H(message), you know the state of the hash function after it processed message || padding. You can resume hashing from that state, feeding in additional data, and compute a valid hash for message || padding || extension — without ever knowing the original message.
Length extension illustrated
Normal hashing:
state₀ → [compress: "secret||Transfer"] → state₁
state₁ → [compress: "$100 to Alice"] → state₂
state₂ → [pad and finalize] → H(secret||message)
What an attacker can do, knowing only H(secret||message):
Treat H(secret||message) as state₂ (it is).
Continue from state₂:
state₂ → [compress: "&&Transfer $9999"] → state₃
state₃ → [pad and finalize] → H(secret||message||padding||extension)
The final hash is valid — it was produced by a correct run of SHA-256
starting from the known state. The attacker never touched the secret.
This turns into a real attack whenever an application uses H(secret || request) as an authentication token. An attacker who intercepts one authenticated request can forge extended requests that will pass the server's verification.
-
Server creates an authentication token
The server computes
token = SHA-256(secret || "user=alice&action=view")and sends the request with this token. The attacker intercepts the request and observes both the message and the token. -
Attacker reconstructs the padding
SHA-256 pads messages to a multiple of 512 bits with a specific scheme: a 1-bit, then zeros, then the 64-bit message length. The attacker knows the visible message length and can compute the padding exactly. The original padded message is
"user=alice&action=view" || SHA-256-padding. -
Attacker extends the message
Using the intercepted token as the internal state, the attacker continues hashing:
token' = SHA-256_continue(token, "&action=admin"). This is a valid SHA-256 output for the extended input. -
Forged request passes verification
The attacker sends
"user=alice&action=view" || padding || "&action=admin"withtoken'. The server verifies by computingSHA-256(secret || full_message)and finds it matchestoken'. The forged request is accepted.
HMAC is the fix
HMAC defeats length extension by hashing the result a second time:
HMAC(K, m) = H(K⊕opad || H(K⊕ipad || m)). Even if an attacker extends
the inner hash, the outer hash over a completely different key derivation produces
an unrelated output. Length extension attacks are impossible against HMAC.
Never use H(secret || message) for authentication. Always use HMAC.
SHA-3 (the Keccak sponge construction) is immune to length extension attacks by design. The sponge absorbs input into a large internal state, of which only a portion is exposed as output. The hidden capacity prevents an attacker from reconstructing the full internal state from the output alone — so there is no state to resume from. This is one of the key structural advantages SHA-3 has over the SHA-2 family.
Chosen-Prefix Collisions
A basic collision requires finding any two inputs that hash to the same value. The attacker has no control over what those inputs look like — they are essentially random-looking byte strings. Harmful in theory; rarely useful in practice.
A chosen-prefix collision is fundamentally more powerful. Given two arbitrary prefixes P₁ and P₂ — say, two documents with different content that an attacker has already chosen — the attacker finds suffixes S₁ and S₂ such that:
The suffixes are computational garbage, but they can be hidden in document metadata, PDF comment fields, image EXIF data, or other places where their presence is invisible or harmless. The two documents, each ending in their respective suffix, produce the same hash — but contain different chosen content.
How the rogue CA attack worked
P₁ = legitimate certificate for "www.example.com"
(purchased from a real CA, will be signed with real CA key)
P₂ = rogue CA certificate
(not legitimate, must not be signed by any CA)
The attackers need: H(P₁ || S₁) = H(P₂ || S₂) under MD5
Step 1: Buy P₁ from a real certificate authority.
The CA signs it: Signature = RSA_sign(MD5(P₁ || S₁))
Step 2: Because H(P₁ || S₁) = H(P₂ || S₂), the CA's signature
is also valid for P₂ || S₂:
RSA_verify(Signature, MD5(P₂ || S₂)) = valid ✓
Step 3: The rogue CA certificate now carries a valid CA signature.
Any certificate it issues is trusted by browsers.
This is why chosen-prefix collisions matter: they allow an attacker to choose meaningful content on both sides. The collision is not between two random blobs — it is between a legitimate document and a malicious substitute.
Why SHA-256 Is Safe (For Now)
SHA-256's 256-bit output places collisions at 2128 — roughly 3.4 × 1038 operations. To put that in physical terms: the observable universe contains approximately 2266 atoms. The entire computing output of humanity, every machine ever built running every second since the Big Bang, would not approach 2128 SHA-256 evaluations.
Collision resistance compared to physical reality
MD5 collision (2^64):
Modern GPU: ~1 second
Was broken in 2004 with academic hardware
SHA-1 collision (2^80):
Google cluster (2017): ~110,000 in cloud compute cost
Broken
SHA-256 collision (2^128):
All GPUs ever manufactured running since 2010:
~2^60 per second × ~2^30 seconds ≈ 2^90 total
We are 38 orders of magnitude short.
Atoms in the observable universe: ~2^266
SHA-256 collision threshold: 2^128
Ratio: 2^138 atoms per collision attempt
The caveat is "for now". SHA-256 has no known structural weaknesses — differential attacks have not found meaningful shortcuts through its 64 rounds. Quantum computers, via Grover's algorithm, would reduce the effective collision resistance from 2128 to 285 (Grover provides a square-root speedup on preimage search, but the birthday bound still applies). 285 is still large, but it is no longer comfortably astronomical. This is why post-quantum hash security discussions often recommend SHA-384 or SHA-512 as a conservative margin.
SHA-3 and the Sponge Construction
SHA-3, standardized by NIST in 2015, uses a fundamentally different construction from the SHA-1 and SHA-2 family. Instead of Merkle-Damgård, SHA-3 is built on the Keccak sponge function.
Sponge construction vs Merkle-Damgård
Merkle-Damgård (SHA-256):
┌────────────┐ ┌────────────┐ ┌────────────┐
│ state₀ │──→│compress(B₁)│──→│compress(B₂)│──→ ... ──→ output
└────────────┘ └────────────┘ └────────────┘
Output = final state (entire state is exposed)
Sponge (SHA-3 / Keccak):
┌──────────────────────────────────────────────────┐
│ state (1600 bits) │
│ ┌───────────────────┬────────────────────────┐ │
│ │ rate (1088 b) │ capacity (512 b) │ │
│ └───────────────────┴────────────────────────┘ │
└──────────────────────────────────────────────────┘
Absorb: XOR input blocks into rate portion, permute
Squeeze: read output from rate portion
Only the rate is exposed. Capacity stays hidden.
Cannot reconstruct full state from output → no length extension
The hidden capacity is the key property. Because the full 1600-bit state is never exposed — only the rate portion appears in the output — an attacker cannot reconstruct the state from the hash alone. Length extension attacks are impossible. SHA-3 also uses a different internal permutation (Keccak-f) with a completely different algebraic structure from SHA-2, so any future cryptanalysis of SHA-256 does not automatically threaten SHA-3.
In practice, SHA-256 with HMAC is secure and ubiquitous. SHA-3 is worth knowing and worth preferring for new protocols that don't need SHA-256 compatibility, but it is not urgently necessary as a migration target the way SHA-1 was.
Birthday Collision Finder
Choose a truncated hash size and generate random values. Watch collisions emerge as the pool grows — the smaller the hash, the faster they appear. The red line marks the theoretical birthday bound at √H attempts.
Length Extension Attack Demo
In a real API, the server computes SHA-256(secret || message) as an
authentication token. Enter a message and observe the token. Then forge an
extended message — without knowing the secret — and watch the forged token verify
correctly.
Key Takeaways
- The birthday paradox means collisions appear after ~√H attempts — so an n-bit hash gives only n/2 bits of collision resistance
- MD5 (264 collision resistance) has been practically broken since 2004; never use it for security
- SHA-1 (280 collision resistance) was broken in 2017 by Google/CWI at a cost of ~$110,000; it is deprecated everywhere
- SHA-256 provides 2128 collision resistance — no shortcut is known, and brute force is physically impossible with current or foreseeable technology
- Chosen-prefix collisions are far more dangerous than basic collisions: they let attackers choose meaningful content on both sides of the collision
- Length extension attacks exploit Merkle-Damgård's exposed internal state — never authenticate with H(secret || message); always use HMAC
- SHA-3's sponge construction hides the internal capacity, making length extension structurally impossible
- HMAC defeats both naive authentication misuse and length extension, and remains secure even with SHA-256
From Caesar's alphabet shift to birthday attacks on collision-resistant hash functions, this series has traced the full arc of modern cryptography. We began with substitution ciphers and the concept of a key, moved through XOR and perfect secrecy, then into the block cipher world of AES and its modes. Asymmetric cryptography arrived with RSA, Diffie-Hellman, and elliptic curves — giving us key exchange and digital signatures without any shared secret. TLS showed how these primitives compose into a protocol that secures billions of connections every day. Hashing and MACs added integrity and authentication. Key derivation functions turned human passwords into computational fortresses. Padding oracles demonstrated that correct cryptographic primitives, combined carelessly, collapse under chosen-ciphertext attacks. And here, at the end, birthday attacks remind us that even the most conservative security margins must be chosen with mathematical care — because the adversary has the same mathematics we do, and more time than we might expect.
Every concept in this series built on the ones before it. A hash function is only as useful as its collision resistance. Collision resistance only means something if you understand the birthday bound. The birthday bound only matters because real attackers exploit it — as Wang, Stevens, and the SHAttered team proved. Cryptography is not a collection of magic black boxes. It is a discipline of precise reasoning about what an adversary can and cannot compute, and every assumption deserves scrutiny.