Chapter 06 // Primitives

Key
Exchange

Chapters 1 through 5 gave you every tool needed to encrypt data with a shared key, plus the math behind what comes next. But they all assume both parties already share that key. This chapter tackles the problem that kept cryptographers stuck for decades: how do two strangers agree on a shared secret when someone is listening to every word?

Scroll to explore
01 // The Problem

You have encryption. You don't have a key.

AES-GCM from Chapter 4 gives you confidentiality and integrity in one operation. But it requires a 256-bit key that both Alice and Bob share. If they have never met, how did they get it?

The key distribution paradox

To send a secret, you need encryption. To use encryption, you need a shared secret. The obvious answer is to send the key over the channel, but the channel is insecure. Anyone listening gets the key and every future message.

This is not a theoretical concern. Every time your browser connects to a website, every time two servers communicate, every time you open a messaging app, this exact problem must be solved first. Without key exchange, symmetric encryption is useless beyond face-to-face meetings.

Why naive solutions fail

Pre-shared keys. Give every pair of users a unique key before they need to communicate. For 10 users, that is 45 keys. For 1,000 users, it is 499,500. For the internet, it is impossible. The number of keys grows as n(n1)/2n(n{-}1)/2, and distributing them securely requires solving the very problem you are trying to avoid.

Trusted couriers. Send someone with the key in a locked briefcase. This works for embassies. It does not work for a billion HTTPS connections per second. Physical delivery is slow, expensive, and does not scale.

Trusted third party. A central server that knows every key and relays them to the right users. This works until the server is compromised, and then every key is exposed at once. It is a single point of failure for the entire system.

This was an open problem for decades. Cryptographers assumed that sharing a secret required a pre-existing secure channel. In 1976, Whitfield Diffie and Martin Hellman published a paper that changed everything: a way for two parties to create a shared secret over a completely public channel.

02 // The Breakthrough

Agreeing on a secret in public

The Diffie-Hellman key exchange lets two people create a shared secret while an eavesdropper watches every message. The core idea is surprisingly simple, and a paint-mixing analogy makes it click.

The paint-mixing analogy
Common color
Public. Everyone can see it.
Alice
Secret
+
Common
=
Mix
Bob
Secret
+
Common
=
Mix
Alice's mix
public channel
Bob's mix
Bob's mix
+
Her secret
=
Shared secret
Alice's mix
+
His secret
=
Shared secret
Both arrive at the same color
Eve's problem
Eve sees:
but not the secret colors

Eve sees the common color and both mixtures. But separating a mixture back into its components is practically impossible. She cannot recover either secret color, and without a secret color she cannot produce the shared secret.

From paint to math

