Section 2: Math Foundations

Modern cryptography is applied mathematics, but here is the good news: to genuinely understand the ciphers, hashes, and key exchanges in the rest of this course, you need surprisingly little. If you can add, multiply, and divide with remainders, you already have the raw material. This page builds everything else you need: modular arithmetic, primes and GCDs, Euler’s totient function, a dash of probability and entropy, and the humble XOR. Every concept comes with an interactive widget — this is the most hands-on page on the site, so play with everything.

Why math at all?
Cryptography needs operations that are easy to do in one direction and hard to reverse without a secret. Multiplying two large primes takes microseconds; factoring the product back apart can take longer than the age of the universe. That asymmetry lives entirely in number theory — which is why we start here.

Modular arithmetic: the clock that powers everything

Modular arithmetic is just “clock math.” On a 12-hour clock, 5 hours after 9 o’clock is 2 o’clock, not 14 o’clock — the numbers wrap around. We say the clock works modulo 12. In general, a mod n means “the remainder when a is divided by n,” and it is always a number from 0 to n−1.

0 1 2 3 4 5 6 7 8 9 10 11 +4 9 + 4 = 13 13 doesn't fit — the hand sweeps past 0 and wraps 9 + 4 ≡ 1 (mod 12) same wheel, any n: results live in 0 … n−1
Arithmetic on a wheel: start at 9 (cyan), step forward 4, wrap past 0, land on 1 (green). Every "mod n" calculation is this picture with n positions on the dial.

The notation you will see everywhere is:

a ≡ b (mod n)     — read: "a is congruent to b modulo n"

which means a and b leave the same remainder when divided by n. For example, 17 ≡ 5 (mod 12) because both leave remainder 5, and 100 ≡ 2 (mod 7) because 100 = 14×7 + 2.

What makes modular arithmetic so useful is that addition and multiplication survive the wrap-around. You can reduce mod n at any point during a calculation and the answer comes out the same:

PropertyRuleWorked example (mod 7)
Addition(a + b) mod n = ((a mod n) + (b mod n)) mod n(23 + 40) mod 7 = 63 mod 7 = 0, and (2 + 5) mod 7 = 0 ✓
Multiplication(a × b) mod n = ((a mod n) × (b mod n)) mod n(23 × 40) mod 7 = 920 mod 7 = 3, and (2 × 5) mod 7 = 10 mod 7 = 3 ✓
Exponentiationak mod n = reduce after every multiply23² mod 7 = 529 mod 7 = 4, and 2² mod 7 = 4 ✓

This is a big deal for cryptography. RSA computes things like m65537 mod n where n is a 600-digit number. Without the ability to reduce as you go, the intermediate numbers would have more digits than there are atoms in the universe. With modular reduction, every intermediate value stays smaller than n.

Fast modular exponentiation (square-and-multiply)

Even with reduction, computing ae mod n by multiplying a by itself e times is hopeless when e has hundreds of digits — that would be more multiplications than seconds in the lifetime of the universe. The trick is square-and-multiply: repeatedly square the base (each squaring doubles the exponent covered), and multiply in an extra factor whenever the binary expansion of the exponent has a 1 bit. Computing 313 mod 7: since 13 = 1101 in binary, you need only 3 squarings and 2 extra multiplies instead of 12 multiplications. For a 2048-bit exponent, that is roughly 3,000 multiplications instead of 22048 — the difference between a millisecond and never. Every RSA signature and every Diffie-Hellman handshake your browser performs relies on this one algorithm.

Mod calculator & fast modpow
result appears here
try 7^128 mod 13 — then try a truly huge exponent like 65537
Watch out: negative numbers
Many programming languages (including JavaScript) return a negative remainder for negative inputs: -17 % 12 gives −5, not 7. Cryptographic code always normalizes to the range 0 … n−1. That is exactly what CL.mod does — and a classic source of bugs when it is forgotten.

Prime numbers and the Euclidean algorithm

A prime is an integer greater than 1 whose only divisors are 1 and itself: 2, 3, 5, 7, 11, 13, … Primes are the atoms of arithmetic — every integer factors into primes in exactly one way. Cryptography loves them for two reasons:

