Skip to main content
Cipher Visualizers home

Breaking MD5 with a Chosen-Prefix Collision

A chosen-prefix collision gives two files that start however the attacker likes and still share one MD5 hash. This guide takes a real HashClash pair apart, one starting with yes and one with no, and traces MD5's internal state block by block as nine near-collision blocks cancel the difference to zero.

Pashalis Laoutaris 16 min read

Try it

Interactive MD5 Chosen-Prefix Collision

🔐 MD5 Chosen-Prefix Collision

A real pair made with HashClash: 640 bytes each, one starting with "yes" and one with "no". Nothing here is faked; MD5 runs live in your browser.
Enter text and click a button to start!
The two files, block by block (64 bytes each)
chosen prefixbirthday bytesnear-collision byte
MD5 internal state after each block (differing hex digits highlighted)
Final hashes
Click "Absorb Next Block" to feed both files into MD5 one block at a time.

Breaking MD5 with a Chosen-Prefix Collision

Introduction

The MD5 collision breaker shows Wang’s attack, which finds two blocks with the same hash. That attack has a catch. Both colliding messages must start from the same state, and the attacker has no say over what the colliding bytes look like. It is an identical-prefix collision.

A chosen-prefix collision removes the catch. The attacker picks two different beginnings, such as two certificates with different names, and then computes a tail for each. With those tails added, the two files have the same MD5. This is the attack behind the rogue certificate authority of 2008 and the Flame malware of 2012. Running it takes Marc Stevens’ HashClash and days of CPU time, so this guide does not recompute one. Instead it checks a real, published pair, byte by byte, and shows exactly how the attack fits together.

Table of Contents

Identical Prefix and Chosen Prefix

MD5 reads its input in blocks of 64 bytes. It keeps a state of four 32-bit words, a, b, c and d, and each block updates that state. The final state is the hash. Two messages collide when their states end up equal.

In an identical-prefix collision, both messages share the same beginning, so they enter the collision blocks with the same state. Wang’s method then finds two blocks that leave the state equal again. In a chosen-prefix collision, the two beginnings differ. So the two states already differ when the collision blocks start, by an amount the attacker did not pick. The attack has to steer two unrelated states back together. That is much harder, and it is why the attack has two steps.

The Pair: yes and no

The pair in this guide comes from Ange Albertini’s corkami/collisions repository, as examples/cpc1.bin and examples/cpc2.bin. It was made with HashClash. Each file is 640 bytes, which is ten blocks. One file starts with the three bytes yes, the other with no and a zero byte. After that come zero bytes, the birthday bytes, and the collision blocks.

The two files differ in exactly 20 bytes. Three of them are the chosen prefixes. Eight are the last bytes of the first block, where the birthday search did its work. The other nine are one byte in each of the nine remaining blocks. Both files hash to eee3c5912df242d08b0662563f34819d.

The near-collision blocks cannot cancel just any difference. They need the difference between the two states to have a special shape. In this pair, after the first block, word a is equal in both states, and words c and d differ by exactly the same amount. Only word b is free.

Getting there is a birthday problem. Equal a words is a condition on 32 bits, and equal differences in c and d is another 32. So the attacker needs two states that agree on a 64-bit function of the state. By the birthday paradox, that takes about 2^32 attempts on each side, where an attempt means trying new values for the last bytes of the first block. In practice the search asks for more than this, because it also wants a difference that the later blocks can remove in few steps. That extra demand is a large part of why the whole attack costs so much.

In the pair, the 8 bytes at offsets 0x38 to 0x3F carry the result. For the yes file they are b74638098a46f17b, and for the no file 1971e7f70972fb06. With those bytes, the first block leaves a state difference of 47 bits in exactly the shape the next step needs.

Step Two: the Near-Collision Blocks

Each of the next nine blocks is a near-collision block. The two files use almost the same block, but message word 11, the bytes at offsets 44 to 47 inside the block, differs by a signed power of two. HashClash builds each block with a differential path, in the spirit of Wang’s attack. The path is chosen so that the small message difference removes part of the state difference instead of adding to it.

The state difference keeps its shape the whole way. Word a stays equal, and c and d keep moving together. Measured as differing bits, the difference falls from 47 to 46, 43, 43, 37, 29, 21, 20 and 6. The ninth block, with a message difference of -2^31, removes the rest. After block 9 the two states are identical.

