Sub topic 11
What cryptographic hashes add
This chapter assumes you know the basics from earlier chapters: a hash maps input to a fixed-size value, collisions are unavoidable, and the birthday bound says an n-bit hash collides after about 2^(n/2) inputs. You should also be comfortable with Python and hexadecimal.
The problem: hashes under attack
A hash table hash such as FNV-1a only has to spread honest keys evenly. Nobody is trying to make it fail on purpose. A cryptographic hash has to hold up against an adversary who knows the algorithm, has plenty of computing power, and chooses inputs deliberately.
That changes the requirements. Determinism, uniformity, speed and avalanche behavior still matter. A cryptographic hash adds three resistance properties, each defined by what the attacker is given and what they must produce.
The three resistance properties
Throughout, H is the hash function, n is its output size in bits, and "work" means the number of hash evaluations.
- Preimage resistance. Given a digest y, it is infeasible to find any input x with H(x) = y. This is also called one-wayness.
- Second-preimage resistance. Given a specific input x1, it is infeasible to find a different input x2 with H(x2) = H(x1).
- Collision resistance. It is infeasible to find any two different inputs x1 and x2 with H(x1) = H(x2). The attacker chooses both.
Generic attack costs
For a well-designed hash, the best known attack is brute force, so the output size sets the ceiling.
| Property | Attacker is given | Generic work for n bits | SHA-256 (n = 256) |
|---|---|---|---|
| Preimage | A digest | about 2^n | about 2^256 |
| Second preimage | One message | about 2^n | about 2^256 |
| Collision | Nothing | about 2^(n/2) | about 2^128 |
Collisions are cheapest because of the birthday bound. The attacker does not need to hit a particular target. Any pair that matches counts, and the number of pairs grows with the square of the number of hashes computed. This is why a hash needs roughly twice as many output bits as the security level you want against collisions. A 256-bit hash gives about 128 bits of collision security.
How the properties relate
A second-preimage attack gives you a collision, because you now hold two different messages with the same digest. So collision resistance implies second-preimage resistance in practice. The reverse does not hold: a hash can resist second-preimage attacks and still have collisions that are cheap to find.
Preimage resistance is a separate property. A hash can have easy collisions and still be hard to invert. History reflects this: practical collisions in MD5 and SHA-1 were found long before practical preimage attacks.
Seeing the gap with a toy experiment
You can feel the difference between 2^n and 2^(n/2) by truncating SHA-256 to 16 bits and attacking it. The code searches for a preimage of a fixed target, then for any collision.
import hashlib
import itertools
def h(data: bytes, bits: int) -> int:
"""SHA-256 truncated to the top `bits` bits."""
full = int.from_bytes(hashlib.sha256(data).digest(), "big")
return full >> (256 - bits)
def find_preimage(target: int, bits: int) -> int:
"""Return how many tries it took to hit the target digest."""
for i in itertools.count():
if h(str(i).encode(), bits) == target:
return i + 1
def find_collision(bits: int) -> int:
"""Return how many tries it took to see any digest twice."""
seen = set()
for i in itertools.count():
v = h(str(i).encode(), bits)
if v in seen:
return i + 1
seen.add(v)
bits = 16
target = h(b"target message", bits)
print("preimage tries:", find_preimage(target, bits))
print("collision tries:", find_collision(bits))A typical run needs tens of thousands of tries for the preimage, since the expected cost is about 2^16 = 65,536. The collision needs a few hundred, since the expected cost is about 2^8 = 256 to 320. The exact numbers vary from run to run.
Note that find_preimage also works as a second-preimage search. If the target is the digest of a known message, any hit with a different input is a second preimage.
Why this scales so badly for the defender
Each extra output bit doubles the preimage cost and multiplies the collision cost by about 1.41. At 16 bits the whole experiment runs in a fraction of a second. At 128 bits a collision search needs about 2^64 evaluations, which is expensive but reachable for well-funded attackers. At 256 bits it is not feasible with any known approach.
Why non-cryptographic hashes fail
FNV-1a, polynomial hashes and similar designs break these properties for structural reasons.
- They are too small. A 32-bit hash has a collision cost of about 2^16 evaluations, which takes milliseconds.
- They are algebraically simple. FNV-1a XORs a byte and multiplies by an odd constant modulo 2^32. Multiplying by an odd number modulo a power of two is invertible, so each step can be undone given the byte. Attackers can therefore construct colliding inputs directly instead of searching for them.
- They were never analyzed against attack. Cryptographic hashes are published, studied by cryptanalysts for years, and retired when attacks appear.
What "infeasible" does and does not cover
Preimage resistance assumes the input is hard to guess. If the attacker can enumerate the plausible inputs, they do not need to invert anything. They hash each guess and compare.
import hashlib
stolen_digest = hashlib.sha256(b"summer2024").hexdigest()
guesses = [b"password", b"123456", b"summer2024", b"letmein"]
for guess in guesses:
if hashlib.sha256(guess).hexdigest() == stolen_digest:
print("recovered:", guess.decode())SHA-256 is working as designed here. The input simply has too little entropy. This is why passwords need a different tool, covered in a later chapter.
Two more limits matter in practice:
- A hash is not encryption. There is no key and no way to recover the message, so a digest cannot hide data that is easy to guess.
- SHA-256 allows length extension. From H(secret + message) and the length of the secret, an attacker can compute H(secret + message + padding + extra) without knowing the secret. So
sha256(key + message)is not a safe authentication tag. HMAC, covered later, fixes this.
Choosing which property you rely on
Decide which game your attacker plays.
| Scenario | Property you rely on |
|---|---|
| Verifying that a download matches a published digest | Second-preimage resistance (the attacker must match a fixed file) |
| Signing a document that someone else prepared | Collision resistance (the attacker may prepare two versions in advance) |
| Storing only a digest of a high-entropy secret | Preimage resistance |
When in doubt, choose a hash with enough output bits that collision resistance holds. It is the strongest requirement, and the others follow in practice.
Exercise
A hash has a 160-bit output and no known weaknesses. About how much work does the best generic attack need for (a) a preimage and (b) a collision?
Show answer
(a) About 2^160 evaluations. (b) About 2^80 evaluations, because the birthday bound halves the exponent. Collision resistance is therefore the weakest of the three properties for a given output size.
Exercise
A software vendor lets a contractor submit a build script. The vendor reviews it, signs its hash, and ships it. Which property must the hash have to stop the contractor from swapping in a malicious script after review, and why is a 32-bit hash unsafe here?
Show answer
Collision resistance. The contractor can prepare a harmless script and a malicious one with the same digest before submitting, since they control both inputs. A 32-bit hash needs only about 2^16 evaluations to find such a pair, which takes milliseconds.