TExcelTAD
Home › Number Theory & Cryptography › The Miller-Rabin Test

The Miller-Rabin Test

Miller-Rabin is the primality test inside essentially every cryptographic library. It strengthens Fermat's test with the square-root-of-1 check, has no Carmichael-style blind spots, and each round lets a composite through with probability at most 1/4.

The idea

Write n−1=2sdn - 1 = 2^s d with dd odd. For a prime nn and any base aa, the sequence

ad, a2d, a4d, …, a2sd=an−1(modn)a^d,\ a^{2d},\ a^{4d},\ \ldots,\ a^{2^s d} = a^{n-1} \pmod{n}

ends in 1 (Fermat), and each term is the square of the previous one. In a field the only square roots of 1 are ±1\pm 1, so either ad≡1a^d \equiv 1, or some term equals −1-1 just before the 1s start. If neither happens, nn is composite and aa is a strong witness.

The algorithm

python · try it yourself
def miller_rabin_round(n, a):
    d, s = n - 1, 0
    while d % 2 == 0:
        d //= 2
        s += 1
    x = pow(a, d, n)
    if x == 1 or x == n - 1:
        return True                      # probably prime for this base
    for _ in range(s - 1):
        x = x * x % n
        if x == n - 1:
            return True
    return False                         # a is a witness: n is composite

def is_probable_prime(n, bases=(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)):
    if n < 2:
        return False
    for p in bases:
        if n % p == 0:
            return n == p
    return all(miller_rabin_round(n, a) for a in bases)

for n in (561, 1105, 1729, 2047, 1_000_000_007, 2**61 - 1, 2**64 + 1, 2**127 - 1):
    print(n, is_probable_prime(n))
561 False
1105 False
1729 False
2047 False
1000000007 True
2305843009213693951 True
18446744073709551617 False
170141183460469231731687303715884105727 True

All three Carmichael numbers are rejected.

How reliable is one round?

