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

Number Theory & Crypto Intro

Every HTTPS connection, every signed software update and every SSH login rests on a few facts about whole numbers: multiplying two primes is easy but splitting the product is hard, raising a number to a power modulo pp is easy but undoing it is hard, and a small set of rules about remainders lets two strangers agree on a secret over a public channel. This course teaches that number theory and then builds the public-key cryptography on top of it, one runnable Python example at a time.

The reference books

The topic order follows two freely available books, used only as maps of topics:

  • William Stein, Elementary Number Theory: Primes, Congruences, and Secrets (Springer, 2009). The author publishes a free PDF at wstein.org/ent. It is the guide for divisibility, primes, congruences, Fermat and Euler, primitive roots, quadratic reciprocity and the first look at RSA, Diffie-Hellman and elliptic curves.
  • Dan Boneh and Victor Shoup, A Graduate Course in Applied Cryptography (free at toc.cryptobook.us). It is the guide for the cryptography side: security goals, why textbook RSA fails, padding, ElGamal, signatures, hash functions and lattice-based schemes.

Thanks to the authors for making their books open. All explanations, numbers, code and exercises in these lessons are written from scratch for this site.

What is in the course

Part Topics
1. Divisibility divisibility, division with remainder, gcd, Euclid and extended Euclid, Diophantine equations
2. Primes infinitely many primes, unique factorization, sieves, the prime number theorem, factoring
3. Congruences modular arithmetic, inverses, linear congruences, the Chinese remainder theorem
4. Fermat and Euler Fermat's little theorem, φ(n)\varphi(n), Euler's theorem, fast exponentiation, orders
5. Primality Fermat test, Carmichael numbers, Miller-Rabin, generating large primes
6. Discrete logs primitive roots, the discrete log problem, baby-step giant-step, Pohlig-Hellman
7. Quadratic residues squares mod pp, Legendre and Jacobi symbols, reciprocity, modular square roots
8. Public-key crypto RSA, its attacks and padding, signatures, Diffie-Hellman, ElGamal
9. Elliptic curves the group law, curves over Fp\mathbb{F}_p, ECDH, ECDSA
10. Hashes, fields, randomness hash functions, the birthday bound, HMAC, GF(2n)GF(2^n) and AES, secure random numbers
11. Lattices lattices, reduction, learning with errors, post-quantum cryptography

Here is the course in one toy example: RSA with two small primes. Key generation needs a gcd and a modular inverse (part 1 and 3), encryption and decryption are modular powers (part 4), and the reason it works is Euler's theorem.

python · try it yourself
from math import gcd

p, q = 101, 113                  # toy primes; real RSA uses primes of 1024+ bits
n, phi = p * q, (p - 1) * (q - 1)
e = 17
assert gcd(e, phi) == 1
d = pow(e, -1, phi)              # modular inverse (Python 3.8+)
m = 4242                         # the "message", a number below n
c = pow(m, e, n)                 # encrypt
print("n =", n, " phi =", phi, " d =", d)
print("ciphertext:", c, " decrypted:", pow(c, d, n))
n = 11413  phi = 11200  d = 3953
ciphertext: 4545  decrypted: 4242

And the other half of public-key cryptography: Diffie-Hellman. Two parties exchange gag^a and gbg^b modulo a prime in public and both arrive at gabg^{ab}, which an eavesdropper cannot compute without solving a discrete logarithm.

python · try it yourself
p, g = 2027, 2                   # a toy prime and generator
a, b = 1234, 567                 # the two private exponents
A, B = pow(g, a, p), pow(g, b, p)
print("public values:", A, B)
print("shared secrets:", pow(B, a, p), pow(A, b, p))
public values: 1646 72
shared secrets: 1562 1562

Warning: Every program in this course is teaching code. The numbers are tiny, the padding is missing and nothing runs in constant time. Never use these functions to protect real data; use a vetted library such as Python's cryptography package or your platform's TLS stack.

