Diffie-Hellman Key Exchange in Pictures
Follow a worked example showing how two parties build a shared secret over a public channel, and why eavesdroppers cannot rebuild it.
Key takeaways
- Two parties can derive an identical secret by exchanging only public values.
- Security rests on a calculation that is easy to do forward and believed to be impractical to reverse at proper sizes.
- The exchange by itself does not prove who is on the other end, so it must be paired with authentication.
- Using fresh private values for each session gives forward secrecy for past traffic.
- Modern systems mostly use elliptic-curve versions and are adding quantum-resistant methods alongside them.
Diffie-Hellman key exchange lets two parties who have never shared a secret create one while someone listens to every message. Each side picks a private number, sends a public value computed from it and combines the other side's public value with its own private number. Both arrive at the same result, which never crosses the network.
Whitfield Diffie and Martin Hellman published the idea in 1976, building on work that included Ralph Merkle's. Variations of it protect web connections, encrypted messaging, VPNs and remote logins today.
The paint mixing picture
A popular analogy uses paint. Mixing colors is easy; separating a mixture back into its ingredients is very hard.
- Alice and Bob openly agree on a common color, say yellow.
- Each chooses a secret color. Alice picks red; Bob picks blue.
- Alice mixes yellow with red and sends the result. Bob mixes yellow with blue and sends his.
- Alice adds her secret red to Bob's mixture. Bob adds his secret blue to Alice's mixture.
- Both now hold yellow plus red plus blue.
An observer sees yellow and the two mixtures. Combining the two mixtures would include too much yellow and still not reproduce the final shade. The math version replaces paint with exponentiation in modular arithmetic.
The math, with tiny numbers
You need one operation: modulo, the remainder after division. For example, 17 mod 5 is 2.
The parties agree on a prime number p and a base g. We'll use p = 23 and g = 5. These are public.
Alice picks a private number a = 6. She computes:
A = g^a mod p = 5^6 mod 23 = 15625 mod 23 = 8 Bob picks a private number b = 15. He computes:
B = g^b mod p = 5^15 mod 23 = 19 Alice sends 8. Bob sends 19. Now each raises the value received to their own private number:
Alice: B^a mod p = 19^6 mod 23 = 2
Bob: A^b mod p = 8^15 mod 23 = 2 Both get 2. That is the shared secret.
Why they match
Alice computed (g to the b) to the a. Bob computed (g to the a) to the b. Both equal g raised to a times b, and the order of multiplication doesn't matter. The modulo operation preserves this.
Why an eavesdropper is stuck
The observer knows p, g, A and B. To compute the secret, they'd need a or b. Finding a from 5^a mod 23 = 8 is called the discrete logarithm problem.
With numbers this small, you can simply try every exponent. With real parameters, a prime of 2048 bits or more, or a well-chosen elliptic curve, no known conventional method finishes in practical time. Ordinary logarithms don't help because the modulo operation makes the outputs jump around without a useful pattern.
Parameter choice matters. A weak or badly formed prime, or a poor random number generator for the private values, can undermine everything. This is why software relies on standardized groups, such as those listed in RFC 7919 for TLS, and on well-tested curves.
Trying to break the example
Put yourself in the observer's seat. You have p = 23, g = 5, A = 8 and B = 19. The natural approach is to walk through exponents until one produces Alice's public value:
5^1 mod 23 = 5
5^2 mod 23 = 2
5^3 mod 23 = 10
5^4 mod 23 = 4
5^5 mod 23 = 20
5^6 mod 23 = 8 <- found a = 6 Six tries, then you compute 19^6 mod 23 = 2 and you have the secret. Notice that the outputs 5, 2, 10, 4, 20, 8 give no hint of how close you are. There is no "warmer" or "colder."
With a tiny modulus the search is trivial. As the numbers grow, the count of possible exponents grows astronomically. Better algorithms than simple trial exist, which explains why a classic finite-field prime has to be thousands of bits long, while elliptic curves, against which the best known conventional attacks are much weaker, manage with far smaller values.
Meanwhile the honest parties' work stays cheap. Raising a number to a huge power doesn't require that many multiplications: software repeatedly squares and reduces, so the effort grows with the number of bits in the exponent and not with its size. That gap between the owner's work and the attacker's is what the method depends on.
What it doesn't do: authentication
Diffie-Hellman gives you a shared secret with someone. It doesn't say who. An attacker who can intercept and replace messages could run one exchange with Alice and another with Bob, sitting in the middle and relaying translated traffic. Both victims would believe they had a private channel.
Real protocols close this hole by authenticating the public values:
- A server signs the handshake with the key from its certificate, as explained in digital signatures.
- SSH clients check the server's host key against a remembered fingerprint.
- Messaging apps let users compare safety numbers, covered in end-to-end encryption in messaging.
- Some VPN setups configure each peer's public key in advance.
Ephemeral exchanges and forward secrecy
If each side generates new private numbers for every session and deletes them afterward, the method is called ephemeral Diffie-Hellman, often abbreviated DHE or ECDHE. Suppose someone records your encrypted traffic today and later steals the server's long-term private key. Because that key only signed the handshake and the temporary values are gone, the old sessions stay closed. This property is forward secrecy.
TLS 1.3 (RFC 8446) requires an ephemeral exchange for new full handshakes that don't rely only on a pre-shared key. Our step-by-step handshake guide shows where the public values travel.
From numbers to curves
Elliptic-curve Diffie-Hellman replaces modular exponentiation with repeated addition of points on a curve. The shape of the exchange is identical: a public starting point, private multipliers, public results and a matching shared point. The advantage is size. A popular choice, X25519 (RFC 7748), uses public keys of just 32 bytes, far smaller than a 2048-bit classic value, with less computation.
The raw shared value isn't used directly as an encryption key. Protocols pass it through a key derivation function, along with details of the conversation, to produce separate keys for each direction and purpose. Those keys then drive a fast cipher, the hybrid pattern described in symmetric vs. public-key encryption.
Common ways implementations go wrong
The idea is short enough to fit on a napkin, which tempts people to code it themselves. The pitfalls are less obvious:
- Predictable private values. If the random number generator is weak, an observer may guess the secret without solving any hard problem.
- Small or outdated groups. Short primes offer little protection, and some old protocols could be pushed toward weak options. Current software disables them.
- Unchecked public values. Receivers need to reject malformed or degenerate values that would force the shared result into a tiny set. Standards describe the checks.
- Skipping authentication. Anonymous exchanges encrypt traffic but can't detect an intermediary.
- Reusing temporary values. Keeping the same "ephemeral" number for a long time erodes forward secrecy.
- Leaking through timing. Code whose running time depends on secret bits can reveal them, so good libraries use constant-time operations.
A maintained cryptographic library handles these for you. If you're reviewing a product, look for standard protocols such as TLS, SSH or a documented messaging protocol instead of a custom exchange.
Where you meet it
- HTTPS: nearly every modern browser connection uses an ephemeral elliptic-curve exchange.
- VPNs: IPsec's key exchange and WireGuard both build on Diffie-Hellman. See WireGuard vs. OpenVPN vs. IPsec.
- SSH: the session keys come from a key exchange at connection time.
- Messaging: ratcheting protocols repeat the exchange as conversations proceed.
If you manage a server, you rarely implement this yourself. Your job is to keep the TLS library current, prefer modern settings and disable obsolete options.
The quantum question
A sufficiently large, error-corrected quantum computer running Shor's algorithm could solve discrete logarithms, including the elliptic-curve version. No such machine is publicly known to exist, but recorded traffic could be decrypted later if one arrives. Many browsers and services have begun pairing X25519 with a lattice-based method called ML-KEM, so that an attacker would need to break both. The article on post-quantum cryptography explains how the replacements differ.
Common questions
Is the shared secret ever sent?
No. Only the public values travel. Each side computes the secret locally.
Is Diffie-Hellman encryption?
It is key agreement. It produces material for keys, and a separate cipher does the encrypting.
Can more than two parties use it?
Yes, extensions let groups derive a common key, though practical group messaging protocols use more elaborate structures to handle members joining and leaving.
Can I try it myself?
Yes. Pick a small prime and base, choose two private numbers and compute the four results with any calculator that has a modulo function. For anything real, use an established library, never hand-rolled arithmetic.