TExcelTAD
Home › Number Theory & Cryptography › Number Theory & Crypto Exercises

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) and pow(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 (g,x,y)(g, x, y) with ax+by=g=gcd⁡(a,b)ax + by = g = \gcd(a, b) (The Extended Euclidean Algorithm), then use it to invert 17 modulo 3120.

python · try it yourself
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:

text
gcd: 2  x, y: -9 47  check: 2
inverse of 17 mod 3120: 2753
Solution

From bx′+(a mod b)y′=gb x' + (a \bmod b) y' = g and a mod b=a−⌊a/b⌋ba \bmod b = a - \lfloor a/b \rfloor b we get x=y′x = y' and y=x′−⌊a/b⌋y′y = x' - \lfloor a/b \rfloor y'.

python · try it yourself
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 x≡2(mod3)x \equiv 2 \pmod 3, x≡3(mod5)x \equiv 3 \pmod 5, x≡2(mod7)x \equiv 2 \pmod 7, then a larger system.

python · try it yourself
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:

text
23
26566 [1, 7, 12, 30]
Solution
python · try it yourself
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 π(N)\pi(N) with N/ln⁡NN / \ln N for N=105N = 10^5.

python · try it yourself
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:

text
pi(N) = 9592  N/ln N = 8686  last prime: 99991
Solution
python · try it yourself
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

N/ln⁡NN / \ln N underestimates π(N)\pi(N) by about 10 % here; Li⁡(N)\operatorname{Li}(N) 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.

python · try it yourself
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:

text
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
Solution
python · try it yourself
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 101810^{18} (60 squarings plus 24 one bits) instead of 101810^{18}.

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.

python · try it yourself
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:

text
561 False
1105 False
3277 False
7919 True
2305843009213693951 True
2305843009213693953 False
Solution
python · try it yourself
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 261−12^{61} - 1 pass.

Exercise 6: Baby-step giant-step

Solve 2x≡1500(mod2027)2^x \equiv 1500 \pmod{2027} with baby-step giant-step (Baby-Step Giant-Step).

python · try it yourself
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:

text
x = 113  check: 1500
Solution
python · try it yourself
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 2p≈902\sqrt{p} \approx 90 group operations instead of up to 2026.

Exercise 7: RSA decryption with the CRT

With p=101p = 101, q=113q = 113, e=17e = 17 (RSA Key Generation), decrypt c=8293c = 8293 using the CRT (Faster RSA with the CRT) and compare with the direct computation.

python · try it yourself
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:

text
direct: 8971  CRT: 8971  re-encrypt: 8293
Solution
python · try it yourself
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 cc.

Exercise 8: Elliptic-curve point order

On y2=x3+2x+3y^2 = x^3 + 2x + 3 over F97\mathbb{F}_{97} (Elliptic Curves over Finite Fields), finish the point addition and find the order of P=(3,6)P = (3, 6).

python · try it yourself
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:

text
2P = (80, 10)  order of P: 5
Solution
python · try it yourself
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?

  1. it skips the exponentiation
  2. two exponentiations with half-size numbers cost less than one full-size one
  3. it uses a smaller ee
  4. it avoids the modulus

A Carmichael number fools…

  1. Miller-Rabin for every base
  2. the Fermat test for every base coprime to it
  3. trial division
  4. the sieve

Baby-step giant-step solves a discrete logarithm in a group of order nn in about…

  1. nn steps
  2. n\sqrt{n} steps and n\sqrt{n} memory
  3. log⁡n\log n steps
  4. constant time