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?
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?
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.
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 , 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.
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.
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.
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 and a generator . Alice picks a secret exponent , computes , and sends A publicly. Bob does the same with his secret , sending .
Alice computes . Bob computes . Both equal . The shared secret is identical, yet neither secret exponent ever crossed the channel.
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 (Chapter 5, Section 2). Alice and Bob agree on a large prime and a generator . The security comes from one asymmetry: computing is fast (repeated squaring takes microseconds even for 2048-bit primes), but given the result, recovering the exponent requires solving the discrete logarithm problem. For a 2048-bit prime, the best known algorithms need roughly operations. Use the demo below to build intuition for modular exponentiation.
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.
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.
Pick a prime, adjust the secret exponents, and watch two parties independently arrive at the same shared secret.
The small primes in the demo are intentionally breakable. Real Diffie-Hellman operates at a completely different scale.
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 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.
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 , 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 and , finding is computationally infeasible. Same trapdoor as the integer DLP, but the math runs on curve points instead of integers mod .
2048 to 4096-bit keys. Well-studied since 1976. Slower key generation and exchange. Still allowed in most protocols but losing ground.
256-bit keys. Faster key generation and exchange. Mandatory in TLS 1.3. Default for most modern protocols. Used by your browser right now.
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.
Both parties use P-256 (also called secp256r1). The curve, its base point , and its order are public standards.
Every P-256 implementation uses the same . The order is how many times you can add to itself before wrapping around.
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.
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.
Key exchange is a building block, not a complete solution. These guidelines reflect how modern protocols use it.
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.
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.
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.
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.