Sub topic 14
When Inputs Fight Back: Anti-Hash Tests
So far this tutorial has treated collisions as bad luck. Two different strings land on the same hash value by chance, verification catches the false match, and the expected running time stays at O(n + m). That argument assumes the input does not depend on your hash parameters. If someone can see your base and modulus before choosing the input, they can build strings that collide on purpose. Competitive programming judges do this with "anti-hash tests," and attackers do the same thing to servers that hash untrusted data.
This chapter assumes you know the polynomial hash, the rolling update, the verification step in Rabin-Karp, and the base and modulus choices covered in earlier chapters. You should also be comfortable with Python's & operator for masking bits.
What an Adversary Can Exploit
A polynomial hash with fixed parameters is a fixed, public function. Anyone who knows base and mod can search offline for colliding strings, and some setups have collisions with a known structure that needs no search at all. What the attack achieves depends on how your code uses the hash:
| How the hash is used | Effect of forced collisions |
|---|---|
| Rabin-Karp with verification | Every false match costs an O(m) comparison. With enough of them the search degrades toward O(nm). |
| Hash compared without verification | Wrong answers, such as reporting equal substrings that differ. |
| Hash used as a dictionary key | Keys pile into a few buckets, so lookups slow from O(1) to O(k). |
The second row is the most common target. Prefix-hash comparisons and the binary search for the longest repeated substring usually skip verification because it would cost too much time. Those methods are correct only with high probability, and that probability argument fails once the input is chosen against your parameters.
Attack 1: Overflow Modulo 2^64 Falls to Thue-Morse Strings
A popular shortcut in C++ is to use unsigned long long and let multiplication overflow, which computes the hash modulo 2^64 with no % operation. It is fast, and it is easy to break.
If the base is even, then base^64 is divisible by 2^64, so every character more than 64 positions from the end gets weight zero. Any two strings that share their last 64 characters collide.
If the base is odd, the Thue-Morse construction breaks it. Start with T₀ = "a". To build T{k+1}, append to Tk a copy of itself with every a and b swapped. Let ~Tk be Tk with a and b swapped, and let L = 2^k be the length of T_k. Horner's rule gives:
- hash(T{k+1}) = hash(Tk) · b^L + hash(~T_k)
- hash(~T{k+1}) = hash(~Tk) · b^L + hash(T_k)
Subtract the second line from the first and let Dk = hash(Tk) − hash(~T_k):
D{k+1} = Dk · (b^{2^k} − 1)
For odd b, b − 1 is divisible by 2, and for i ≥ 1, b^{2^i} − 1 is divisible by 2^{i+2}. After ten steps the product contains at least 1 + (3 + 4 + … + 11) = 64 factors of two. So D₁₀ ≡ 0 (mod 2^64) for every odd base, and the two 1024-character strings collide whatever base you picked.
MASK = (1 << 64) - 1
SWAP = str.maketrans("ab", "ba")
def hash64(s, base):
"""Polynomial hash with C-style unsigned 64-bit overflow."""
h = 0
for ch in s:
h = (h * base + ord(ch)) & MASK
return h
def thue_morse(k):
s = "a"
for _ in range(k):
s = s + s.translate(SWAP)
return s
t = thue_morse(10)
u = t.translate(SWAP)
print(len(t), t != u) # 1024 True
for base in (31, 131, 257, 1_000_003, 0x9E3779B97F4A7C15):
print(base, hash64(t, base) == hash64(u, base)) # True for every odd baseAll five checks print True, and the last base is a large random-looking odd constant. Randomizing the base does not protect a 2^64 modulus. The weakness comes from the modulus being a power of two.
Attack 2: Birthday Collisions Against a Known Prime
A prime modulus such as 10^9 + 7 avoids the structural weakness, but it is small. By the birthday bound, hashing about √(π·M/2) random strings gives an even chance of a repeated value. For M ≈ 10^9 that is roughly 40,000 strings, which takes a fraction of a second.
import random
import string
def poly_hash(s, base=256, mod=1_000_000_007):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
def find_collision(base=256, mod=1_000_000_007, length=8, seed=1):
rng = random.Random(seed)
seen = {}
tries = 0
while True:
tries += 1
s = "".join(rng.choice(string.ascii_lowercase) for _ in range(length))
h = poly_hash(s, base, mod)
if h in seen and seen[h] != s:
return seen[h], s, tries
seen[h] = s
a, b, tries = find_collision()
print(a, b, poly_hash(a) == poly_hash(b), tries)The script prints two different 8-letter strings with equal hashes, usually after a few tens of thousands of tries. An attacker who knows your parameters can embed one string as the pattern and fill the text with the other.
Double hashing with two fixed 10^9-scale primes raises the cost of a birthday search to about 10^9 strings, which is slow but possible. Known parameters also allow stronger methods. The "tree attack" combines strings in pairs, level by level, until their hash differences cancel. Lattice reduction finds colliding strings for fixed multi-modulus hashes. Fixed parameters can be broken. Secret, random parameters are what make these attacks fail.
The Defense: Secret Random Base, Large Prime Modulus
The collision bound from the parameter-choice chapter applies when the base is chosen uniformly at random after the input is fixed. Two distinct strings of length L collide only when the base is a root of their difference polynomial, and that polynomial has degree at most L − 1. A nonzero polynomial of that degree has at most L − 1 roots modulo a prime p, so:
Pr[collision] ≤ (L − 1) / p
The adversary cannot aim at a base they do not know. A strong default is the Mersenne prime p = 2^61 − 1 with a base drawn at runtime:
import secrets
MOD = (1 << 61) - 1
BASE = secrets.randbelow(MOD - 256) + 256 # random, larger than the alphabet
def build_prefix(s):
h = [0] * (len(s) + 1)
p = [1] * (len(s) + 1)
for i, ch in enumerate(s):
h[i + 1] = (h[i] * BASE + ord(ch)) % MOD
p[i + 1] = (p[i] * BASE) % MOD
return h, p
def sub(h, p, i, j):
return (h[j] - h[i] * p[j - i]) % MOD
t = "ab" * 50_000
h, p = build_prefix(t)
print(sub(h, p, 0, 1000) == sub(h, p, 2, 1002)) # True: identical substrings
print(sub(h, p, 0, 1000) == sub(h, p, 1, 1001)) # False with overwhelming probabilityWith L = 10^5 and p ≈ 2.3 × 10^18, one comparison collides with probability below 5 × 10^−14. A program making 10^7 comparisons still has a total failure chance under 10^−6, by the union bound. In C++, 2^61 − 1 needs a 128-bit product or the standard shift-and-add reduction, using the same overflow care as the Java and C++ chapter.
This idea also applies outside string search. In 2011, researchers showed that web frameworks hashing request parameters with fixed functions could be stalled by crafted POST bodies full of colliding keys. In response, Python made string-hash randomization the default in version 3.3, controlled by PYTHONHASHSEED.
Verification Still Matters
Randomization limits how likely a collision is. Verification decides what a collision costs. Rabin-Karp that compares text[i:i+m] == pattern on every hash hit always returns correct results, so an attacker who somehow forces collisions can only slow it down. Code that trusts hash equality, such as prefix-hash comparisons or the longest-repeated-substring binary search, has no such fallback, and random parameters are its only protection. When a wrong answer costs more than extra time, add a verification step at the points where a decision is made, or use a deterministic method such as KMP or suffix arrays.
Exercise
A solution uses unsigned 64-bit overflow and sets the base at runtime to a random odd number. Why is it still vulnerable, and what is the shortest Thue-Morse pair the argument in this chapter guarantees will collide?
Show answer
The weakness comes from the modulus 2^64, not from the base. For any odd base, the hash difference of Tk and its swapped copy is a product of terms b^(2^i) − 1, and these supply at least 64 factors of two once k = 10. The 1024-character strings T10 and ~T_10 therefore collide for every odd base, so randomizing the base does not help.
Exercise
You compare 2 × 10^6 pairs of substrings, each up to 2 × 10^5 characters long, using a random base modulo 10^9 + 7. Bound the chance of at least one false equality, and say what change you would make.
Show answer
Each comparison fails with probability at most (L − 1)/p ≈ 2 × 10^5 / 10^9 = 2 × 10^−4. The union bound over 2 × 10^6 comparisons gives about 400, which guarantees nothing, so failures are likely. Switch to p = 2^61 − 1 with a random base. That gives about 2 × 10^5 / 2.3 × 10^18 ≈ 8.7 × 10^−14 per comparison and under 2 × 10^−7 in total. Alternatively, use double hashing with two independently random bases.
Exercise
An attacker knows your Rabin-Karp parameters and your code verifies every hash match. Can they make it return a wrong answer? What can they do instead?
Show answer
They cannot make it return a wrong answer, because every reported match is checked character by character. They can build a text in which many windows collide with the pattern's hash, which forces an O(m) comparison at each one and pushes the running time toward O(nm).