What you should know first

The course is intermediate. It assumes comfort with Python and with proofs at the level of Discrete Mathematics, whose divisibility, gcd, modular arithmetic and RSA lessons are a gentler first pass. For a refresher on primes and remainders see Basic Math. The practical side of security (TLS, password storage, certificates) is in Cybersecurity; this course explains the mathematics underneath it.

How lessons work

Each lesson states the idea in math notation (a≡b(modn)a \equiv b \pmod{n}, gcd⁡(a,b)\gcd(a, b), φ(n)\varphi(n)), proves or motivates it, computes it in Python with built-in big integers (pow(a, e, n), math.gcd), and ends with an In software note, exercises with answers and worked solutions, and a short quiz.

Tip: Python integers have unlimited size, so pow(3, 10**6, 10**9 + 7) and 2048-bit RSA numbers both just work. NumPy integers do not: they overflow at 64 bits (32 in the browser). Use plain int for number theory.

Learning paths

Your goal Suggested route
Security engineer Discrete Math → this course (parts 1-4, 8, 10) → Cybersecurity
Blockchain developer this course (parts 3-5, 9, 10) → Solidity
Algorithms and contests parts 1-5 → Data Structures & Algorithms

Exercises

Exercise 1: Easy one way, hard the other

Multiplying 101⋅113101 \cdot 113 is quick. If you were only given 11413, how would you recover the two primes, and why does this get impossibly slow for 600-digit numbers?

Answer

Trial division by primes up to 11413≈106.8\sqrt{11413} \approx 106.8 finds 101; for a 600-digit number there are about 1029710^{297} candidates below the square root.

Solution

Every composite nn has a prime factor at most n\sqrt{n}. Trying 2,3,5,…2, 3, 5, \ldots reaches 101 after 26 primes. For n≈10600n \approx 10^{600} the square root is 1030010^{300}, and even the best known factoring algorithms (the number field sieve) need far more operations than any computer can do. RSA's security rests on this gap.

Exercise 2: Check a decryption (code)

With the RSA numbers above, decrypt the ciphertext 1 and the ciphertext 0. Explain the result without running anything, then confirm in code.

Answer

Both decrypt to themselves: 1d=11^d = 1 and 0d=00^d = 0.

Solution

Powers of 0 and 1 never change, so these "messages" encrypt to themselves. This is a first hint that textbook RSA leaks information (Why Textbook RSA Is Insecure).

python · try it yourself
n, d = 101 * 113, pow(17, -1, 100 * 112)
print(pow(1, d, n), pow(0, d, n))
1 0

Exercise 3: A shared secret by hand

With p=11p = 11, g=2g = 2, a=3a = 3 and b=4b = 4, compute AA, BB and the shared secret.

Answer

A=8A = 8, B=5B = 5, shared secret =4= 4.

Solution

A=23=8A = 2^3 = 8 and B=24=16≡5(mod11)B = 2^4 = 16 \equiv 5 \pmod{11}. Then Ba=53=125=11⋅11+4≡4B^a = 5^3 = 125 = 11 \cdot 11 + 4 \equiv 4 and Ab=84=4096=372⋅11+4≡4A^b = 8^4 = 4096 = 372 \cdot 11 + 4 \equiv 4. Both sides get 212≡4(mod11)2^{12} \equiv 4 \pmod{11}.

Test yourself

RSA's security relies mainly on the difficulty of…

  1. adding large numbers
  2. factoring a product of two large primes
  3. sorting numbers
  4. computing a gcd

Why does the course use Python's built-in int rather than NumPy integers?

  1. NumPy is slower to import
  2. Python integers have unlimited precision, NumPy integers overflow
  3. NumPy cannot do modular arithmetic
  4. Python integers are always 64-bit

The examples in this course are…

  1. production-ready cryptography
  2. teaching code with toy parameters, not for protecting real data
  3. faster than OpenSSL
  4. certified by NIST