← Back to section · Foundations of Cryptography
Primality Testing: From Trial Division to Miller–Rabin
The first step in RSA key generation is producing large primes. This article explains the ceiling of trial division, why Carmichael numbers defeat the Fermat test, and how the Miller–Rabin probabilistic test trades a minuscule error probability for workable speed.
The first step in generating an RSA key pair is finding two sufficiently large primes among the integers. But there is a problem: given an odd number with hundreds of digits, how do you know whether it is prime or composite? Dividing by everything is obviously out of the question, and fully “proving” primality is too slow. The entire history of primality testing is a search for a balance between speed and certainty, and modern cryptography’s answer is surprising: accept a minuscule probability of error in exchange for an overwhelming advantage in speed.
Trial division: correct, but it does not go far
The most naive approach is trial division: if is composite, it must have a prime factor no larger than , so it suffices to try every prime up to . The principle is airtight and perfectly adequate for small numbers. But cryptographic integers run to 1024 or 2048 bits, and is still on the order of 512 bits — the candidate primes to try outnumber what the age of the universe could enumerate. In practice trial division survives in only one role: a cheap “pre-screen” using a batch of small primes to quickly discard obvious composites, passing the few survivors on to stronger tests. Pre-screening saves a great deal of time, but by itself it yields no conclusion about primality.
The Fermat test and the Carmichael trap
Fermat’s little theorem says that if is prime and is coprime to , then . Used in reverse it gives the Fermat test: pick a random base , compute ; if the result is not 1, is certainly composite, and if it is 1, the evidence leans toward prime. Modular exponentiation has fast algorithms, so this test is very quick. Unfortunately it has a systematic blind spot: there is a class of composite numbers called Carmichael numbers — 561, 1105, 1729 and so on — that satisfy the Fermat congruence for every base coprime to them. In other words, run the Fermat test on a Carmichael number and, no matter how many bases you draw, you may conclude “probably prime” and be wrong. Such numbers are rare, but they disqualify the Fermat test in principle as a standalone primality oracle.
Miller–Rabin: sharpening the Fermat test
The Miller–Rabin test improves on this by watching not just the final result but the whole trajectory of square roots during the computation. Write as with odd, and for a base compute the sequence modulo . If is prime, this sequence either starts at 1 or passes through (that is, ) just before reaching 1. A composite number finds this trajectory very hard to fake: if the term before a 1 in the sequence is not , you have found a nontrivial square root of 1 modulo , whereas modulo a prime 1 has only the two roots — which directly proves composite. It can be shown that for any odd composite, at least three quarters of all bases expose it; a composite therefore slips through one round with probability at most one quarter. Repeating with independent bases drives the error down to at most . With 40 rounds the error is below , far smaller than the chance that a memory cell randomly flips a bit. Real implementations (OpenSSL’s prime generation, for instance) work exactly this way: trial-division pre-screening followed by multiple Miller–Rabin rounds, and large primes roll out steadily.
A terminological clarification is in order: a composite that fools the test for certain bases is called a “strong pseudoprime” to those bases. The number 2047, for instance, is the smallest strong pseudoprime to base 2 and makes a single-base Miller–Rabin test err. Such examples show that too few, or too predictable, bases are dangerous: either use enough random bases to dilute the error probability, or adopt fixed base sets that have been rigorously verified for the target size. In practice it is also common to run one quick base-2 round as a filter — the overwhelming majority of composites die in that round, and only a handful of survivors need the full battery of later bases, cutting the overall cost further.
Industry’s double safety: combined tests and provable primes
Real cryptographic libraries often add a second safety net on top of Miller–Rabin. Some mathematical software and crypto libraries use the Baillie–PSW test: one Miller–Rabin round with base 2, followed by a strong Lucas test. The two tests have entirely different blind spots — no composite is known that fools both, despite a long-standing bounty for a counterexample. The combination offers no clean probability bound of the Miller–Rabin kind, yet at very low computational cost it buys reliability that is empirically impeccable — a typical specimen of the subtle division of labour between engineering judgement and theoretical proof: where a theoretical guarantee is absent, evidence accumulated over years of large-scale use fills the gap.
At the other end of the spectrum lies the “provable prime” route. Pocklington’s theorem and its successor constructions such as Maurer’s method produce, alongside the prime itself, a primality certificate that anyone can re-verify quickly: a partial factorisation witnessing primality is given explicitly, and a verifier need only check a handful of congruences. Some standards explicitly prefer such auditable artefacts for parameter generation, because in a compliance review a certificate outweighs a probabilistic argument — the reviewer need not trust the generator’s random number source, only arithmetic itself. Probabilistic testing suffices for everyday key generation; provable primes serve root keys, standardised parameters and other settings where auditability demands are extreme. The same decision problem grows entirely different solutions under different trust requirements, which is why primality testing remains a perennially fresh topic.
The deterministic route and engineering reality
Deterministic polynomial-time algorithms do exist in theory: the AKS test of 2002 first proved that primality can be decided exactly in polynomial time, a theoretical milestone; and for fixed size ranges there are Miller–Rabin variants where checking a small prescribed set of bases is already conclusive — for integers below 64 bits, only a handful of specified bases are needed. Yet in the actual setting of RSA key generation, the probabilistic test’s error has already been pushed far below every other source of failure, and it is fast enough, so industry still relies on Miller–Rabin as its workhorse. The lesson matters: much of cryptography’s “security” is not absolute proof but failure probability compressed to engineering negligibility — and primality testing is the earliest and cleanest example of that idea.
Tags: number theoryprimality testingMiller-RabinRSA