#Why this matters
Public-key systems such as RSA, Diffie-Hellman, and ECC operate over finite sets of integers rather than unbounded numbers. Modular arithmetic keeps values inside a fixed range while creating one-way traps: raising a number to a large power modulo n is fast, whereas reversing it without the secret key is infeasible.
In CTF challenges and security audits, you routinely compute modular inverses, check coprimality, and combine congruences. Mastering these five tools in Python 3 gives you the exact foundation needed for classical ciphers and RSA.
#The modulo operator and congruences
On a 12-hour clock, 17 hours past 12 wraps back to 5, so 17 mod 12 = 5. Formally, for any integer a and modulus n > 0:
a mod n = a - n * floor(a / n)
This floor rule explains negative numbers in Python: for -7 % 3, floor(-7 / 3) = -3, so -7 - 3 * (-3) = 2. Whenever n > 0, Python returns a non-negative remainder in 0..(n - 1).
We write a = b (mod n) (congruence) when n divides (a - b). Addition and multiplication reduce cleanly modulo n:
(a + b) mod n = ((a mod n) + (b mod n)) mod n(a * b) mod n = ((a mod n) * (b mod n)) mod n- For large powers
(a^k) mod n, callpow(a, k, n), which runs inO(log k)time; e.g.pow(2, 1000, 997)returns16.
#GCD, Extended GCD, and modular inverses
GCD(a, b) is the largest integer dividing both a and b. Two integers are coprime when GCD(a, b) = 1. The Euclidean algorithm uses GCD(a, 0) = a and GCD(a, b) = GCD(b, a mod b):
- StartGCD(48, 18) -> 48 mod 18 = 12
- Step 2GCD(18, 12) -> 18 mod 12 = 6
- Step 3GCD(12, 6) -> 12 mod 6 = 0
- ResultGCD(6, 0) = 6
Instead of division, modular arithmetic multiplies by a modular inverse: an integer x with a * x = 1 (mod n). An inverse exists if and only if GCD(a, n) = 1.
The Extended Euclidean Algorithm finds x, y for Bezout's identity a * x + b * y = GCD(a, b). For 30 and 11, (-4) * 30 + 11 * 11 = -120 + 121 = 1, so 11^(-1) mod 30 = 11 and 30^(-1) mod 11 = -4 mod 11 = 7.
import math
def extended_gcd(a, b):
if b == 0:
return a, 1, 0
g, x, y = extended_gcd(b, a % b)
return g, y, x - (a // b) * y
def mod_inverse(a, n):
g, x, _ = extended_gcd(a % n, n)
if g != 1:
raise ValueError("No inverse!")
return x % n
print(math.gcd(48, 18)) # 6
print(mod_inverse(3, 11)) # 4
print(pow(7, -1, 26)) # 15 (Python 3.8+ built-in)Calling mod_inverse(6, 15) raises ValueError because GCD(6, 15) = 3 != 1. Python 3.8+ provides pow(a, -1, n) natively.
#Euler's totient, Fermat's Little Theorem, and Euler's Theorem
Euler's totient phi(n) counts integers in 1..(n - 1) (for n > 1) coprime to n:
| Case | Formula | Example |
|---|---|---|
Prime p |
phi(p) = p - 1 |
phi(7) = 6 |
Distinct primes p, q |
phi(p * q) = (p - 1) * (q - 1) |
phi(15) = 2 * 4 = 8 |
Prime power p^k |
phi(p^k) = p^k - p^(k - 1) |
phi(8) = 8 - 4 = 4 |
Composite n = 12 |
Product over prime powers | phi(12) = 4 (1, 5, 7, 11) |
- Fermat's Little Theorem: For prime
pnot dividinga,a^(p - 1) = 1 (mod p), givinga^(-1) = a^(p - 2) (mod p). Fora = 2, p = 5,2^3 mod 5 = 3. - Euler's Theorem: When
GCD(a, n) = 1,a^phi(n) = 1 (mod n). RSA choosese * d = 1 (mod phi(n))so(m^e)^d = m (mod n).
- Valid ONLY when modulus p is prime
- Fails silently on composite moduli (n = 12)
- Requires primality check first
- Valid for ANY n when GCD(a, n) = 1
- Raises ValueError when no inverse exists
- Recommended default in Python 3.8+
#Chinese Remainder Theorem (CRT)
Given remainders of x modulo pairwise-coprime moduli n_1, ..., n_k (GCD(n_i, n_j) = 1 for i != j), CRT guarantees a unique solution modulo N = n_1 * ... * n_k by summing a_i * N_i * (N_i^(-1) mod n_i) (mod N) where N_i = N / n_i.
from functools import reduce
def phi(n):
res, p, temp = n, 2, n
while p * p < temp + 1:
if temp % p == 0:
while temp % p == 0:
temp //= p
res -= res // p
p += 1
return res - res // temp if temp > 1 else res
def crt(rems, mods):
N = reduce(lambda a, b: a * b, mods)
return sum(ai * (N // ni) * pow(N // ni, -1, ni) for ai, ni in zip(rems, mods)) % N
print(phi(12), phi(100)) # 4 40
print(pow(2, 10**18, 10**9 + 7)) # 719476260
print(crt([2, 3, 2], [3, 5, 7])) # 23CRT accelerates RSA decryption roughly 4x and powers Hastad's broadcast attack: encrypting the same unpadded message m with e = 3 under three pairwise-coprime RSA moduli lets CRT recover m^3 (m^3 < n_1 * n_2 * n_3), whose cube root reveals m.
#Defending / Common mistakes
- Using Fermat's shortcut on composite moduli:
pow(a, n - 2, n)works only for primen; default topow(a, -1, n). - Reducing exponents modulo
n:2^1000 mod 15is not2^(1000 mod 15) mod 15; callpow(2, 1000, 15)directly. - Skipping pairwise coprimality in CRT: Always check
math.gcd(n_i, n_j) == 1before invertingN_i. - Applying
(p - 1)(q - 1)whenp == q: Distinct primes are required;phi(p^2) = p^2 - p.
#Summary
- Modular arithmetic wraps integers into
0..(n - 1)viaa - n * floor(a / n), andpow(a, k, n)runs inO(log k). - A modular inverse exists if and only if
GCD(a, n) = 1, computed via Extended GCD orpow(a, -1, n). - Euler's totient
phi(n)generalizes Fermat's Little Theorem to Euler's Theorem (a^phi(n) = 1 mod n). - CRT solves pairwise-coprime congruences uniquely modulo
N, enabling fast RSA decryption and Hastad's attack.