For composite odd nn, at most a quarter of the bases in [2,n−2][2, n - 2] are strong liars (Rabin's theorem; for most nn far fewer). So kk independent random bases give an error probability below 4−k4^{-k}, and for random large candidates the real error is much smaller still.

python · try it yourself
from math import gcd

def strong_liars(n):
    return [a for a in range(2, n - 1) if miller_rabin_round(n, a)]

def miller_rabin_round(n, a):
    d, s = n - 1, 0
    while d % 2 == 0:
        d, s = d // 2, s + 1
    x = pow(a, d, n)
    if x in (1, n - 1):
        return True
    for _ in range(s - 1):
        x = x * x % n
        if x == n - 1:
            return True
    return False

for n in (561, 1105, 2047, 3277, 8911, 65):
    l = strong_liars(n)
    print(f"n={n:5}  strong liars: {len(l):3} of {n - 3}  ({len(l) / (n - 3):.2%})")
n=  561  strong liars:   8 of 558  (1.43%)
n= 1105  strong liars:  28 of 1102  (2.54%)
n= 2047  strong liars: 240 of 2044  (11.74%)
n= 3277  strong liars: 292 of 3274  (8.92%)
n= 8911  strong liars: 1780 of 8908  (19.98%)
n=   65  strong liars:   4 of 62  (6.45%)

Compare with the Fermat test, where every unit of 561 lied: Miller-Rabin's liars for 561 are a tiny fraction.

Deterministic versions

The smallest strong pseudoprime to base 2 is 2047=23⋅892047 = 23 \cdot 89; to bases 2 and 3 together it is 1373653. Researchers have computed how many prime bases suffice for all nn below a bound; the first 12 primes (2 to 37) give a deterministic test for every n<3.18⋅1023n < 3.18 \cdot 10^{23} (Sorenson and Webster, 2017), which covers all 64-bit integers. Above that, random bases are used.

python · try it yourself
def sprp(n, a):
    d, s = n - 1, 0
    while d % 2 == 0:
        d, s = d // 2, s + 1
    x = pow(a, d, n)
    if x in (1, n - 1):
        return True
    for _ in range(s - 1):
        x = x * x % n
        if x == n - 1:
            return True
    return False

from sympy import isprime
print([n for n in range(3, 10000, 2) if sprp(n, 2) and not isprime(n)])
n = 1373653
print(n, sprp(n, 2), sprp(n, 3), sprp(n, 5), isprime(n))
[2047, 3277, 4033, 4681, 8321]
1373653 True True False False

In software

  • OpenSSL, BoringSSL, Go's crypto/rand.Prime, Java's BigInteger.isProbablePrime and Python's sympy.isprime all run Miller-Rabin; FIPS 186-5 (Table B.1) fixes the minimum number of rounds by prime size: 4 rounds (error probability 2−1002^{-100}) or 5 rounds (2−1122^{-112}) for the 1024-bit primes of an RSA-2048 key, optionally followed by one Lucas test. So few rounds suffice because the candidates are random; a number chosen by an adversary needs many more.
  • Bases must be random when nn may be adversarial. With fixed public bases an attacker can construct composites that pass, the problem behind several 2018 library bug reports.
  • Proving primality (rather than "probably prime") is possible with ECPP or the AKS algorithm, but it is slower and rarely needed in practice.

Exercises

Exercise 1: Decompose

Write n−1=2sdn - 1 = 2^s d for n=97n = 97 and n=2047n = 2047.

Answer

96=25⋅396 = 2^5 \cdot 3; 2046=2⋅10232046 = 2 \cdot 1023.

Solution

96/2=4896 / 2 = 48, 2424, 1212, 66, 33: five halvings, d=3d = 3. 2046/2=10232046 / 2 = 1023, which is odd, so s=1s = 1, d=1023d = 1023.

Exercise 2: Base 2 lies about 2047

Show that base 2 does not detect 2047=23⋅892047 = 23 \cdot 89 but base 3 does.

Answer

21023≡1(mod2047)2^{1023} \equiv 1 \pmod{2047}; 31023≢±13^{1023} \not\equiv \pm 1.

Solution

211=2048≡1(mod2047)2^{11} = 2048 \equiv 1 \pmod{2047} and 1023=11⋅931023 = 11 \cdot 93, so 21023≡12^{1023} \equiv 1: the round passes. With s=1s = 1 there are no squarings left, so base 3 fails unless 31023≡±13^{1023} \equiv \pm 1, and it is not (try pow(3, 1023, 2047)).

Exercise 3: Probability (code)

For n=3277n = 3277 (the second strong pseudoprime to base 2), what fraction of bases are strong liars? How many independent random rounds bring the worst-case error below 2−1282^{-128}?

Answer

292 of the 3274 bases, about 8.9 %; 64 rounds by the 4−k4^{-k} bound.

Solution

The table in this lesson shows 292 strong liars for 3277, well under the worst-case quarter. For the bound, 4−k≤2−1284^{-k} \le 2^{-128} means 2k≥1282k \ge 128, so k=64k = 64. In practice, for random candidates far fewer rounds are needed, which is why standards specify smaller numbers.

python · try it yourself
print(next(k for k in range(1, 200) if 4.0 ** -k <= 2.0 ** -128))
64

Test yourself

Miller-Rabin writes n−1n - 1 as…

  1. p⋅qp \cdot q
  2. 2sd2^s d with dd odd
  3. d2+1d^2 + 1
  4. φ(n)+1\varphi(n) + 1

The worst-case probability that one Miller-Rabin round with a random base accepts a composite is…

  1. 1/2
  2. at most 1/4
  3. 0
  4. 1/n

Why does Miller-Rabin catch Carmichael numbers like 561?

  1. it uses more bases
  2. it finds square roots of 1 other than ±1\pm 1, impossible modulo a prime
  3. it factors nn
  4. it checks digit sums