Learn › Blockchain & Access Control › Module 2 · Public-key cryptography
Number theory: Fermat, inverses, Euclid and CRT
Fermat's little theorem with four worked reductions, linear congruences and modular inverses, the extended Euclidean algorithm step by step, and the Chinese remainder theorem.
Fermat’s little theorem
p prime, gcd(a, p) = 1 ⇒ ap−1 ≡ 1 (mod p). For any a: ap ≡ a (mod p).
Reduce the exponent modulo p − 1, then compute a small power.
Worked examples
- 128129 mod 17: 129 = 8·16 + 1 ⇒ 128 mod 17 = 9.
- 21000 mod 13: 1000 = 83·12 + 4 ⇒ 24 = 16 ≡ 3.
- (220 + 330 + 440 + 550 + 660) mod 7: exponents mod 6 give 22 + 30 + 44 + 52 + 60 ≡ 4 + 1 + 4 + 4 + 1 = 14 ≡ 0.
- x103 ≡ 4 (mod 11): 103 ≡ 3 (mod 10), so x3 ≡ 4; trying values gives 53 = 125 ≡ 4, so x ≡ 5.
Linear congruences and modular inverses
a′ is the inverse of a mod m if a′a ≡ 1 (mod m). It exists (and is unique mod m) exactly when gcd(a, m) = 1. Proof by Bézout: sa + tm = 1 ⇒ sa ≡ 1 (mod m). To solve ax ≡ b (mod m), multiply by a−1: x ≡ a−1b.
Worked examples
- 3−1 mod 7 = 5, since 3·5 + 7·(−2) = 1. Then 3x ≡ 4 (mod 7) ⇒ x ≡ 20 ≡ 6.
- 19−1 mod 141: 141 = 7·19 + 8; 19 = 2·8 + 3; 8 = 2·3 + 2; 3 = 2 + 1. Back-substituting gives 1 = 52·19 − 7·141, so the inverse is 52.
- 32−1 mod 17: 32 ≡ −2, and (−2)(−9) = 18 ≡ 1, so −9 ≡ 8 (check 32·8 = 256 = 15·17 + 1).
Extended Euclidean algorithm
Run Euclid forward until the remainder is 1, then substitute back to write 1 = s·a + t·m; s mod m is the inverse.
Worked example: 13−1 mod 2436
Forward: 2436 = 187·13 + 5; 13 = 2·5 + 3; 5 = 1·3 + 2; 3 = 1·2 + 1.
Back: 1 = 3 − 2 = 3 − (5 − 3) = 2·3 − 5 = 2(13 − 2·5) − 5 = 2·13 − 5·5 = 2·13 − 5(2436 − 187·13) = 937·13 − 5·2436.
Inverse = 937. Check: 13·937 = 12,181 = 5·2436 + 1. (The source notes gave 947 after a slip in the forward step; 13·947 leaves remainder 131.)
OpenSSL runs this to compute the RSA private exponent d = e−1 mod φ(n).
Chinese remainder theorem
If m1, …, mn are pairwise coprime, the system x ≡ ak (mod mk) has a unique solution mod M = ∏mk.
Mk = M/mk; yk = Mk−1 mod mk; x = Σ akMkyk mod M.
It works because every other term contains mj as a factor and vanishes mod mj.
Worked example
x ≡ 2 (mod 3), 3 (mod 5), 2 (mod 7). M = 105; Mk = 35, 21, 15; yk = 2, 1, 1. x = 2·35·2 + 3·21·1 + 2·15·1 = 233 ≡ 23 (mod 105). Check: 23 leaves 2, 3, 2.
RSA-CRT: computing Cd mod p and mod q with half-size moduli and recombining makes decryption and signing about four times faster.