Sub topic 12
When a Hash Breaks: MD5 and SHA-1
This chapter assumes you know the three cryptographic properties from the previous chapter: preimage, second-preimage, and collision resistance. It also assumes you can use the birthday bound to estimate collision odds. Here you will see what it means for a hash to be "broken", how MD5 and SHA-1 failed, and which jobs they can still do.
What "broken" means
A hash function is broken when someone finds an attack that is cheaper than the generic attack for its output size. Generic attacks work on any hash:
- Finding a preimage by brute force costs about 2^n hashes for an n-bit output.
- Finding a collision with the birthday bound costs about 2^(n/2) hashes.
So a 128-bit hash should need about 2^64 work to collide, and a 160-bit hash about 2^80. A function counts as broken for collisions when a method needs far less than that. It does not need to be cheap for everyone. Once the cost is within reach of a well-funded attacker, the function is unsafe for any use that depends on collision resistance.
"Broken" is also specific to a property. MD5 and SHA-1 both fail at collision resistance. Neither has a practical preimage or second-preimage attack. Most of the decisions in this chapter depend on that difference.
How the two functions failed
Both functions were designed to be fast, and both use the same Merkle–Damgård structure. That design processes the message in fixed-size blocks and feeds a running internal state from one block to the next. Researchers found that they could steer differences between two messages through the internal rounds so that the differences cancelled out. This is differential cryptanalysis, and it needs far less work than random guessing.
The MD5 collisions published in 2004 could be computed in hours on ordinary hardware, and later work reduced that to seconds. The SHA-1 attack was theoretical for twelve years. In 2017 researchers at Google and CWI Amsterdam produced two different PDF files with the same SHA-1 hash. It took roughly 2^63 SHA-1 computations, which is about 9 quintillion hashes spread over GPUs and CPUs. That is expensive, but it is well below the 2^80 that a 160-bit hash is supposed to cost.
Identical-prefix and chosen-prefix collisions
The two kinds of collision attack differ a great deal in how dangerous they are.
- Identical-prefix collision. The attacker picks one shared prefix, and the algorithm produces two different blocks that make the hashes match. The attacker has little control over the content of those blocks, which look like random bytes.
- Chosen-prefix collision. The attacker picks two different prefixes, for example two different certificate subjects. The algorithm then computes extra blocks that make the two full messages hash identically.
Both kinds exploit a structural property. If H(a) == H(b) and a and b have the same length, then H(a + s) == H(b + s) for any suffix s. The internal state after a and after b is identical, so everything after that is identical too.
Chosen-prefix collisions are the ones that matter in practice. They let an attacker build two documents that look legitimate and different but share one hash. Chosen-prefix collisions for MD5 appeared in 2007. They were practical for SHA-1 by 2020, at an estimated cost of tens of thousands of US dollars in rented GPU time.
Real attacks
- Rogue CA (2008). Researchers submitted a normal certificate request to a commercial authority that still signed with MD5. They had built a second, malicious certificate that collided with it, so the signature on the first was valid for the second. The second certificate was a CA certificate, which could then sign certificates for any website.
- Flame (2012). This malware used an MD5 chosen-prefix collision to forge a Microsoft code-signing certificate, so it could spread as if Microsoft had signed it.
- SHA-1 in the web of trust (2020). A chosen-prefix collision allowed impersonation attacks on PGP keys.
Each attack targeted a signature, where a trusted party signs a hash of a document. If two documents share a hash, a signature on one is also a signature on the other.
Seeing the birthday bound in action
You cannot reproduce a real MD5 collision attack in a few lines. You can show the generic bound that those attacks beat. This script truncates MD5 to 32 bits and searches for a collision by brute force:
import hashlib
def trunc_md5(data: bytes, bits: int = 32) -> int:
digest = int.from_bytes(hashlib.md5(data).digest(), "big")
return digest >> (128 - bits)
seen = {}
i = 0
while True:
msg = str(i).encode()
t = trunc_md5(msg)
if t in seen:
print(f"collision after {i + 1} messages")
print(seen[t], msg, hex(t))
break
seen[t] = msg
i += 1The search typically ends after tens of thousands of messages, matching the birthday estimate for 32 bits from the earlier chapter. Full MD5 has a 128-bit output, so the same method would need about 2^64 hashes. The cryptanalytic attacks avoid that cost by using the structure of the algorithm. A break means the shortcut exists, not that the output is too short.
You can compare the output sizes directly:
import hashlib
for name in ("md5", "sha1", "sha256"):
h = hashlib.new(name, b"hello world")
print(name, h.digest_size * 8, "bits", h.hexdigest())What is still safe, and what is not
Because only collision resistance fell, the answer depends on the job.
| Use | MD5 / SHA-1 verdict | Reason |
|---|---|---|
| Digital signatures, certificates | Do not use | Signature forgery needs only a collision |
| Integrity check against a malicious party | Do not use | An attacker can craft two files with one hash |
| Content-addressed storage with untrusted writers | Do not use | An attacker can plant a colliding object |
| Detecting accidental corruption | Acceptable | Random errors do not target collisions |
| Cache keys, deduplication of trusted data | Acceptable | No adversary controls the inputs |
| HMAC-SHA1 for legacy protocols | Tolerable, avoid in new designs | HMAC does not rely on collision resistance |
| Password storage | Never | Fast hashes are the wrong tool regardless of collisions |
Python marks non-security use of these functions explicitly. On FIPS-restricted systems, MD5 can be disabled unless you declare that the use is not for security:
import hashlib
checksum = hashlib.md5(b"payload", usedforsecurity=False).hexdigest()
print(checksum)The usedforsecurity argument is available since Python 3.9. It documents your intent for the next reader, and it keeps the code working on restricted systems.
Migrating away
Git is a well-known case of a system built on SHA-1. After SHAttered, Git switched to a hardened SHA-1 implementation that detects the telltale bit patterns of known collision attacks, and it added support for SHA-256 repositories. Browsers stopped accepting SHA-1 certificates in 2017. NIST has announced that SHA-1 should be phased out by 2030.
When you replace a broken hash in your own system:
- Find every place the hash is used, including stored values, protocol fields, and file names.
- Decide whether each use depends on collision resistance. Signatures and trust decisions come first.
- Store the algorithm name next to each digest, such as
sha256:..., so you can change it again later. - Re-hash stored data where the original input is available. Where it is not, keep the old digests for lookup only and never for trust decisions.
- Remove the old algorithm after a transition period, rather than leaving both accepted.
Exercise
A build system identifies cached artifacts by their MD5 hash. The artifacts are produced only by your own trusted CI servers. A colleague says the system must move to SHA-256 immediately because MD5 is broken. Is the colleague right? What would change your answer?
Show answer
For the current design the risk is low, because no attacker controls the inputs, and accidental MD5 collisions are as unlikely as for any 128-bit hash. The collision attacks need an adversary who can craft the artifacts. The answer changes if outside contributors can submit inputs that CI hashes, or if the hash is used to verify downloads or signatures. Then an attacker could plant a colliding artifact, and SHA-256 is needed. Even in the low-risk case, switching is cheap and removes the need to reason about the question again.
Exercise
Explain why a chosen-prefix collision is more dangerous than an identical-prefix collision for a certificate authority that signs certificate requests.
Show answer
With an identical-prefix collision the attacker cannot control the meaningful content, since the colliding blocks look like random bytes after a shared prefix. With a chosen-prefix collision the attacker picks two different meaningful prefixes, such as a harmless website certificate and a CA certificate. The extra blocks make both hash the same. The authority signs the harmless one, and the signature is also valid for the malicious one.