Number Theory & Crypto Exercises
Time to practise the whole course. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Try every algorithm on numbers small enough to check by hand first. Python's built-in
pow(a, e, n)andpow(a, -1, n)are handy for checking your own versions. All code here is teaching code with toy parameters: never use it to protect real data.
| # | Exercise | Practises |
|---|---|---|
| 1 | Extended Euclid and inverses | Bézout coefficients, modular inverses |
| 2 | A CRT solver | Chinese Remainder Theorem |
| 3 | Counting primes with a sieve | sieve of Eratosthenes, the prime number theorem |
| 4 | Square-and-multiply | fast modular exponentiation |
| 5 | Miller-Rabin | strong pseudoprimes, Carmichael numbers |
| 6 | Baby-step giant-step | discrete logarithms |
| 7 | RSA decryption with the CRT | RSA, Garner's formula |
| 8 | Elliptic-curve point order | the group law on a curve over a finite field |
Exercise 1: Extended Euclid and inverses
Complete egcd(a, b) so it returns with (The Extended Euclidean Algorithm), then use it to invert 17 modulo 3120.
def egcd(a, b):
if b == 0:
return a, 1, 0
g, x, y = egcd(b, a % b)
return g, 0, 0 # TODO: express x and y for (a, b) through x, y for (b, a % b)
g, x, y = egcd(240, 46)
print("gcd:", g, " x, y:", x, y, " check:", 240 * x + 46 * y)
g, x, _ = egcd(17, 3120)
print("inverse of 17 mod 3120:", x % 3120)gcd: 2 x, y: 0 0 check: 0
inverse of 17 mod 3120: 0
Expected output when solved:
gcd: 2 x, y: -9 47 check: 2
inverse of 17 mod 3120: 2753Solution
From and we get and .
def egcd(a, b):
if b == 0:
return a, 1, 0
g, x, y = egcd(b, a % b)
return g, y, x - (a // b) * y
g, x, y = egcd(240, 46)
print("gcd:", g, " x, y:", x, y, " check:", 240 * x + 46 * y)
g, x, _ = egcd(17, 3120)
print("inverse of 17 mod 3120:", x % 3120)gcd: 2 x, y: -9 47 check: 2
inverse of 17 mod 3120: 2753
Exercise 2: A CRT solver
Complete crt so it combines congruences with pairwise coprime moduli (The Chinese Remainder Theorem). Solve the classic puzzle , , , then a larger system.
from math import prod
def crt(residues, moduli):
M = prod(moduli)
x = 0
for r, m in zip(residues, moduli):
Mi = M // m
x += 0 # TODO: add r * Mi * (inverse of Mi modulo m)
return x % M
print(crt([2, 3, 2], [3, 5, 7]))
print(crt([1, 7, 12, 30], [11, 13, 17, 31]))0
0
Expected output when solved:
23
26566 [1, 7, 12, 30]Solution
from math import prod
def crt(residues, moduli):
M = prod(moduli)
x = 0
for r, m in zip(residues, moduli):
Mi = M // m
x += r * Mi * pow(Mi, -1, m)
return x % M
x = crt([1, 7, 12, 30], [11, 13, 17, 31])
print(crt([2, 3, 2], [3, 5, 7]))
print(x, [x % m for m in (11, 13, 17, 31)])23
26566 [1, 7, 12, 30]
The second line also prints the residues, confirming the answer.
Exercise 3: Counting primes with a sieve
Finish the sieve of Eratosthenes (The Sieve of Eratosthenes) and compare with for .
import math
def sieve(n):
is_p = [True] * (n + 1)
is_p[0] = is_p[1] = False
for p in range(2, math.isqrt(n) + 1):
if is_p[p]:
pass # TODO: mark p*p, p*p + p, ... as composite
return [i for i, v in enumerate(is_p) if v]
N = 10**5
ps = sieve(N)
print("pi(N) =", len(ps), " N/ln N =", round(N / math.log(N)), " last prime:", ps[-1])pi(N) = 99999 N/ln N = 8686 last prime: 100000
Expected output when solved:
pi(N) = 9592 N/ln N = 8686 last prime: 99991Solution
import math
def sieve(n):
is_p = [True] * (n + 1)
is_p[0] = is_p[1] = False
for p in range(2, math.isqrt(n) + 1):
if is_p[p]:
is_p[p * p::p] = [False] * len(range(p * p, n + 1, p))
return [i for i, v in enumerate(is_p) if v]
N = 10**5
ps = sieve(N)
print("pi(N) =", len(ps), " N/ln N =", round(N / math.log(N)), " last prime:", ps[-1])pi(N) = 9592 N/ln N = 8686 last prime: 99991
underestimates by about 10 % here; is much closer (The Prime Number Theorem).
Exercise 4: Square-and-multiply
Write power(a, e, n) with left-to-right square-and-multiply (Fast Modular Exponentiation) and count the multiplications it uses.
def power(a, e, n):
r, mults = 1, 0
for bit in bin(e)[2:]:
pass # TODO: square r; if bit is "1", also multiply by a (count both)
return r, mults
for a, e, n in ((7, 560, 561), (3, 2026, 100), (5, 10**18, 10**9 + 7)):
r, mults = power(a, e, n)
print(f"{a}^{e} mod {n} = {r} ({mults} multiplications) built-in: {pow(a, e, n)}")7^560 mod 561 = 1 (0 multiplications) built-in: 1
3^2026 mod 100 = 1 (0 multiplications) built-in: 29
5^1000000000000000000 mod 1000000007 = 1 (0 multiplications) built-in: 921116510
Expected output when solved:
7^560 mod 561 = 1 (13 multiplications) built-in: 1
3^2026 mod 100 = 29 (19 multiplications) built-in: 29
5^1000000000000000000 mod 1000000007 = 921116510 (84 multiplications) built-in: 921116510Solution
def power(a, e, n):
r, mults = 1, 0
for bit in bin(e)[2:]:
r, mults = r * r % n, mults + 1
if bit == "1":
r, mults = r * a % n, mults + 1
return r, mults
for a, e, n in ((7, 560, 561), (3, 2026, 100), (5, 10**18, 10**9 + 7)):
r, mults = power(a, e, n)
print(f"{a}^{e} mod {n} = {r} ({mults} multiplications) built-in: {pow(a, e, n)}")7^560 mod 561 = 1 (13 multiplications) built-in: 1
3^2026 mod 100 = 29 (19 multiplications) built-in: 29
5^1000000000000000000 mod 1000000007 = 921116510 (84 multiplications) built-in: 921116510
The count is the bit length plus the number of 1 bits: 84 multiplications for the 60-bit exponent (60 squarings plus 24 one bits) instead of .
Exercise 5: Miller-Rabin
Complete the strong-pseudoprime test for one base (The Miller-Rabin Test), then classify a few numbers with the bases 2, 3, 5, 7, 11, 13.
def strong_probable_prime(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
# TODO: square x up to s - 1 times; return True if it ever becomes n - 1
return True
def is_prime(n):
if n < 2:
return False
for a in (2, 3, 5, 7, 11, 13):
if n % a == 0:
return n == a
if not strong_probable_prime(n, a):
return False
return True
for n in (561, 1105, 3277, 7919, 2**61 - 1, 2**61 + 1):
print(n, is_prime(n))561 False
1105 False
3277 True
7919 True
2305843009213693951 True
2305843009213693953 False
Expected output when solved:
561 False
1105 False
3277 False
7919 True
2305843009213693951 True
2305843009213693953 FalseSolution
def strong_probable_prime(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
def is_prime(n):
if n < 2:
return False
for a in (2, 3, 5, 7, 11, 13):
if n % a == 0:
return n == a
if not strong_probable_prime(n, a):
return False
return True
for n in (561, 1105, 3277, 7919, 2**61 - 1, 2**61 + 1):
print(n, is_prime(n))561 False
1105 False
3277 False
7919 True
2305843009213693951 True
2305843009213693953 False
The Carmichael numbers 561 and 1105 and the base-2 strong pseudoprime 3277 are caught; 7919 and the Mersenne prime pass.
Exercise 6: Baby-step giant-step
Solve with baby-step giant-step (Baby-Step Giant-Step).
import math
def bsgs(g, h, p):
m = math.isqrt(p - 1) + 1
baby = {pow(g, j, p): j for j in range(m)} # g^j for j < m
step = pow(g, -m, p) # g^(-m)
y = h
for i in range(m):
# TODO: if y is in baby, return i * m + baby[y]; otherwise multiply y by step
pass
return None
x = bsgs(2, 1500, 2027)
print("x =", x)x = None
Expected output when solved:
x = 113 check: 1500Solution
import math
def bsgs(g, h, p):
m = math.isqrt(p - 1) + 1
baby = {pow(g, j, p): j for j in range(m)}
step = pow(g, -m, p)
y = h
for i in range(m):
if y in baby:
return i * m + baby[y]
y = y * step % p
return None
x = bsgs(2, 1500, 2027)
print("x =", x, " check:", pow(2, x, 2027))x = 113 check: 1500
About group operations instead of up to 2026.
Exercise 7: RSA decryption with the CRT
With , , (RSA Key Generation), decrypt using the CRT (Faster RSA with the CRT) and compare with the direct computation.
p, q, e = 101, 113, 17
n, phi = p * q, (p - 1) * (q - 1)
d = pow(e, -1, phi)
c = 8293
dp, dq, q_inv = d % (p - 1), d % (q - 1), pow(q, -1, p)
mp = 0 # TODO: c^dp mod p
mq = 0 # TODO: c^dq mod q
m_crt = mq + q * ((q_inv * (mp - mq)) % p)
print("direct:", pow(c, d, n), " CRT:", m_crt)direct: 8971 CRT: 0
Expected output when solved:
direct: 8971 CRT: 8971 re-encrypt: 8293Solution
p, q, e = 101, 113, 17
n, phi = p * q, (p - 1) * (q - 1)
d = pow(e, -1, phi)
c = 8293
dp, dq, q_inv = d % (p - 1), d % (q - 1), pow(q, -1, p)
mp = pow(c, dp, p)
mq = pow(c, dq, q)
m_crt = mq + q * ((q_inv * (mp - mq)) % p)
print("direct:", pow(c, d, n), " CRT:", m_crt, " re-encrypt:", pow(m_crt, e, n))direct: 8971 CRT: 8971 re-encrypt: 8293
Garner's formula recombines the two half-size results; re-encrypting gives back .
Exercise 8: Elliptic-curve point order
On over (Elliptic Curves over Finite Fields), finish the point addition and find the order of .
p, a_coef = 97, 2
def add(P, Q):
if P is None: return Q
if Q is None: return P
(x1, y1), (x2, y2) = P, Q
if x1 == x2 and (y1 + y2) % p == 0:
return None
if P == Q:
lam = 0 # TODO: tangent slope (3 x1^2 + a) / (2 y1) mod p
else:
lam = 0 # TODO: chord slope (y2 - y1) / (x2 - x1) mod p
x3 = (lam * lam - x1 - x2) % p
return (x3, (lam * (x1 - x3) - y1) % p)
P = (3, 6)
R, k = P, 1
while R is not None and k < 200:
R, k = add(R, P), k + 1
print("2P =", add(P, P), " order of P:", k)2P = (91, 91) order of P: 200
Expected output when solved:
2P = (80, 10) order of P: 5Solution
p, a_coef = 97, 2
def add(P, Q):
if P is None: return Q
if Q is None: return P
(x1, y1), (x2, y2) = P, Q
if x1 == x2 and (y1 + y2) % p == 0:
return None
if P == Q:
lam = (3 * x1 * x1 + a_coef) * pow(2 * y1, -1, p) % p
else:
lam = (y2 - y1) * pow(x2 - x1, -1, p) % p
x3 = (lam * lam - x1 - x2) % p
return (x3, (lam * (x1 - x3) - y1) % p)
P = (3, 6)
R, k = P, 1
while R is not None and k < 200:
R, k = add(R, P), k + 1
print("2P =", add(P, P), " order of P:", k)2P = (80, 10) order of P: 5
The order divides the number of points on the curve (100), as Lagrange's theorem requires.
Test yourself
Why does the CRT make RSA decryption about 3 to 4 times faster?
- it skips the exponentiation
- two exponentiations with half-size numbers cost less than one full-size one
- it uses a smaller
- it avoids the modulus
A Carmichael number fools…
- Miller-Rabin for every base
- the Fermat test for every base coprime to it
- trial division
- the sieve
Baby-step giant-step solves a discrete logarithm in a group of order in about…
- steps
- steps and memory
- steps
- constant time