Why nine blocks and not one? Each block can only cancel a small piece of the difference, because a differential path that cancels more is far harder to satisfy. The corkami README puts it this way: fewer blocks means longer computation. It cites about 72 core-hours for nine blocks with HashClash, and about 400,000 hours for a single block.

Why Any Common Suffix Keeps the Collision

MD5 hashes block by block and carries only the state forward. Once two messages reach the same state at the same length, MD5 has no memory of how they got there. So any bytes appended to both files keep them colliding. The padding is the same too, since it depends only on the length.

This is what makes chosen-prefix collisions so dangerous. The colliding blocks can sit in the middle of a file, hidden in a comment or a field nobody reads, and everything after them can be shared. In 2008 a team that included Stevens used this to make two X.509 certificates with the same MD5: an ordinary website certificate, and a certificate authority of their own. A real authority signed the first, and that signature was valid for the second.

Interactive Visualizer

The visualizer above holds the two real files and runs MD5 on them in your browser. Click Absorb Next Block to feed both files through MD5 one block at a time. Each row shows the two states after that block, with the differing hex digits highlighted, the message difference in word 11, and a bar for the number of differing bits.

Watch the first row. The two states look unrelated, yet their first eight hex digits, word a, already match. Then watch the bar shrink, block by block, until it hits zero at block 9. At the end, type any text into the suffix box. Both files get that text appended, and their hashes stay equal.

A Worked Example

Here is the full trace that the code below prints. The column dm11 is the difference in message word 11 between the two blocks. The last column is the state difference, word by word, modulo 2^32.

block  bytes that differ          dm11    state bits that differ  d(a, b, c, d) in hex
    0  prefix + 8 birthday       -                           47  (0, -66b6d6dd, -2828de12, -2828de12)
    1  1 at 0x6f                 +2^26                       46  (0, -68b6d6cd, -2828de02, -2828de02)
    2  1 at 0xad                 +2^11                       43  (0, -6896decd, -2808de02, -2808de02)
    3  1 at 0xec                 +2^6                        43  (0, -6895df0d, -2807de02, -2807de02)
    4  1 at 0x12e                +2^17                       37  (0, -6097df0d, -2007de02, -2007de02)
    5  1 at 0x16d                +2^9                        29  (0, -608fde0d, -1fffde02, -1fffde02)
    6  1 at 0x1ae                +2^23                       21  (0, -600fde0b, -1fffde00, -1fffde00)
    7  1 at 0x1ec                -2^3                        20  (0, -600ffdff, -1ffffe00, -1ffffe00)
    8  1 at 0x22e                +2^19                        6  (0, -3ffffdff, 200, 200)
    9  1 at 0x26f                -2^31                        0  (0, 0, 0, 0)

The pattern is plain in the numbers. Word a never differs. The differences in c and d are equal on every line. Each block nudges b, c and d toward zero. After block 8, only b still differs much, and c and d are off by just 0x200. Block 9 cancels all three at once.

The repository also ships the HashClash collision detector’s log for this pair. It reports a collision in block 9 with a message difference of 0x80000000 in word 11, which is the -2^31 of the last line.

Python Implementation

The code writes MD5 out in full, so that it can print the state after every block. It holds the yes file in hex and builds the no file from the 20 bytes that differ. It checks its MD5 against Python’s hashlib, traces both files, and finally appends a common suffix to show that the collision survives.

# md5_chosen_prefix.py
#
# Checks a real MD5 chosen-prefix collision: one file starts with "yes", the other with "no", and both
# have the same MD5. The pair was made with Marc Stevens' HashClash and is published in Ange Albertini's
# corkami/collisions repository (examples/cpc1.bin and cpc2.bin). MD5 is written out here so that the
# internal state can be printed after every 64-byte block, which shows how the attack works.
import hashlib
import math
import struct

M32 = 0xFFFFFFFF
K = [int(abs(math.sin(i + 1)) * 2 ** 32) & M32 for i in range(64)]
S = [7, 12, 17, 22] * 4 + [5, 9, 14, 20] * 4 + [4, 11, 16, 23] * 4 + [6, 10, 15, 21] * 4
IV = (0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476)


def rotl(x, s):
    return ((x << s) | (x >> (32 - s))) & M32


