Cryptographic Hash Functions
A cryptographic hash function maps data of any length to a short fixed-size digest, like a fingerprint. Signatures sign hashes, passwords are stored as (slow, salted) hashes, Git names commits by their hash and blockchains chain blocks with them. This lesson states the security properties precisely and tests them on SHA-256.
Definition and properties
A hash function is cryptographic if:
- Preimage resistance (one-way): given , finding any with takes about work.
- Second-preimage resistance: given , finding with takes about work.
- Collision resistance: finding any pair with takes about work, the birthday bound.
Collisions must exist (infinitely many inputs, outputs: pigeonhole), but nobody should be able to find one.
import hashlib
for msg in (b"", b"abc", b"abd", b"The quick brown fox jumps over the lazy dog"):
print(f"{msg[:20]!r:24} {hashlib.sha256(msg).hexdigest()}")b'' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
b'abc' ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
b'abd' a52d159f262b2c6ddb724a61840befc36eb30c88877a4030b65cbe86298449c9
b'The quick brown fox ' d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
The avalanche effect
Changing one input bit should flip each output bit with probability 1/2, independently. Then nearby inputs give unrelated digests, and no partial information about the input leaks.
import hashlib
def bits(b):
return int.from_bytes(b, "big")
base = b"transfer 100 EUR to account 12345"
h0 = bits(hashlib.sha256(base).digest())
flips = []
for i in range(len(base) * 8):
m = bytearray(base)
m[i // 8] ^= 1 << (i % 8)
flips.append(bin(h0 ^ bits(hashlib.sha256(bytes(m)).digest())).count("1"))
print("input bits:", len(flips), " average output bits flipped:", sum(flips) / len(flips))
print("min / max:", min(flips), max(flips))input bits: 264 average output bits flipped: 127.73106060606061
min / max: 106 151
The average is close to 128 of 256, as for a random function.
Why one-wayness is plausible but brute force is not
There is no proof that SHA-256 is one-way; confidence comes from decades of public cryptanalysis. What we can measure is brute force: finding an input whose hash starts with zero bits takes about tries. Bitcoin mining is exactly this search, with around 78 today.
import hashlib
def mine(prefix, zero_bits):
target = 1 << (256 - zero_bits)
nonce = 0
while int.from_bytes(hashlib.sha256(prefix + nonce.to_bytes(8, "big")).digest(), "big") >= target:
nonce += 1
return nonce
for k in (4, 8, 12, 16):
print(f"{k:2} leading zero bits: nonce {mine(b'block-42', k):6} (expected about {2**k})") 4 leading zero bits: nonce 43 (expected about 16)
8 leading zero bits: nonce 91 (expected about 256)
12 leading zero bits: nonce 206 (expected about 4096)
16 leading zero bits: nonce 71489 (expected about 65536)
Each 4 extra bits multiplies the work by 16 on average; at 256 bits the search is hopeless.
Broken and current hash functions
| Function | Output | Status |
|---|---|---|
| MD5 | 128 bits | collisions in seconds (2004); never use for security |
| SHA-1 | 160 bits | practical collision "SHAttered" (2017); deprecated |
| SHA-256 / SHA-512 (SHA-2) | 256 / 512 | secure; Merkle-Damgård construction |
| SHA3-256 (Keccak) | 256 | secure; sponge construction, different design |
| BLAKE2 / BLAKE3 | 256+ | secure and fast in software |
import hashlib
data = b"number theory"
for name in ("md5", "sha1", "sha256", "sha3_256", "blake2s"):
h = hashlib.new(name, data)
print(f"{name:9} {h.digest_size * 8:3} bits {h.hexdigest()[:32]}...")md5 128 bits 7b965a78e6b8facc94327d0ceab0626e...
sha1 160 bits 54f049c01b5bf031a87220f504c30e17...
sha256 256 bits a82d9086889a25f8eee60f04a6a2c7f6...
sha3_256 256 bits e906582507983c1575f739ff6d784e84...
blake2s 256 bits f8d9cead245c0f64179c17f0eefd0cbc...
Hashes for passwords are different
General-purpose hashes are designed to be fast, which helps attackers guess passwords. Password storage uses deliberately slow, salted, memory-hard functions (Argon2id, scrypt, bcrypt, PBKDF2 with many iterations); see Password Storage.
In software
- Python's
hashlib, OpenSSL'sEVP_Digest,sha256sum; Git object ids (SHA-1, moving to SHA-256); Docker image digests (sha256:...). - Do not use a hash as a MAC by writing
H(key || message): that is vulnerable to length extension (Merkle-Damgård, Length Extension and HMAC).
Exercises
Exercise 1: Which property?
Name the property each attack breaks: (a) given a password hash, find a password that produces it; (b) create two contracts with the same hash, sign the harmless one, later claim the other was signed; (c) given a signed file, produce a different file with the same hash.
Answer
(a) preimage, (b) collision, (c) second preimage.
Solution
In (b) the attacker chooses both inputs, so only collision resistance is needed to stop it, and that costs just for a generic attack: this is why hash outputs are twice the security level.
Exercise 2: Pigeonhole
Why can no hash function with 256-bit output be collision-free on all 300-bit inputs?
Answer
inputs map into outputs.
Solution
By the pigeonhole principle some output is hit by at least inputs. Collision resistance is about the difficulty of finding them.
Exercise 3: Partial preimage (code)
Find the smallest nonce such that sha256(b"lesson" + str(i).encode()) starts with the hex digits 000.
Answer
Run the search; it needs about tries on average.
Solution
import hashlib
i = 0
while not hashlib.sha256(b"lesson" + str(i).encode()).hexdigest().startswith("000"):
i += 1
print(i, hashlib.sha256(b"lesson" + str(i).encode()).hexdigest()[:16])14719 00055cf2cd382fec
Three hex digits are 12 bits, so each try succeeds with probability .
Test yourself
For an ideal -bit hash, finding a collision costs about…
Which hash function has practical collision attacks?
- SHA-256
- SHA3-256
- MD5
- BLAKE2s
The avalanche effect means…
- hashes get longer with longer input
- flipping one input bit flips about half of the output bits
- hashes are reversible
- outputs avalanche into zeros