Two numbers do not need to be prime themselves to be useful — often we only need them to be coprime (sharing no common factor except 1). The tool for checking is the greatest common divisor, and the 2,300-year-old Euclidean algorithm computes it astonishingly fast. The idea: gcd(a, b) = gcd(b, a mod b), repeated until the remainder hits zero. The last nonzero remainder is the answer.

Worked example — gcd(252, 105):

StepDivisionQuotientRemainder
1252 = 2 × 105 + 42242
2105 = 2 × 42 + 21221
342 = 2 × 21 + 020 — stop

The last nonzero remainder is 21, so gcd(252, 105) = 21. Three steps, no factoring required. Since 21 ≠ 1, the two numbers are not coprime. The same algorithm, run “in reverse” (the extended Euclidean algorithm), is how RSA computes its private key from its public key parameters — you will meet it again in Section 6.

252 = 2 × 105 + 42 105 105 42 105 = 2 × 42 + 21 42 42 21 42 = 2 × 21 + 0 — stop 21 21 21 gcd(252, 105) = 21 — the largest tile that measures both bars exactly
Euclid's algorithm as tiling, drawn to scale: fit copies of the smaller number into the larger; the leftover (red) becomes the new smaller number. When the leftover hits 0, the previous remainder — 21 — tiles everything perfectly.
Prime checker & GCD stepper
enter a number and check
steps appear here, line by line

Euler’s totient function φ(n)

φ(n) (phi of n) counts how many integers from 1 to n are coprime to n. For example, φ(10) = 4, because only 1, 3, 7, and 9 share no factor with 10 — the even numbers and 5 are disqualified.

Two special cases carry almost all of RSA on their shoulders:

RuleWhyExample
φ(p) = p − 1 for prime pA prime shares a factor with nothing below itφ(13) = 12
φ(p×q) = (p−1)(q−1) for distinct primes p, qOnly multiples of p or q are excludedφ(15) = φ(3×5) = 2×4 = 8

Check the second one by hand: the numbers 1–15 coprime to 15 are 1, 2, 4, 7, 8, 11, 13, 14 — exactly eight of them.

Now the theorem that makes public-key cryptography possible. Euler’s theorem says that if gcd(a, n) = 1, then:

a^φ(n) ≡ 1 (mod n)

Try it: φ(10) = 4, and 34 = 81 ≡ 1 (mod 10). Or 74 = 2401 ≡ 1 (mod 10). Exponents effectively work modulo φ(n) — raising to the power φ(n) is like going all the way around the clock and landing back at 1.

The RSA punchline (preview of Section 6)
RSA picks two secret primes p and q, publishes n = pq, and chooses encryption/decryption exponents e and d such that e×d ≡ 1 (mod φ(n)). Then encrypting (raise to e) followed by decrypting (raise to d) gives med = m1 + k·φ(n) ≡ m (mod n) by Euler’s theorem — the message comes back. An attacker who wants d must compute φ(n) = (p−1)(q−1), and the only known way to do that is to factor n. The entire scheme is Euler’s theorem plus the hardness of factoring.
Totient explorer
try primes, then products of two primes, and verify the formulas

Probability and entropy: how surprised is an attacker?

The birthday paradox

In a room of just 23 people, there is a 50% chance two share a birthday. This feels wrong — 23 is tiny next to 365 — until you notice you are not comparing one person against the room, you are comparing every pair, and 23 people form 253 pairs. Collisions among random values arrive roughly at the square root of the number of possible values, not at the number itself.

This matters enormously for hash functions. A 128-bit hash has 2128 possible outputs, but an attacker looking for any two inputs with the same hash expects success after only about 264 attempts — the square root. That is why a hash meant to resist collisions needs twice as many bits as your target security level: SHA-256 gives 128-bit collision resistance, not 256. You will see this used in real attacks in Section 5.

Entropy: measuring unpredictability in bits

Entropy quantifies how hard something is to guess. If a secret is chosen uniformly from N equally likely possibilities, it has log₂(N) bits of entropy — each bit doubles the attacker’s work. A fair coin flip is 1 bit; a random lowercase letter is log₂(26) ≈ 4.7 bits; a random byte is 8 bits.