def compress(ihv, block):
    """One MD5 compression: the state (a, b, c, d) absorbs one 64-byte block."""
    w = struct.unpack("<16I", block)
    a, b, c, d = ihv
    for i in range(64):
        if i < 16:
            f, g = (b & c) | (~b & d), i
        elif i < 32:
            f, g = (d & b) | (~d & c), (5 * i + 1) % 16
        elif i < 48:
            f, g = b ^ c ^ d, (3 * i + 5) % 16
        else:
            f, g = c ^ (b | (~d & M32)), (7 * i) % 16
        a, b, c, d = d, (b + rotl((a + f + K[i] + w[g]) & M32, S[i])) & M32, b, c
    return tuple((x + y) & M32 for x, y in zip(ihv, (a, b, c, d)))


def pad(data):
    return data + b"\x80" + b"\0" * ((55 - len(data)) % 64) + struct.pack("<Q", 8 * len(data))


def md5(data):
    ihv = IV
    padded = pad(data)
    for i in range(0, len(padded), 64):
        ihv = compress(ihv, padded[i:i + 64])
    return struct.pack("<4I", *ihv).hex()


def state_hex(ihv):
    return struct.pack("<4I", *ihv).hex()


def signed(x):
    return x - 2 ** 32 if x >= 2 ** 31 else x


def power_of_two(x):
    """Writes a signed power of two as +2^k or -2^k."""
    return ("-" if x < 0 else "+") + "2^%d" % (abs(x).bit_length() - 1)


YES = bytes.fromhex(
    "7965730000000000000000000000000000000000000000000000000000000000"
    "000000000000000000000000000000000000000000000000b74638098a46f17b"
    "f34526136660c801b92a75255a6723a6923deb8db0b757f1459f2295bec04375"
    "9198a2d3e0fd59edd1c5fa0b7965974db3b3e40c110c9032de4ba14bb81b5ec8"
    "25d38f19cd104307d9bbff8cb75a23f94dd8131458a33597c5d1d4a99ae2fd1f"
    "ba784000c37e93b231a36e2d346a4ac9534ec045361ec86a5698e6f0571d6198"
    "13fcffcd4d83a2d2bbb8dc042be2b883db5380d73de997d3235a27f9989ae756"
    "7d86e4351eb833eeea15d181ba9662ec7531fbda4fae246f67d6af109629fbc7"
    "a332bba9ead5e4ae1fc2fb234122b2e0691e29206f5b201e5e3d112f3e4d9f39"
    "8bc95c93a5efa4227d9a66516eedad703290d4bd6792389bdc150dbfdc717227"
    "e05b43fa4459e860f7637ff0730ad4be3328aa992c902dd00158e38f58503099"
    "e860db910013c91d7a619b9a5d5ebd71231ad2bda6e038660b8cf599567963d6"
    "6e5ed77ec34e9d5f6523c038c9555aa1e23cca78584db53b0445c3b444c88726"
    "0260f662913470fec334546d76077f1a7353e60b08fb8280ad5f22151869b56e"
    "bb06c3a7ff391552befed45cd2555a71ece9bc1ab7bb0861c53ee7897c9303fc"
    "1f8a9ad842bf6c016a3926847458e2e400d4677b27bd936ddff0104a2b007e68"
    "1dded58a6789ea520c32bd30a28cbed0a735bac6bb7d07804922efe510b2836d"
    "e6186ee3f052e435836142357297c58d4ff793685a705f5a043ad542c1fa0fe2"
    "ae57dbaff151b8b73818ef2eb8a6a92c8187fafeb2c4dc45a364916db86ef5d1"
    "4f9cfa623d4246596732ec99da897a88e7ade321ed3c4bc04d9f833cdc7fb70a"
)
# the "no" file differs from the "yes" file in only these 20 bytes (offset: new value)
DIFF = {0x000: 0x6E, 0x001: 0x6F, 0x002: 0x00,                                  # the chosen prefixes
        0x038: 0x19, 0x039: 0x71, 0x03A: 0xE7, 0x03B: 0xF7,                     # the birthday bytes
        0x03C: 0x09, 0x03D: 0x72, 0x03E: 0xFB, 0x03F: 0x06,
        0x06F: 0x51, 0x0AD: 0x72, 0x0EC: 0xFA, 0x12E: 0xAF, 0x16D: 0x60,        # one byte in each
        0x1AE: 0xFF, 0x1EC: 0x6C, 0x22E: 0xCD, 0x26F: 0x08}                     # near-collision block
NO = bytes(DIFF.get(i, b) for i, b in enumerate(YES))


