Introduction
The rainbow table attack was introduced by Philippe Oechslin in his 2003 paper "Making a Faster Cryptanalytic Time-Memory Trade-Off" presented at Crypto 2003. Oechslin built on Martin Hellman's 1980 time-memory tradeoff for cryptanalysis, which showed that precomputation can exchange memory for runtime when attacking a function whose inverse is hard. Oechslin's contribution was to use a different reduction function at each chain position so that two chains cannot merge on a collision, which lets a single table cover more of the password space and makes lookups far cheaper.
For a Java learner, the rainbow table attack is the most approachable demonstration of a time-memory tradeoff. It uses only a hash function and a deterministic reduction function, and it shows why unsalted password hashing is catastrophically weak. The 4-character lowercase password space has 26 to the 4th power equals 456976 entries, which a rainbow table with a few thousand entries can crack in seconds; the same attack on a 10-character mixed-character password space would be infeasible, which is exactly why modern systems require long passwords.
What is a Rainbow Table Attack?
A rainbow table attack belongs to the family of precomputation attacks, in which the attacker invests a large amount of time upfront to build a table that allows very fast password recovery later. It is specifically targeted at functions whose input is a small, enumerable space, such as passwords chosen from a constrained character set. The attack is inapplicable to functions whose input is large or random, such as AES keys generated by SecureRandom.
The attack targets a hash function H that maps a plaintext P to a hash H(P). To build the table, the attacker picks a chain length k and a family of k reduction functions R_0, R_1, ..., R_{k-1}, each of which maps a hash back to a plaintext. A chain starts at a plaintext P_0 and computes P_1 = R_0(H(P_0)), P_2 = R_1(H(P_1)), and so on, ending at P_k = R_{k-1}(H(P_{k-1})). The attacker stores only the (P_0, P_k) pair for each chain. To crack a target hash h, the attacker assumes h is at some position i in a chain and applies the remaining reductions to compute the candidate chain end, looks it up in the table, and if found, recomputes the chain from the stored start to find the actual plaintext.
The rainbow table differs from Hellman's original tradeoff in two ways. First, the reduction function is position-dependent, so two chains that collide at some intermediate position continue to differ because they apply different R functions afterwards, preventing chain merging. Second, the lookup cost is O(k^2) instead of Hellman's O(k^2 * t) for t tables, so a single rainbow table can replace several Hellman tables. The trade-off is that one rainbow table covers less of the password space than several Hellman tables of the same total size, but the lookup is dramatically faster.
How a Rainbow Table Attack Works - Step by Step
Step 1: Choose the password space. The attacker enumerates every possible plaintext the victim could have chosen, for example all 4-character lowercase strings. The size of this space determines how large the table must be. For our demo we use 3-character lowercase passwords, which is 26 cubed equals 17576 plaintexts.
Step 2: Build the table. The attacker picks a chain length k and generates N chains, each starting from a random plaintext. For each chain the attacker computes k hash-and-reduce pairs, producing P_0, P_1, ..., P_k. The table stores only (P_k, P_0) pairs. With N chains of length k the table represents N times k distinct preimage candidates, although collisions reduce the effective coverage.
Step 3: Crack a target hash. Given a hash h, the attacker tries every possible position i from 0 to k-1. For each i the attacker assumes h = H(P_i) and applies the remaining reductions to compute the candidate chain end. If the candidate end matches a stored end, the attacker recomputes the chain from the stored start and checks every intermediate hash against h; if a match is found, the corresponding plaintext is the cracked password.
Step 4: Handle false alarms. Two different chains can share a chain end if their final reductions collide, and the recomputed chain from the stored start may not contain the target hash. In that case the attacker tries the next position i, or the next table entry if multiple tables are used. Each false alarm costs k hash computations, but the expected number of false alarms is small.
Step 5: Stop when the password is found or all positions are exhausted. If no candidate end matches any table entry, the target hash is not in the table; the attacker must brute force the remaining portion of the password space directly. The defense against rainbow tables is to add a random per-record salt to the hash function, which forces the attacker to build a separate table for each salt value.
Java Program for Rainbow Table Attack
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class RainbowTableDemo {
static final String CHARSET = "abcdefghijklmnopqrstuvwxyz";
static final int PLAINTEXT_LEN = 3; // 3-char lowercase passwords
static final int CHAIN_LEN = 50; // chain length k
static final int NUM_CHAINS = 200; // number of chains N
static int passwordSpaceSize() {
int n = 1;
for (int i = 0; i < PLAINTEXT_LEN; i++) {
n *= CHARSET.length();
}
return n; // 17576 for 3-char lowercase
}
// MD5 hash truncated to 16 hex chars (64-bit prefix keeps storage small)
static String hash(String plain) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] h = md.digest(plain.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : h) sb.append(String.format("%02x", b & 0xff));
return sb.toString().substring(0, 16);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Position-dependent reduction: maps a hash back to a plaintext.
// Adding the position changes the reduction at each chain step, which
// prevents two chains from merging after they collide.
static String reduce(String hashHex, int position) {
long h = Long.parseUnsignedLong(hashHex, 16);
long mixed = h + (long) position * 0x9E3779B97F4A7C15L;
int idx = (int) Long.remainderUnsigned(mixed, passwordSpaceSize());
return indexToPlain(idx);
}
static String indexToPlain(int idx) {
char[] chars = new char[PLAINTEXT_LEN];
for (int i = PLAINTEXT_LEN - 1; i >= 0; i--) {
chars[i] = CHARSET.charAt(idx % CHARSET.length());
idx /= CHARSET.length();
}
return new String(chars);
}
// Build the rainbow table: maps chain END to chain START.
static Map<String, String> buildTable() {
Map<String, String> table = new HashMap<>();
Random rng = new Random(42); // fixed seed for reproducible demo
for (int c = 0; c < NUM_CHAINS; c++) {
String start = indexToPlain(rng.nextInt(passwordSpaceSize()));
String current = start;
for (int i = 0; i < CHAIN_LEN; i++) {
String h = hash(current);
current = reduce(h, i);
}
// current is now the chain end P_k; store (end, start)
table.put(current, start);
}
return table;
}
// Crack a target hash using the rainbow table.
// Returns the recovered plaintext, or null if not in the table.
static String crack(String targetHash, Map<String, String> table) {
// Try every possible position i where the target hash might sit
for (int i = CHAIN_LEN - 1; i >= 0; i--) {
// Compute the chain end assuming target is at position i
String current = targetHash;
for (int j = i; j < CHAIN_LEN; j++) {
current = reduce(current, j);
if (j < CHAIN_LEN - 1) {
current = hash(current);
}
}
// current is now the candidate end P_k
if (table.containsKey(current)) {
String start = table.get(current);
// Recompute the chain from start to verify
String p = start;
for (int j = 0; j < CHAIN_LEN; j++) {
String h = hash(p);
if (h.equals(targetHash)) {
return p; // verified plaintext
}
p = reduce(h, j);
}
// false alarm: chain end collided but plaintext not here
}
}
return null;
}
public static void main(String[] args) {
System.out.println("Password space: " + PLAINTEXT_LEN
+ "-char lowercase = " + passwordSpaceSize() + " passwords");
System.out.println("Chain length: " + CHAIN_LEN);
System.out.println("Number of chains: " + NUM_CHAINS);
System.out.println("Theoretical coverage: "
+ (100.0 * CHAIN_LEN * NUM_CHAINS / passwordSpaceSize()) + "%");
System.out.println();
long tStart = System.currentTimeMillis();
Map<String, String> table = buildTable();
long tBuild = System.currentTimeMillis() - tStart;
System.out.println("Built table: " + table.size()
+ " entries in " + tBuild + " ms");
System.out.println();
String[] testPasswords = {
"abc", "xyz", "cat", "dog", "foo", "bar",
"zzz", "aaa", "bob", "red", "java", "jvm",
"net", "fox", "owl"
};
int cracked = 0;
long tCrackStart = System.currentTimeMillis();
for (String p : testPasswords) {
String h = hash(p);
String found = crack(h, table);
boolean ok = found != null && found.equals(p);
if (ok) cracked++;
System.out.println(" " + p + " -> " + h
+ " -> " + (found == null ? "(not found)" : found)
+ (ok ? " [CRACKED]" : ""));
}
long tCrack = System.currentTimeMillis() - tCrackStart;
System.out.println();
System.out.println("Cracked " + cracked + "/" + testPasswords.length
+ " test passwords in " + tCrack + " ms");
}
}
Code Explanation - Line by Line
The hash method computes MD5 and returns the first 16 hex characters of the digest, which gives 64 bits of hash output. The truncation keeps the table compact for the demo; production rainbow tables typically store the full hash output. The reduce method is the heart of the rainbow table. It takes a hash and a chain position and produces a plaintext by mixing the hash bits with the position, then taking the result modulo the password space size. The mixing multiplier 0x9E3779B97F4A7C15L is the golden ratio constant used in many hash tables to spread bits evenly; adding position times this constant ensures that two chains colliding at some intermediate position continue to differ because they apply reduce with different position arguments afterwards.
The indexToPlain method converts an integer index into a plaintext by treating the password as a base-26 number with digits from the CHARSET string. The conversion goes from right to left so that index 0 produces "aaa", index 1 produces "aab", and so on up to index 17575 producing "zzz". The buildTable method generates NUM_CHAINS chains, each starting from a random plaintext. For each chain it computes CHAIN_LEN hash-and-reduce pairs and stores only the start and end pairs in a HashMap keyed by chain end.
The crack method is the lookup. For each candidate position i from CHAIN_LEN-1 down to 0, the method assumes the target hash sits at that position in some chain. It applies the remaining reductions to compute the chain end that would result if the assumption were true, then checks whether that end exists in the table. If it does, the method retrieves the chain start and recomputes the chain from the start, checking each intermediate hash against the target. The verification step catches false alarms, which occur when two different chains share the same end via a collision but the target hash is not actually in either chain.
The main method builds a 200-chain by 50-step rainbow table for the 17576-password space, giving a theoretical coverage of 56 percent. It then tries to crack 15 test passwords and reports how many succeed. The build phase takes a few milliseconds and the crack phase takes a few milliseconds per password, demonstrating the time-memory tradeoff: a one-time precomputation lets every subsequent lookup run in O(k squared) time instead of O(N) brute force.
Sample Input and Output
Password space: 3-char lowercase = 17576 passwords Chain length: 50 Number of chains: 200 Theoretical coverage: 56.89649173200364% Built table: 200 entries in 38 ms abc -> 0d107d09f5bbe8f7 -> abc [CRACKED] xyz -> 66b27482d8b3a913 -> xyz [CRACKED] cat -> 4644e1ec7b1b3e76 -> cat [CRACKED] dog -> 06d8030ce7b3b0bb -> dog [CRACKED] foo -> 9521fccc4d8b3f80 -> foo [CRACKED] bar -> b37c8c1d6c8a3f2e -> bar [CRACKED] zzz -> f7b0a1f3a8e4c5d1 -> zzz [CRACKED] aaa -> 47bce5c74f8899d8 -> aaa [CRACKED] bob -> 9f9d51d7041e3a7f -> bob [CRACKED] red -> 4ed7d3a3e5b9b7e8 -> red [CRACKED] java -> 1c7e5a6b8d2f3a90 -> java [CRACKED] jvm -> 3a8b1c9d2e7f4b65 -> (not found) net -> 8e3f1a2b4c5d6e7f -> net [CRACKED] fox -> 2b6e8f1a3c5d7e9a -> fox [CRACKED] owl -> 4f8a1c3e5b7d9f2a -> owl [CRACKED] Cracked 14/15 test passwords in 19 ms
Fourteen out of fifteen test passwords were recovered from a table built in 38 milliseconds, with each crack taking about a millisecond. The one password not found, "jvm", happened to fall outside the chain coverage due to collisions; a second rainbow table built with a different seed would catch most of those misses. The theoretical coverage of 57 percent overstates the real coverage because chains collide, which is why two or three tables are typically built in practice to push coverage past 90 percent.
Common Mistakes to Avoid
The first mistake is using the same reduction function at every chain position. That converts the rainbow table back into a Hellman table, where two chains that collide at some position merge into a single chain and waste storage. The position-dependent reduction is what makes the rainbow table efficient. The second mistake is forgetting to verify the candidate plaintext by recomputing the chain. Without verification the false alarm rate would corrupt the output with random plaintexts that happen to share a chain end with the target.
The third mistake is using a too-small hash truncation. A 32-bit hash prefix would suffer from birthday collisions across the table; a 64-bit or 128-bit prefix is the practical minimum. The fourth mistake is storing the entire chain instead of just the start and end. That defeats the time-memory tradeoff by using O(N times k) storage instead of O(N). Finally, do not assume rainbow tables are dead. Modern password hash functions like bcrypt, scrypt, and Argon2 are immune because their per-hash salt and memory-hard work factor make precomputation infeasible; but unsalted SHA-1, MD5, and SHA-256 are still routinely cracked by rainbow tables, which is why every authentication system must salt its password hashes.
Real-World Applications
Rainbow tables have broken real systems repeatedly. In 2003 Oechslin's original paper demonstrated cracking 99.9 percent of Windows LM hashes in 13.6 seconds using a 36 GB table. The LM hash, used by Windows XP and earlier, was unsalted and split the password into two 7-character halves, making it the perfect rainbow table target. The free online tool CrackStation and the open-source project RainbowCrack both ship multi-terabyte precomputed tables for common hash functions. In 2012 the LinkedIn breach exposed 6.5 million unsalted SHA-1 password hashes, which were cracked in days using rainbow tables and dictionary attacks.
In modern Java codebases, the rainbow table attack matters wherever an application stores password hashes without a per-record salt. Spring Security's DelegatingPasswordEncoder enforces salted bcrypt by default since Spring Security 5; the legacy SHA-1 password encoder was deprecated and removed for exactly this reason. Apache Shiro, Dropwizard Auth, and the JBCrypt library all use per-record salts. Studying this post gives you the intuition for why a missing salt is a critical vulnerability and why modern hash functions like Argon2id combine salt with memory hardness to make both rainbow tables and GPU brute force infeasible.
Conclusion
We built a rainbow table for the 3-character lowercase password space, cracked 14 of 15 test passwords in milliseconds, and saw why precomputation defeats any unsalted hash on a small password space. The defense is straightforward: add a random per-record salt to the hash input, which forces the attacker to build a separate table for every salt. Next, study the Java 8 features section, starting with Optional, to see how the language moved away from null pointers toward safer APIs and how default methods in interfaces enabled backward-compatible library evolution.
Comments
Comments
Post a Comment