Now replace colors with numbers and mixing with a math operation called modular exponentiation (explained in the next section). Alice and Bob agree on a large prime p\color{#e8e8ed}p and a generator g\color{#e8e8ed}g. Alice picks a secret exponent a\color{#8b5cf6}a, computes A=gamodp\color{#8b5cf6}A = g^a \bmod p, and sends A publicly. Bob does the same with his secret b\color{#f59e0b}b, sending B=gbmodp\color{#f59e0b}B = g^b \bmod p.

Alice computes Bamodp\color{#00e5a0}B^a \bmod p. Bob computes Abmodp\color{#00e5a0}A^b \bmod p. Both equal gabmodp\color{#00e5a0}g^{ab} \bmod p. The shared secret is identical, yet neither secret exponent ever crossed the channel.

03 // The Math Behind It

From algebra to a trapdoor

Chapter 5 built the algebra that Diffie-Hellman runs on: the multiplicative group, generators, and finite fields. Here is the one property that turns that algebra into a secure protocol.

Diffie-Hellman works inside the multiplicative group Zp\mathbb{Z}_p^* (Chapter 5, Section 2). Alice and Bob agree on a large prime pp and a generator gg. The security comes from one asymmetry: computing gamodpg^a \bmod p is fast (repeated squaring takes microseconds even for 2048-bit primes), but given the result, recovering the exponent aa requires solving the discrete logarithm problem. For a 2048-bit prime, the best known algorithms need roughly 21122^{112} operations. Use the demo below to build intuition for modular exponentiation.

Modular Arithmetic Explorer

Numbers 1 through 22 are arranged on a clock. Each step computes the next power of the generator g. Watch how the powers visit every position before cycling back to 1.

0/22 powers
12345678910111213141516171819202122g = 5mod 23
04 // Try It

Key exchange with small numbers

Watch Diffie-Hellman happen step by step with numbers small enough to follow by hand. Adjust the private exponents, change the prime, and see how Alice and Bob always arrive at the same shared secret while Eve is left in the dark.

Diffie-Hellman Key Exchange

Pick a prime, adjust the secret exponents, and watch two parties independently arrive at the same shared secret.

Public parameters (visible to everyone)
p = 23g = 5
Alice
6
Public value (A)
8
56mod23=85^{6} \bmod 23 = 8
Alice computes shared secret
2
B6mod23=196mod23=2B^{6} \bmod 23 = 19^{6} \bmod 23 = 2
Bob
15
Public value (B)
19
515mod23=195^{15} \bmod 23 = 19
Bob computes shared secret
2
A15mod23=815mod23=2A^{15} \bmod 23 = 8^{15} \bmod 23 = 2
Shared secret (both sides match)
2
gabmodp=56×15mod23g^{ab} \bmod p = 5^{6 \times 15} \bmod 23
Eve's view
👁
Eve sees (public)
g = 5, p = 23, A = 8, B = 19
Eve needs (private)
a = ?, b = ?🔒
Brute force difficulty
Eve must try up to 21 exponents to find a or b (for p = 23).
For a 2048-bit prime, Eve would need ~21122^{112} operations. All the computers on Earth could not finish in a human lifetime.
05 // Parameter Sizing

From toy numbers to real security

The small primes in the demo are intentionally breakable. Real Diffie-Hellman operates at a completely different scale.

Real-world parameters

The small primes in the demo above (23, 47, 97) are intentionally tiny. An attacker could brute-force the discrete log for those in microseconds. Real Diffie-Hellman uses primes of 2048 bits or more. That is a number with over 600 decimal digits.

NIST recommends 2048-bit primes for 112-bit security (meaning an attacker would need roughly 21122^{112} operations to break it, far beyond any computer) and 3072-bit primes for 128-bit security. The private exponents must also be large enough to prevent attacks that exploit small exponent spaces.

This is the first time in this course that security depends on a computational hardness assumption. AES resists attacks because of the structure of the cipher itself. Diffie-Hellman is secure only because the discrete logarithm problem is believed to be hard. If someone finds a fast algorithm for discrete logs, the protocol breaks completely. This distinction matters when we discuss quantum computing in Chapter 12.

06 // Modern Key Exchange

ECDH: smaller keys, same security

Elliptic Curve Diffie-Hellman performs the same protocol as classic DH, but over an elliptic curve. Walk through key generation step by step: pick a scalar, compute a public point, and derive a shared secret.

Chapter 5 introduced elliptic curves: the equation y2=x3+ax+by^2 = x^3 + ax + b, point addition, scalar multiplication, and how these curves work over finite fields. The key insight for key exchange is the Elliptic Curve Discrete Logarithm Problem: given a base point GG and Q=kGQ = kG, finding kk is computationally infeasible. Same trapdoor as the integer DLP, but the math runs on curve points instead of integers mod pp.

🔢

Classic DH

2048 to 4096-bit keys. Well-studied since 1976. Slower key generation and exchange. Still allowed in most protocols but losing ground.

2048-bit key = ~112-bit security

ECDH (P-256)

256-bit keys. Faster key generation and exchange. Mandatory in TLS 1.3. Default for most modern protocols. Used by your browser right now.

256-bit key = ~128-bit security

ECDH Step by Step

Generate real key pairs on the P-256 curve, exchange public keys, and derive a shared secret. The same algorithm your browser uses for HTTPS.

1
Agree on a curve

Both parties use P-256 (also called secp256r1). The curve, its base point GG, and its order nn are public standards.

Base point G (x)
6b17d1f2e12c…3945d898c296
Base point G (y)
4fe342e2fe1a…406837bf51f5

Every P-256 implementation uses the same GG. The order n2256n \approx 2^{256} is how many times you can add GG to itself before wrapping around.

2
Alice's private key
3
Alice's public key
4
Bob's key pair
07 // The Attack

The man in the middle

Diffie-Hellman is mathematically sound. But it has a fundamental weakness: it tells you nothing about who you are exchanging keys with. An attacker who can intercept messages can silently hijack the entire conversation.

How the attack works

Mallory (the name cryptographers use for an active attacker, as opposed to Eve who only eavesdrops) sits between Alice and Bob on the network. When Alice sends her public value, Mallory intercepts it and substitutes her own. She does the same to Bob. Now Mallory has a shared secret with Alice (who thinks she is talking to Bob) and a different shared secret with Bob (who thinks he is talking to Alice).

When Alice sends an encrypted message, Mallory decrypts it with her Alice-side key, reads or modifies it, re-encrypts it with her Bob-side key, and forwards it. Bob receives a valid encrypted message and has no way to detect the interception. The math is correct on every leg. The problem is that the math does not prove identity.

Key exchange without authentication is fundamentally broken. Diffie-Hellman gives you a shared secret, but it cannot tell you who holds the other half. Fixing this requires something from Chapter 7: public-key cryptography and digital signatures, which let you verify the identity of the other party before trusting the exchanged key.

08 // Best Practices

Using key exchange correctly

Key exchange is a building block, not a complete solution. These guidelines reflect how modern protocols use it.

🔑

Use ECDH, Not Classic DH

P-256 or X25519 give you equivalent security with far smaller keys. TLS 1.3 mandates ECDH. Classic finite-field DH requires 2048+ bit parameters for the same level of protection.

♻️

Always Use Ephemeral Keys

Generate a fresh key pair for every session and discard it afterward. Ephemeral keys provide forward secrecy: compromising a long-term key does not expose past sessions.

🛡️

Never Skip Authentication

Key exchange without authentication is vulnerable to man-in-the-middle attacks. Always pair ECDH with digital signatures or certificates to verify the identity of the other party.

Validate Public Keys

Before using a received public key, verify that it is a valid point on the expected curve. Skipping this check can let an attacker send a crafted key that leaks your private key through the math of the exchange.

The common thread: key exchange is never used alone. In every real-world protocol, it is combined with authentication (to prevent MITM), key derivation (to produce multiple keys from one shared secret), and ephemeral keys (for forward secrecy). The protocol does the hard work so you do not have to compose these pieces manually.

09 // What You Learned

From shared secrets to public keys

This chapter introduced the first protocol primitive: a way to create shared secrets from nothing. It also revealed why that is not enough on its own.

The story so far

The key distribution problem was the missing piece in symmetric cryptography. Diffie-Hellman solved it: two parties can derive a shared secret over a public channel using modular exponentiation and the hardness of the discrete logarithm problem.

ECDH modernized the idea with elliptic curves, achieving the same security with smaller keys and faster computation. TLS 1.3 uses ephemeral ECDH for every HTTPS connection, providing forward secrecy by discarding keys after each session.

The man-in-the-middle attack showed that key exchange without authentication is dangerously incomplete. Mallory can transparently hijack the conversation because Diffie-Hellman proves nothing about identity.

Closing the identity gap requires a different kind of cryptography. Instead of a shared secret, each party needs a public key that anyone can see and a private key that only they hold. That is asymmetric encryption, the subject of Chapter 7. Combined with digital signatures (also Chapter 7), it gives us the tools to authenticate key exchanges and build the secure channels the modern internet depends on.

Up Next

Chapter 07 // Public-Key Cryptography

Continue Learning