Sub topic 8
Measuring the avalanche effect
This chapter assumes you can read Python, use XOR and shifts, and have seen the earlier chapters on determinism, uniformity, and mapping hash values to buckets. You will build a small test harness that measures how well a hash function mixes its input. You will then run it on three hash functions from earlier chapters.
What the avalanche effect is
A hash function has good avalanche behavior if a tiny change to the input changes the output in an unpredictable way. Flip one input bit, and each output bit should flip with probability 1/2, independently of the others. A hash that behaves this way satisfies the strict avalanche criterion (SAC).
Avalanche matters for two reasons:
- Bucket choice. Similar keys such as
user1,user2, anduser3should land in unrelated buckets. If similar inputs give similar hashes, they cluster, and a hash table slows down. - Cryptographic strength. If a one-bit change leaves a pattern in the output, an attacker can use that pattern. Cryptographic hashes need near-perfect avalanche in every output bit.
Avalanche is a statistical property. You cannot prove it with one example. You measure it over many random inputs.
The measurement procedure
The test works like this:
- Pick a random message.
- Hash it to get a baseline.
- Flip one input bit and hash again.
- XOR the two hashes. Each 1 in the result marks an output bit that changed.
- Repeat for every input bit and many random messages, and count how often each output bit changes.
The result is a matrix with one row per input bit and one column per output bit. Each cell holds the fraction of trials in which that output bit flipped. For an ideal hash, every cell is close to 0.5.
A reusable harness
The code below measures any function that maps bytes to an integer. It uses random.Random(seed).randbytes, which needs Python 3.9 or later. The seed makes runs repeatable.
import hashlib
import random
def sum_hash32(data: bytes) -> int:
return sum(data) & 0xFFFFFFFF
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF
return h
def sha256_32(data: bytes) -> int:
return int.from_bytes(hashlib.sha256(data).digest()[:4], "big")
def flip_bit(data: bytes, i: int) -> bytes:
out = bytearray(data)
out[i // 8] ^= 1 << (i % 8)
return bytes(out)
def avalanche_matrix(hash_fn, out_bits=32, msg_len=8, trials=1000, seed=1):
rng = random.Random(seed)
in_bits = msg_len * 8
counts = [[0] * out_bits for _ in range(in_bits)]
for _ in range(trials):
msg = rng.randbytes(msg_len)
base = hash_fn(msg)
for i in range(in_bits):
diff = base ^ hash_fn(flip_bit(msg, i))
for j in range(out_bits):
if (diff >> j) & 1:
counts[i][j] += 1
return [[c / trials for c in row] for row in counts]
def summarize(name, matrix):
cells = [f for row in matrix for f in row]
mean = sum(cells) / len(cells)
worst = max(abs(f - 0.5) for f in cells)
print(f"{name:10s} mean flip rate {mean:.3f} worst bias {worst:.3f}")
for name, fn in [("sum", sum_hash32), ("fnv1a", fnv1a_32), ("sha256/32", sha256_32)]:
summarize(name, avalanche_matrix(fn))To keep the comparison fair, the harness truncates SHA-256 to its first 32 bits. All three functions then have the same output width.
Reading the results
Two numbers summarize each matrix. The mean flip rate is the average over all cells. The worst bias is the largest distance of any single cell from 0.5.
| Statistic | Ideal value | What a bad value means |
|---|---|---|
| Mean flip rate | 0.5 | The hash changes too few output bits (or too many, which is rare). |
| Worst bias | Near 0 | Some output bit barely reacts to some input bit. |
Random noise sets the floor for the worst bias. With 1000 trials per cell, the standard deviation of a measured rate is about 0.5 / sqrt(1000), or 0.016. Across 2048 cells, a perfect hash still shows a worst bias of roughly 0.05 to 0.07. Do not chase that residual. Raise trials to shrink it.
Here is what you should expect from the three functions.
- Sum of bytes. The mean flip rate is far below 0.5, because flipping one input bit adds or subtracts a power of two, which changes only a few output bits through carries. The high output bits almost never flip, so the worst bias approaches 0.5. This is the failure behind the anagram collisions you saw earlier.
- FNV-1a. The mean flip rate is much better, but the worst bias is large. The reason is explained in the next section.
- SHA-256 (truncated). Every cell sits near 0.5, and the worst bias is just noise.
You can also check the full 256-bit output of SHA-256. Flipping one bit of b"hello world" changes about 128 of the 256 output bits, which is the half you would expect.
Why FNV-1a has uneven avalanche
FNV-1a XORs a byte into the state and then multiplies by an odd prime. In a multiplication, a bit can only influence bits at the same position or higher, because carries travel upward. So if the last byte changes at bit k, the final state can change only at bit k and above. Bits below k are untouched.
This matters directly for bucket selection. Taking h % 16 keeps only the low 4 bits of the hash. Those bits depend on the low 4 bits of the state just before the final multiplication. You can confirm this on a message that differs only in its last byte:
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF
return h
msg = b"hello"
for bit in range(8):
flipped = bytearray(msg)
flipped[-1] ^= 1 << bit
changed = fnv1a_32(msg) % 16 != fnv1a_32(bytes(flipped)) % 16
print(bit, changed)Bits 0 to 3 print True. Bits 4 to 7 print False. A change to the high half of the last byte can never move the key to a different bucket in a 16-bucket table. The mixing exists, but it flows toward the high bits, and a power-of-two modulo reads the low bits.
There are three common remedies:
- Fold the high bits down. Apply
h ^= h >> 16before the modulo, so high-bit mixing reaches the low bits. - Use a prime table size. A prime modulus uses information from all the bits.
- Use a hash with a finalizer. Modern fast hashes end with extra shift-and-multiply steps that mix every bit.
Limits of the test
A good avalanche score is necessary but not sufficient. Keep these cautions in mind:
- Input size. A hash can mix well on 8-byte inputs and poorly on 1-byte inputs. Test the lengths your application uses.
- Input structure. Random messages are the easy case. Real keys are often counters, timestamps, or words from a dictionary. Also measure bucket counts on your real keys.
- Correlation. Each flip rate can be 0.5 while pairs of output bits move together. The SAC measures only single bits. Stricter tests (the bit independence criterion) check pairs.
- Cryptographic security. Avalanche says nothing about preimage or collision resistance. A hash can score perfectly and still be easy to invert. Passing is not proof of security.
Exercise
A hash is truncated to its low 3 bits to choose one of 8 buckets. In the avalanche matrix, the column for output bit 0 has flip rates of 0.50 for every input bit, but columns 1 and 2 show a flip rate of 0.00 for input bits in the last byte. What does this tell you about bucket assignment for keys that differ only in the last byte?
Show answer
Only output bit 0 reacts to the last byte, so bits 1 and 2 never change. Keys that differ only in the last byte can reach just 2 of the 8 buckets, because only bit 0 varies. Four keys that differ in the last byte would collide into those 2 buckets, even if the full hash values differ.
Exercise
Modify summarize so that it also prints the output bit position with the lowest average flip rate. Which position would you expect it to report for sum_hash32 on 8-byte messages, and why?
Show answer
Compute the mean of each column, for example col_means = [sum(row[j] for row in matrix) / len(matrix) for j in range(len(matrix[0]))], then print min(range(len(col_means)), key=col_means.__getitem__). For sum_hash32 on 8-byte messages the sum is at most 8 * 255 = 2040, which fits in 11 bits. A carry would have to reach bit 11 or above, which is impossible, so the high output bits (11 to 31) never flip and have rate 0. The function returns the first of these tied positions, which is bit 11.