Show contents
Chapter 1 of 6 · 20 min
The arithmetic of public keys
By the end of this chapter, you'll be able to
- Compute a GCD and a modular inverse in Python
- State Fermat's little theorem and use it as a test
- Implement the Miller-Rabin primality test
- Generate a prime number of several hundred bits
Counting on a clock
Modular arithmetic means counting on a clock: on a 12-hour dial, 9 o'clock + 5 hours = 2 o'clock. We write (9 + 5) % 12 == 2. You can add, subtract and multiply "modulo n" by taking the remainder each time. Division, however, does not always exist: that is where the GCD and the inverse come in.
GCD and modular inverse
The GCD (greatest common divisor) of two numbers is the largest number that divides both. Two numbers are coprime if their GCD is 1.
The modular inverse of e modulo m is the number d such that (e × d) % m == 1. It exists exactly when e and m are coprime. Python computes it with pow(e, -1, m), thanks to the extended Euclidean algorithm.
import math
print("gcd(48, 18) =", math.gcd(48, 18))
print("gcd(17, 60) =", math.gcd(17, 60)) # coprime
d = pow(17, -1, 60) # inverse of 17 modulo 60
print("inverse of 17 mod 60 =", d, "| check:", (17 * d) % 60)
try:
pow(18, -1, 60) # gcd(18, 60) = 6: no inverse
except ValueError as error:
print("no inverse:", error)
gcd(48, 18) = 6
gcd(17, 60) = 1
inverse of 17 mod 60 = 53 | check: 1
no inverse: base is not invertible for the given modulus
Fermat's little theorem
Pierre de Fermat noticed in the 17th century that if p is prime, then for any a that is not a multiple of p:
a^(p-1) mod p = 1
It is a quick test: if pow(a, n-1, n) is not 1, then n is certainly not prime. The computation is immediate even for huge numbers, whereas trying every divisor would take longer than the age of the Universe.
for n in (97, 91, 561):
witnesses = [a for a in (2, 3, 5, 7) if pow(a, n - 1, n) == 1]
print(f"n = {n}: the test passes for a = {witnesses}")
print("91 = 7 × 13 and 561 = 3 × 11 × 17")
n = 97: the test passes for a = [2, 3, 5, 7]
n = 91: the test passes for a = [3]
n = 561: the test passes for a = [2, 5, 7]
91 = 7 × 13 and 561 = 3 × 11 × 17
The test unmasks 91 with 2, 5 and 7, but not with 3: one witness alone is therefore not enough. And 561 passes the test for every value coprime with it (2, 5 and 7; only 3, which divides it, unmasks it): it is a Carmichael number, a perfect liar for Fermat's test. A finer test is needed.
The Miller-Rabin test
The Miller-Rabin test strengthens Fermat's idea: it writes n - 1 = 2^s × d and looks at the sequence of successive squares. A composite number is unmasked by at least 3 witnesses a out of 4. With 40 witnesses drawn at random, the probability of error falls below 1 in 280: it is the test used in practice to generate keys.
The whole thing takes a fraction of a second.
Text description of the animation
- We draw a large odd number, with the top bit set to 1 to guarantee the size.
- Many candidates are eliminated right away by small divisions.
- Each witness that does not unmask n increases confidence.
- If a witness unmasks n, we move to the next candidate. About 1 odd number in 177 of this size is prime.
- The whole thing takes a fraction of a second.
import random
def miller_rabin(n, witnesses=40, rng=random.Random(1)):
"""True if n is probably prime, False if it is certainly composite."""
if n < 4:
return n in (2, 3)
if n % 2 == 0:
return False
s, d = 0, n - 1
while d % 2 == 0: # n - 1 = 2^s × d, with d odd
s, d = s + 1, d // 2
for _ in range(witnesses):
a = rng.randrange(2, n - 1)
x = pow(a, d, n)
if x in (1, n - 1):
continue
for _ in range(s - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False # a is a witness: n is composite
return True
for n in (97, 91, 561, 2**127 - 1, 2**128 + 1):
print(n if n < 10**6 else f"{str(n)[:12]}…", "→", "prime" if miller_rabin(n) else "composite")
97 → prime
91 → composite
561 → composite
170141183460… → prime
340282366920… → composite
Miller-Rabin unmasks 561 easily, confirms that 2127 − 1 is prime, and shows that 2128 + 1 is not (it is divisible by 59,649,589,127,497,217).
Mini-lab: make a prime numberPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: the modular inverse by hand
pow(e, -1, m) hides the extended Euclidean algorithm. Write a function extended_euclid(a, b) that returns (g, x, y) with g = gcd(a, b) and a×x + b×y = g, then a function inverse(e, m) that uses it. Check with inverse(17, 60) and inverse(65537, 3120), comparing with pow.
Hint 1
b == 0, return (a, 1, 0). Otherwise, call extended_euclid(b, a % b), which returns (g, x1, y1), and return (g, y1, x1 - (a // b) * y1).Hint 2
g != 1, the inverse does not exist. Otherwise, the inverse is x % m (the % brings it between 0 and m - 1).Show the solution and common mistakes
def extended_euclid(a, b):
if b == 0:
return a, 1, 0
g, x1, y1 = extended_euclid(b, a % b)
return g, y1, x1 - (a // b) * y1
def inverse(e, m):
g, x, _ = extended_euclid(e, m)
if g != 1:
raise ValueError(f"{e} is not invertible modulo {m}")
return x % m
for e, m in [(17, 60), (65537, 3120)]:
d = inverse(e, m)
print(f"inverse({e}, {m}) = {d} | pow: {pow(e, -1, m)} | e×d mod m = {e * d % m}")
inverse(17, 60) = 53 | pow: 53 | e×d mod m = 1
inverse(65537, 3120) = 2753 | pow: 2753 | e×d mod m = 1
Euclid's algorithm divides the remainders successively, then goes back up the quotients to express the GCD as a combination of a and b. The number of steps is proportional to the number of digits: it stays instant for 600-digit numbers.
Common mistakes:
- Forgetting the final
% m:xcan be negative, which gives an "inverse" that is mathematically correct but unexpected. - Swapping
a // banda % bin the recursive call. - Looking for the inverse with a
for d in range(m)loop: impossible as soon asmhas a few dozen digits.
Summary
- 1The modular inverse of e modulo m exists when gcd(e, m) = 1; pow(e, -1, m) computes it.
- 2Fermat's little theorem gives a fast test, fooled by Carmichael numbers.
- 3Miller-Rabin with 40 witnesses confirms that a large number is prime with negligible error.
- 4The primes of keys must be drawn with unpredictable randomness (secrets), never with random.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.