🔢 1. The mathematics of public-key cryptography
Two computers that have never met, talking over a line that everybody can listen to, agree on a secret that nobody else knows. That sounds impossible, and for most of history it was. Since the 1970s it is done billions of times a day: every SSH login, every HTTPS page, every signed software update.
This part explains the mathematics behind it. Every example uses small numbers that you can check by hand (or in Python: pow(base, exponent, modulus)). Real systems use the same formulas with numbers of 77 to 925 digits (why exactly those sizes?).
Every section has a practice page with many more worked examples and exercises (answers hidden), and there is a separate chapter on prime numbers. Look for the ✏️ boxes.
0. The three jobs
Public-key cryptography does three different jobs. Keep them apart, because each protocol in the next parts uses a different mix:
| Job | Question it answers | Examples |
|---|---|---|
| Key exchange | How do we get a shared secret over an open line? | Diffie–Hellman, ECDH (X25519), ML-KEM |
| Signature | How do I prove that I wrote this, without giving away my secret? | RSA signatures, Ed25519, ECDSA |
| Encryption | How do I lock something that only you can open? | RSA encryption, ECDH + a symmetric cipher |
The actual data is never encrypted with public-key maths, which is slow. It is encrypted with a fast symmetric cipher (AES or ChaCha20) using a key that the public-key part produced. Public-key cryptography only does the hard part: getting that key to the right person and proving who is who.
All three jobs rest on the same idea: a one-way function, a calculation that is easy in one direction and practically impossible to reverse, unless you know a secret (a trapdoor).
1. Clock arithmetic
All of it happens in modular arithmetic: you count on a clock. With modulus 12, $9 + 5 = 14$, but on the clock that is 2. We write:
$$14 \bmod 12 = 2 \qquad\text{or}\qquad 14 \equiv 2 \pmod{12}$$“$a \bmod n$” is simply the remainder after dividing by $n$. Adding and multiplying work as usual, you just take the remainder at the end (or in between, which gives the same result):
$$7 \cdot 8 = 56 \equiv 4 \pmod{13}$$Dividing works differently. You do not divide; you multiply by the inverse: the number that gives 1 when multiplied. Modulo 7 the inverse of 3 is 5, because:
$$3 \cdot 5 = 15 \equiv 1 \pmod 7$$An inverse exists only when the number and the modulus share no factor (their greatest common divisor is 1). The extended Euclidean algorithm finds it quickly, even for numbers with hundreds of digits (in Python: pow(3, -1, 7)).
✏️ Practise: Clock arithmetic: exercises: remainders, inverses step by step with the extended Euclidean algorithm, solving equations, Fermat’s little theorem, and the clock arithmetic inside your IBAN.
2. Easy forward, hard backward
Forward is fast. To calculate $5^{13} \bmod 23$ you do not multiply 13 times. You square repeatedly and take the remainder each time (square-and-multiply):
$$5^1 = 5,\quad 5^2 = 25 \equiv 2,\quad 5^4 \equiv 2^2 = 4,\quad 5^8 \equiv 4^2 = 16 \pmod{23}$$$$5^{13} = 5^{8} \cdot 5^{4} \cdot 5^{1} \equiv 16 \cdot 4 \cdot 5 = 320 \equiv 21 \pmod{23}$$For an exponent of 600 digits that is about 2,000 squarings: milliseconds.
Backward is hard. The opposite question, “5 to the power of what gives 21 modulo 23?”, is the discrete logarithm. Look at all the powers of 5 modulo 23:
| $k$ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| $5^k \bmod 23$ | 5 | 2 | 10 | 4 | 20 | 8 | 17 | 16 | 11 | 9 | 22 | 18 | 21 | 13 | 19 | 3 | 15 | 6 | 7 | 12 | 14 | 1 |
The results jump around without any pattern; every number from 1 to 22 appears exactly once. Here you can still look it up in the table ($k = 13$), but with a modulus of 600 digits the table has more rows than there are atoms in the universe, and no known method is much faster than (cleverly) searching.
Two problems like this carry almost all public-key cryptography today:
- Factoring: multiplying two primes is easy ($47 \cdot 59 = 2773$), finding them back from $2773$ is hard when the primes are big. → RSA
- Discrete logarithm: $g^k \bmod p$ is easy, finding $k$ is hard. → Diffie–Hellman, and its elliptic-curve version → X25519, Ed25519
✏️ Practise: Easy forward, hard backward: exercises: square-and-multiply by hand, discrete logarithms, generators, baby-step giant-step, and factoring tricks.
🔢 Background: Prime numbers: why there are infinitely many, how many there are, Euler’s φ, Fermat’s little theorem with proof, and how computers test whether a 300-digit number is prime.
3. RSA (1977)
RSA turns factoring into a trapdoor. Let’s make a key.
Key generation
- Pick two primes: $p = 47$, $q = 59$.
- Multiply: $n = p \cdot q = 2773$. This is the modulus; it is public.
- Calculate $\varphi(n) = (p-1)(q-1) = 46 \cdot 58 = 2668$. This number is the trapdoor: you can only calculate it if you know $p$ and $q$.
- Pick a public exponent that shares no factor with 2668: $e = 17$ (real keys use 65537).
- Calculate the private exponent $d$, the inverse of $e$ modulo $\varphi(n)$:
- Public key: $(n, e) = (2773, 17)$
- Private key: $d = 157$ (and $p$, $q$, which you throw away or keep secret)
Encrypting a message $m = 1234$ (a number smaller than $n$) with the public key:
$$c = m^e \bmod n = 1234^{17} \bmod 2773 = 1793$$Decrypting with the private key:
$$m = c^d \bmod n = 1793^{157} \bmod 2773 = 1234 \;✓$$Why does this work? Euler’s theorem says that $m^{\varphi(n)} \equiv 1 \pmod n$. Because $e \cdot d = 1 + k \cdot \varphi(n)$ for some whole number $k$:
$$c^d = m^{e d} = m^{1 + k\varphi(n)} = m \cdot \left(m^{\varphi(n)}\right)^k \equiv m \cdot 1^k = m \pmod n$$Signing is the same calculation the other way round. You put the hash of a document (say $h = 999$) through the private key:
$$s = h^d \bmod n = 999^{157} \bmod 2773 = 2089$$Anyone can check it with the public key: $2089^{17} \bmod 2773 = 999$, which matches the hash of the document. Only the owner of $d$ could have made $s$.
Why is it safe? An attacker knows $n$ and $e$. To find $d$ he needs $\varphi(n)$, so he needs $p$ and $q$, so he needs to factor $n$. For $2773$ that takes a second. For a 3072-bit $n$ (925 digits) it is far out of reach with every known method.
⚠️ “Textbook RSA” as above is not safe in practice. The same message always gives the same ciphertext, and an attacker can manipulate ciphertexts in useful ways. Real RSA always adds random padding: OAEP for encryption, PSS (or PKCS #1 v1.5) for signatures.
✏️ Practise and go deeper: RSA: exercises and in depth: make your own keys, the full proof, the Chinese-remainder speed-up, five ways to break textbook RSA, and reading a real OpenSSL key.
4. Diffie–Hellman key exchange (1976)
Diffie–Hellman solves the opening question: two parties get a shared secret, while everybody listens.
The paint analogy. Alice and Bob publicly agree on yellow paint. Each mixes in a secret colour of their own and sends the mix to the other. Each then adds their own secret colour to what they received. Both end up with yellow + Alice’s colour + Bob’s colour: the same colour. A listener only saw the two mixes, and un-mixing paint is impossible.
The real thing. Publicly agreed: a prime $p = 23$ and a base $g = 5$.
| Alice | Bob | |
|---|---|---|
| picks a secret | $a = 6$ | $b = 15$ |
| sends | $A = 5^6 \bmod 23 = 8$ | $B = 5^{15} \bmod 23 = 19$ |
| calculates | $B^a = 19^6 \bmod 23 = 2$ | $A^b = 8^{15} \bmod 23 = 2$ |
Both get 2, because $(g^b)^a = g^{ab} = (g^a)^b$. The listener sees $23, 5, 8, 19$. To get the secret, he has to find $a$ from $8 = 5^a$: a discrete logarithm (in the table above: $k = 6$). With a real 2048-bit prime he cannot.
The shared secret itself never travels over the line. And when Alice and Bob throw away $a$ and $b$ after the conversation, nobody can ever reconstruct it, not even Alice and Bob. This is called forward secrecy: someone who records everything today and steals a server’s keys next year still cannot read today’s conversation.
⚠️ Diffie–Hellman alone does not tell you who you are talking to. An attacker in the middle can do one exchange with Alice and another with Bob, and pass everything along. That is why every protocol combines it with a signature: in SSH the server signs the exchange with its host key, in TLS with its certificate.
✏️ Practise and go deeper: Diffie–Hellman: exercises and in depth: subgroups, Pohlig–Hellman, the small-subgroup and man-in-the-middle attacks with real numbers, forward secrecy, and the groups real protocols use.
5. Elliptic curves
RSA and classic Diffie–Hellman need big numbers: 3072 bits for good security. Elliptic curves give the same security with 256 bits, which means shorter keys and much faster calculations. That is why modern SSH keys (Ed25519) and almost every HTTPS connection (X25519) use them.
5.1 The curve
An elliptic curve is the set of points $(x, y)$ that satisfy:
$$y^2 = x^3 + ax + b$$On paper (with real numbers) it is a smooth curve, symmetric around the x-axis. The magic is that you can add two points and get a third point on the same curve:
- Draw a line through $P$ and $Q$. It crosses the curve in exactly one more point.
- Mirror that point in the x-axis. The result is $P + Q$.
- $P + P$ (doubling) uses the tangent line at $P$.
- There is one extra point, $\mathcal{O}$ (“the point at infinity”), which plays the role of zero.
5.2 The same, on a clock
Cryptography does not use real numbers but clock arithmetic. Take this small curve modulo 17:
$$y^2 \equiv x^3 + 2x + 2 \pmod{17}$$It has exactly 19 points (18 pairs $(x, y)$ plus $\mathcal{O}$). The line-and-mirror rule turns into formulas. For two different points $(x_1, y_1)$ and $(x_2, y_2)$:
$$\lambda = \frac{y_2 - y_1}{x_2 - x_1}, \qquad x_3 = \lambda^2 - x_1 - x_2, \qquad y_3 = \lambda(x_1 - x_3) - y_1$$and for doubling a point, $\lambda = \dfrac{3x_1^2 + a}{2y_1}$. All calculations are modulo 17, and “dividing” means multiplying by the inverse (section 1).
A worked example. Take the starting point $G = (5, 1)$. We will see below that $3G = (10, 6)$ and $4G = (3, 1)$. Add them:
$$\lambda = \frac{1 - 6}{3 - 10} = \frac{-5}{-7} \equiv \frac{12}{10} \equiv 12 \cdot 10^{-1} \equiv 12 \cdot 12 = 144 \equiv 8 \pmod{17}$$(the inverse of 10 is 12, because $10 \cdot 12 = 120 = 7 \cdot 17 + 1$)
$$x_3 = 8^2 - 10 - 3 = 51 \equiv 0, \qquad y_3 = 8 \cdot (10 - 0) - 6 = 74 \equiv 6 \pmod{17}$$So $3G + 4G = (0, 6)$, and indeed that is $7G$ in the table below.
5.3 Multiplying a point by a number
$kG$ means $G + G + \dots + G$ ($k$ times). Here are all multiples of $G = (5, 1)$:
| $k$ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| $kG$ | (5,1) | (6,3) | (10,6) | (3,1) | (9,16) | (16,13) | (0,6) | (13,7) | (7,6) | (7,11) |
| $k$ | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
|---|---|---|---|---|---|---|---|---|---|
| $kG$ | (13,10) | (0,11) | (16,4) | (9,1) | (3,16) | (10,11) | (6,14) | (5,16) | $\mathcal{O}$ |
After 19 steps you are back at zero, so this curve’s group order is $n = 19$, and numbers that multiply points are counted modulo 19.
Again the points jump around without pattern. That gives the elliptic-curve version of the one-way function:
- Forward: from $k$ and $G$ to $Q = kG$ is fast, by doubling and adding (double-and-add, like square-and-multiply). For a 256-bit $k$: about 256 doublings.
- Backward: from $Q$ and $G$ to $k$ is the elliptic-curve discrete logarithm problem (ECDLP). For good curves the best known attacks take about $\sqrt{n}$ steps: $2^{128}$ for a 256-bit curve. Out of reach.
In elliptic-curve cryptography, the private key is a number $k$, and the public key is the point $kG$.
5.4 ECDH: Diffie–Hellman on a curve
Exactly the same as section 4, with points instead of powers:
| Alice | Bob | |
|---|---|---|
| secret | $a = 3$ | $b = 10$ |
| sends | $A = 3G = (10, 6)$ | $B = 10G = (7, 11)$ |
| calculates | $aB = 3 \cdot (7, 11) = (13, 10)$ | $bA = 10 \cdot (10, 6) = (13, 10)$ |
Both get $(13, 10) = 30G = 11G$, because $a(bG) = b(aG) = abG$. The listener has to find 3 from $(10, 6)$.
5.5 Real curves
| Curve | Field modulus $p$ | Used in |
|---|---|---|
| Curve25519 (Daniel J. Bernstein, 2006) | $2^{255} - 19$ | X25519 key exchange (SSH, TLS, WireGuard, Signal), Ed25519 signatures (as an equivalent Edwards curve) |
| NIST P-256 | $2^{256} - 2^{224} + 2^{192} + 2^{96} - 1$ | TLS certificates, ECDSA, smart cards, passkeys |
Both have roughly $2^{252}$ to $2^{256}$ points. Curve25519 is designed so that the obvious, simple implementation is also the safe one (constant-time, no special cases to forget), and its constants are explained instead of just given. That is a big part of why it became the default almost everywhere.
🌀 Go deeper: Elliptic curves and ECDH in depth: derive the addition formulas yourself, find every point by hand, double-and-add, ECDH on two curves, and how Curve25519, the Montgomery ladder and Edwards curves work.
6. Digital signatures on a curve (Schnorr / EdDSA)
How do you prove that you know $x$ (your private key) without revealing it? The Schnorr signature (1989) is the simplest answer, and Ed25519 is a careful version of it.
- Private key: a number $x$. Public key: $P = xG$.
Signing a message $m$:
- Pick a fresh secret number $k$ (the nonce) and calculate $R = kG$.
- Hash everything together: $e = H(R, P, m)$, a number modulo $n$.
- Calculate $s = k + e \cdot x \pmod n$.
- The signature is the pair $(R, s)$.
Verifying: anybody with $P$ checks that
$$sG = R + eP$$Why it works: $sG = (k + ex)G = kG + e(xG) = R + eP$. The secret $x$ is hidden inside $s$, masked by the random $k$, so $s$ reveals nothing about $x$.
With our small curve ($n = 19$): private key $x = 7$, so $P = 7G = (0, 6)$. Nonce $k = 10$, so $R = 10G = (7, 11)$. Suppose the hash gives $e = 5$. Then:
$$s = 10 + 5 \cdot 7 = 45 \equiv 7 \pmod{19}$$Check: $sG = 7G = (0, 6)$. And $R + eP = 10G + 5 \cdot 7G = 10G + 35G = 45G = 7G = (0, 6)$ ✓.
⚠️ The nonce $k$ must never be reused or predictable. Two signatures with the same $k$ give two equations with one unknown, and anybody can solve them for $x$. This is exactly how the PlayStation 3 signing key was extracted in 2010 (Sony used ECDSA with a fixed nonce). Ed25519 avoids it by not using a random $k$ at all: it calculates $k$ as a hash of the private key and the message, so it is unique per message and never depends on a good random generator.
ECDSA (used with P-256) is the older, more complicated cousin: $s = k^{-1}(h + r x) \bmod n$, where $r$ is the x-coordinate of $kG$. It does the same job, with the same nonce danger.
✏️ Practise and go deeper: Digital signatures: exercises and in depth: Schnorr as a proof of knowledge, Fiat–Shamir, ECDSA by hand, recovering a private key from a reused nonce, and why Ed25519 needs no random numbers.
7. How big is “big enough”?
Security is measured in bits: “128-bit security” means about $2^{128}$ operations to break it, more than all computers on Earth can do before the sun burns out. Equivalent key sizes (NIST SP 800-57):
| Security | Symmetric (AES) | RSA / classic DH | Elliptic curve |
|---|---|---|---|
| 112 bits | 3DES (old) | 2048 | 224 |
| 128 bits | AES-128 | 3072 | 256 (Curve25519, P-256) |
| 192 bits | AES-192 | 7680 | 384 |
| 256 bits | AES-256 | 15360 | 512 |
That is why an Ed25519 public key is 32 bytes and a comparable RSA key 384 bytes.
📏 Go deeper: Why 77 to 925 digits?: what 128-bit security means in years, why RSA needs twelve times more digits than a curve, the records of what has been broken, and why we don’t simply use bigger numbers.
8. Quantum computers
In 1994 Peter Shor showed that a large enough quantum computer can factor and solve discrete logarithms (also on elliptic curves) quickly. That would break RSA, Diffie–Hellman, X25519, Ed25519 and ECDSA alike. Symmetric ciphers and hashes are hit much less: Grover’s algorithm roughly halves their security, so AES-256 stays fine.
Such a quantum computer does not exist yet. But traffic recorded today can be decrypted later (“harvest now, decrypt later”), so the key exchange is being replaced first.
The replacement is based on lattices. The idea of learning with errors, in one sentence: solving a set of linear equations is easy, but if every equation has a small random error added, finding the solution becomes extremely hard, even for a quantum computer. In 2024 NIST standardised:
- ML-KEM (FIPS 203, formerly Kyber) for key exchange,
- ML-DSA (FIPS 204, formerly Dilithium) and SLH-DSA (FIPS 205) for signatures.
Because these are young, they are deployed as hybrids: classic X25519 and ML-KEM together, so the result is safe as long as either one holds. OpenSSH uses this by default (mlkem768x25519-sha256, see part 2), and so do current browsers (X25519MLKEM768, see part 4).
9. Putting it together
Every real protocol is a combination of the pieces above:
- Key exchange (ECDH, possibly hybrid with ML-KEM) → a shared secret, with forward secrecy.
- Signature (Ed25519, ECDSA, RSA) → proof of who took part in that exchange.
- A key derivation function (a hash, see key derivation functions) turns the shared secret into symmetric keys.
- A symmetric cipher (AES-GCM, ChaCha20-Poly1305) encrypts the actual data.
The next parts show how each protocol puts these together, and why they make different choices:
- 2. SSH: a live connection, the server proves itself with a host key, you prove yourself with your key.
- 3. OpenPGP: no live connection at all (email, files), so no Diffie–Hellman back and forth.
- 4. TLS, WireGuard, FIDO2 and Signal: four more ways to combine the same mathematics.
Check it yourself
# Python 3.8+
pow(1234, 17, 2773) # 1793 RSA encrypt
pow(1793, 157, 2773) # 1234 RSA decrypt
pow(17, -1, 2668) # 157 the private exponent
pow(19, 6, 23), pow(8, 15, 23) # (2, 2) Diffie–Hellman
Sources
- W. Diffie, M. Hellman, New Directions in Cryptography, 1976.
- R. Rivest, A. Shamir, L. Adleman, A Method for Obtaining Digital Signatures and Public-Key Cryptosystems, 1978.
- D. J. Bernstein, Curve25519: new Diffie-Hellman speed records, 2006; RFC 7748 (X25519) and RFC 8032 (Ed25519).
- NIST SP 800-57 Part 1 (key sizes), FIPS 203 (ML-KEM), FIPS 204 (ML-DSA).
- The small curve $y^2 = x^3 + 2x + 2 \bmod 17$ is a classic textbook example (Paar & Pelzl, Understanding Cryptography).