if __name__ == "__main__":
    for t in (b"", b"abc", b"message digest", bytes(range(256)) * 3):
        assert md5(t) == hashlib.md5(t).hexdigest()
    print("prefixes:", YES[:3], NO[:3], "| lengths:", len(YES), len(NO))
    print("block  bytes that differ          dm11    state bits that differ  d(a, b, c, d) in hex")
    ha = hb = IV
    for blk in range(len(YES) // 64):
        x, y = YES[64 * blk:64 * blk + 64], NO[64 * blk:64 * blk + 64]
        ha, hb = compress(ha, x), compress(hb, y)
        where = [64 * blk + i for i in range(64) if x[i] != y[i]]
        dm = signed((struct.unpack("<16I", y)[11] - struct.unpack("<16I", x)[11]) & M32)
        bits = sum(bin(p ^ q).count("1") for p, q in zip(ha, hb))
        diff = ", ".join("%x" % signed((q - p) & M32) for p, q in zip(ha, hb))
        print("%5d  %-24s  %-6s  %22d  (%s)" % (blk, "%d at %#x" % (len(where), where[0]) if blk else
              "prefix + %d birthday" % (len(where) - 3), power_of_two(dm) if blk else "-", bits, diff))
    print("state after the last block:", state_hex(ha), state_hex(hb))
    print("md5(yes) =", md5(YES), "  hashlib:", hashlib.md5(YES).hexdigest())
    print("md5(no)  =", md5(NO), "  hashlib:", hashlib.md5(NO).hexdigest())
    tail = b" ...and anything appended to both files keeps them colliding."
    print("with a common suffix:", md5(YES + tail), md5(NO + tail))

Running the file prints this output:

prefixes: b'yes' b'no\x00' | lengths: 640 640
block  bytes that differ          dm11    state bits that differ  d(a, b, c, d) in hex
    0  prefix + 8 birthday       -                           47  (0, -66b6d6dd, -2828de12, -2828de12)
    1  1 at 0x6f                 +2^26                       46  (0, -68b6d6cd, -2828de02, -2828de02)
    2  1 at 0xad                 +2^11                       43  (0, -6896decd, -2808de02, -2808de02)
    3  1 at 0xec                 +2^6                        43  (0, -6895df0d, -2807de02, -2807de02)
    4  1 at 0x12e                +2^17                       37  (0, -6097df0d, -2007de02, -2007de02)
    5  1 at 0x16d                +2^9                        29  (0, -608fde0d, -1fffde02, -1fffde02)
    6  1 at 0x1ae                +2^23                       21  (0, -600fde0b, -1fffde00, -1fffde00)
    7  1 at 0x1ec                -2^3                        20  (0, -600ffdff, -1ffffe00, -1ffffe00)
    8  1 at 0x22e                +2^19                        6  (0, -3ffffdff, 200, 200)
    9  1 at 0x26f                -2^31                        0  (0, 0, 0, 0)
state after the last block: f5f3a9bfcfd21ab7129ad02c48b2cf78 f5f3a9bfcfd21ab7129ad02c48b2cf78
md5(yes) = eee3c5912df242d08b0662563f34819d   hashlib: eee3c5912df242d08b0662563f34819d
md5(no)  = eee3c5912df242d08b0662563f34819d   hashlib: eee3c5912df242d08b0662563f34819d
with a common suffix: d359a33ca288183c9af867188d7e78e4 d359a33ca288183c9af867188d7e78e4

I checked the pair and the code in several ways. The bytes in the code are identical to cpc1.bin and cpc2.bin as downloaded from the repository. The handwritten MD5 matches hashlib on the test strings and on both files. The visualizer runs a JavaScript copy of the same MD5. Its state after every block matches the Python trace exactly, and it matches the MD5 in Node.js on 300 random messages and on both files with 300 random suffixes. The state before block 9 also matches the detector log in the repository, word for word.

Limitations

This guide checks a collision, it does not compute one:

  • No collision is computed here. The birthday search and the differential paths take HashClash, a large C++ toolset, and many core-hours. The pair is real, but it was made elsewhere.
  • The prefixes are tiny. yes and no keep the pair readable. A real attack uses meaningful prefixes, such as two certificates or two documents, and the same method applies to any of them.
  • The tails are not pretty. The collision blocks look like random bytes. Real attacks hide them in a part of the file format that nobody displays, such as a comment, an unused field, or a key that is never checked.
  • The differential paths are not shown. Each near-collision block satisfies a long list of bit conditions inside MD5’s 64 steps. The trace shows what each block achieves, not the conditions that make it work.

Security Status

  • MD5 is broken for anything that needs collision resistance. Identical-prefix collisions take seconds on a laptop. Chosen-prefix collisions take hours to days of computing, which is cheap for a motivated attacker.
  • Real attacks have used it. In late 2007 Stevens and colleagues predicted the 2008 US presidential election by publishing a hash in advance, backed by documents for several candidates with that same MD5. In 2008 they created a rogue certificate authority. In 2012 the Flame malware used a new variant of the attack to forge a Microsoft code-signing certificate.
  • SHA-1 has fallen the same way. Leurent and Peyrin published a practical chosen-prefix collision for SHA-1 in 2020, called SHA-1 is a Shambles. For new systems, use SHA-256, SHA-3 or BLAKE2, which have no known collision attacks.

FAQ

Why can’t I compute a chosen-prefix collision in the browser?

The birthday search alone needs on the order of 2^32 MD5 evaluations per side, and in practice more. Then HashClash has to build nine differential paths and find blocks that satisfy them. That adds up to dozens of core-hours on fast native code, which is far beyond a web page.

Why do the two files differ in only one byte per block?

The near-collision blocks are almost the same on purpose. A small message difference, a single power of two in word 11, causes a controlled change in the state. The differential path makes sure that change cancels part of the existing difference instead of spreading.

Why is word a equal after the first block?

That is the target of the birthday search. The near-collision method used here can cancel a difference where a is equal and c and d move together. So the attacker searches the last bytes of the first block until the two states fall into that shape.

Would SHA-256 fall to the same attack?

SHA-256 would not fall. The attack depends on differential paths through MD5’s specific round functions and message schedule. SHA-256 has a larger state, a stronger message expansion, and no known practical collision attack of any kind.

Can I check whether a file contains a collision like this?

Yes, even from one file. Stevens developed counter-cryptanalysis, which detects the traces of a collision attack inside a single file. It looks for blocks that follow a known attack path. The log for this pair comes from his detector, and the same idea protects Git and GitHub against SHA-1 collisions.

References

  1. Stevens, Marc, Arjen Lenstra, and Benne de Weger. “Chosen-Prefix Collisions for MD5 and Colliding X.509 Certificates for Different Identities,” EUROCRYPT 2007.

  2. Stevens, Marc, et al. “Short Chosen-Prefix Collisions for MD5 and the Creation of a Rogue CA Certificate,” CRYPTO 2009.

  3. Stevens, Marc. “Counter-Cryptanalysis,” CRYPTO 2013 (the collision detector and the analysis of Flame).

  4. Leurent, Gaëtan, and Thomas Peyrin. “SHA-1 is a Shambles: First Chosen-Prefix Collision on SHA-1 and Application to the PGP Web of Trust,” USENIX Security 2020.

  5. Albertini, Ange. “Hash collisions and their exploitations,” the corkami/collisions repository, source of the pair: https://github.com/corkami/collisions

  6. Stevens, Marc. “HashClash: MD5 & SHA-1 Cryptanalysis Toolbox”: https://github.com/cr-marcstevens/hashclash

  7. The MD5 collision breaker on this site, which covers the identical-prefix attack: /blog/md5_collision_breaker_guide/

A visual representation of an MD5 hash collision
Modern & Applied Cryptography Breakers Intermediate

Breaking MD5 with Collision Attacks

Every hash function is vulnerable to a generic birthday attack. MD5 is vulnerable to something worse: a real, structural flaw that produces full 128-bit collisions far faster than any generic attack should allow. Both are demonstrated here, live and verified.

16 min read

A visual representation of recovering a Merkle-Hellman private key from the public key with lattice reduction
Modern & Applied Cryptography Breakers Advanced

Breaking Merkle-Hellman: Recovering the Key from the Public Key

Shamir broke the basic Merkle-Hellman knapsack in 1982 without seeing a single ciphertext. This guide rebuilds his key-recovery attack with a small LLL lattice, finds a working private key for the guide's 32-bit key in milliseconds, and measures it on keys of up to 256 bits.

21 min read

A visual representation of factoring a Rabin modulus from the answers of a decryption oracle
Modern & Applied Cryptography Breakers Intermediate

Breaking Rabin with a Chosen-Ciphertext Attack

Redundancy lets a Rabin receiver pick the right one of four square roots, and it is often said to stop the chosen-ciphertext attack. It only slows it down. This guide factors a Rabin key from the receiver's answers alone, in about 2^(k-1) queries for k bits of redundancy, and then factors a 64-bit key from the ciphertext alone.

18 min read