4 fair coin flips = 4 bits of entropy H T T H → the secret "1001", one of 2⁴ = 16 equally likely values each extra bit doubles the attacker's search space 1 bit 2 2 bits 4 3 bits 8 4 bits 16 5 bits 32 … at 128 bits the bar would wrap around the observable universe many times over
Entropy in pictures: n independent fair coin flips give n bits, and possibilities grow as 2ⁿ. Linear growth in bits, exponential growth in guessing work — which is why key length is measured in bits, not digits.

For a password of length L drawn from a character set of size S, the entropy is L × log₂(S)provided every character is chosen uniformly at random. Human-chosen passwords have far less entropy than this formula suggests, because humans pick words, dates, and keyboard patterns. Compare some honest numbers, assuming an attacker with specialized hardware making 1012 guesses per second:

Password styleEntropyCombinationsAvg. time to crack at 10¹²/sec
8 random lowercase letters8 × 4.70 ≈ 37.6 bits≈ 2.1 × 10¹¹about 0.1 seconds
4 random words from a 7,776-word list (diceware)4 × 12.9 ≈ 51.7 bits≈ 3.7 × 10¹⁵about half an hour
16 random printable characters (95 symbols)16 × 6.57 ≈ 105 bits≈ 4.4 × 10³¹about 700 billion years

Notice the pattern: entropy grows linearly with length but cracking time grows exponentially. Length beats cleverness every time. Cryptographic keys aim for 128+ bits of entropy, at which point brute force is physically off the table regardless of hardware.

Entropy estimator
bits of entropy and brute-force time appear here

Bitwise operations: XOR, the workhorse

Computers store everything as bits, and ciphers manipulate those bits directly. The star of the show is XOR (exclusive or, written ⊕): it outputs 1 exactly when its inputs differ.

aba ⊕ ba AND ba OR b
00000
01101
10101
11011

Three properties make XOR the heart of stream ciphers and the one-time pad:

Combine them and you get the fundamental trick of symmetric encryption for free. Encrypt by XORing plaintext with a key: c = m ⊕ k. Decrypt by XORing again with the same key:

c ⊕ k = (m ⊕ k) ⊕ k = m ⊕ (k ⊕ k) = m ⊕ 0 = m
m ⊕ k c ⊕ k m 01101001 10110010 11011011 10110010 01101001 message k=1 flips the bit, k=0 leaves it ciphertext same key flips the same bits back = m recovered ✓ m ⊕ k ⊕ k = m — encrypting twice with the same key is a no-op
XOR as a bank of toggle switches: wherever the key holds a 1, the message bit flips. Apply the key once to scramble, apply it again and every flipped bit flips back — decryption is literally re-encryption.

Encryption and decryption are the same operation. If the key stream is truly random, used once, and as long as the message, this is the one-time pad — the only provably unbreakable cipher. Every practical stream cipher (RC4, ChaCha20) is an attempt to fake that random key stream from a short key. XOR also appears inside AES round operations and in the padding-oracle and keystream-reuse attacks of Section 8, so build intuition for it now.

The other bit operations play supporting roles: AND masks bits off (x AND 0x0F keeps only the low 4 bits), OR forces bits on, and shifts («, ») move bits left or right — a left shift by k multiplies by 2k. Hash functions like SHA-256 are built almost entirely from XOR, AND, rotations, and additions.

XOR playground
hex of A ⊕ B, then the round trip (A ⊕ B) ⊕ B = A
Never reuse a keystream
If two messages m₁ and m₂ are XORed with the same keystream k, an attacker who captures both ciphertexts can compute c₁ ⊕ c₂ = m₁ ⊕ m₂ — the key drops out entirely, leaving two plaintexts XORed together, which is very breakable. This exact mistake broke Soviet one-time pads (project VENONA) and the WEP Wi-Fi standard.

Check your understanding

Going deeper

courseKhan Academy — Modular Arithmetic
Gentle, visual introduction to mod, congruence, and modular exponentiation with practice exercises.
videoIntroduction to Cryptography — Christof Paar
Full university lecture series covering the math behind every major cipher; the companion to the free-to-read Understanding Cryptography textbook.
pdfA Computational Introduction to Number Theory and Algebra — Victor Shoup
Rigorous and free: the full text of the standard number-theory-for-cryptographers reference, downloadable at shoup.net.
video3Blue1Brown
Beautiful visual math intuition — see especially the videos on the Enigma-adjacent counting problems, primes, and the exponential function.