Skip to content
CryptographyInternals

Diffie-Hellman Key Exchange Example, Step by Step

A Diffie-Hellman key exchange example with real numbers: p = 23, g = 5, secrets 6 and 15, shared key 2. See how it works and why Eve can't follow at 2048 bits.

Published on 9 min read

Diffie-Hellman lets two people who have never met agree on a secret number over a channel that everyone can read. Each side keeps a private number, publishes a value derived from it, and combines the other side's public value with its own secret. Both land on the same result, while an eavesdropper who copied every message cannot. With the textbook numbers p = 23 and g = 5, Alice's secret 6 and Bob's secret 15 produce the shared key 2. The rest of this post walks through that example one multiplication at a time, then scales it up to the 2048-bit and elliptic-curve sizes that protect real traffic.

The paint analogy, in two sentences

Alice and Bob each start from the same public pot of yellow paint, stir in a secret color of their own, and swap the mixtures in plain view. Each then adds their own secret color to the mixture they received, and both end up with the same brown, which an observer cannot recreate because unmixing paint is hard.

That is the whole idea. The math below replaces "mixing" with exponentiation and "unmixing is hard" with the discrete logarithm problem.

A complete worked example with small numbers

Everyone, including the eavesdropper Eve, knows two public parameters:

  • the prime p = 23
  • the generator g = 5

Step 1: each side picks a secret

Alice picks a = 6. Bob picks b = 15. Neither number is ever sent.

Step 2: each side publishes a public value

Alice computes A = 5^6 mod 23. In full, 5^6 = 15625, and 15625 = 23 × 679 + 8, so A = 8.

Bob computes B = 5^15 mod 23. 5^15 = 30517578125, which leaves remainder B = 19 when divided by 23.

Alice sends 8. Bob sends 19. Eve sees both.

Step 3: each side combines

Alice raises Bob's value to her secret: 19^6 mod 23. Bob raises Alice's value to his: 8^15 mod 23. Real implementations never compute the giant power first; they reduce after every multiplication (square and multiply):

Alice: 19^6 mod 23
  19^2 = 361  -> 361 mod 23 = 16
  19^4 = 16^2 = 256 -> 256 mod 23 = 3
  19^6 = 19^4 * 19^2 = 3 * 16 = 48 -> 48 mod 23 = 2

Bob: 8^15 mod 23   (15 = 8 + 4 + 2 + 1)
  8^2 = 64  -> 18
  8^4 = 18^2 = 324 -> 2
  8^8 = 2^2 = 4
  8^15 = 4 * 2 * 18 * 8 = 1152 -> 1152 mod 23 = 2

Both get 2. That is the shared secret.

Why both answers match

Alice computed (g^b)^a and Bob computed (g^a)^b. Both are g^(ab) = 5^90 mod 23. Exponents can be reduced mod p - 1 = 22 here, and 90 mod 22 = 2, so the secret is 5^2 = 25, which is 2 on a 23-hour clock. The order of the exponents does not matter, which is exactly the property the protocol relies on.

Who knows what

ValueAliceBobEve (listening)
p = 23, g = 5yesyesyes
a = 6yesnono
b = 15noyesno
A = 8yesyesyes
B = 19yesyesyes
Shared secret = 2yesyesno

Eve holds every public value but neither secret exponent, and the table shows the gap she would have to close.

Clock arithmetic: what "mod p" means

"mod 23" means you work on a clock with 23 positions, numbered 0 to 22. Any number wraps around: 25 o'clock is 2 o'clock, 48 is 2 as well, and 15625 lands on 8 after going around the dial 679 times. You only ever keep the remainder.

This has two consequences. Numbers never grow: however large the exponent, every intermediate result fits on the dial, which is why a laptop can handle 2048-bit exponents in milliseconds. And the wrap-around destroys order: knowing that the result is 8 tells you nothing about how many laps the hand took to get there.

Why the powers of 5 jump around

Here are all the powers of 5 on the 23-hour clock:

k1234567891011
5^k mod 2352104208171611922
k1213141516171819202122
5^k mod 23182113193156712141

Two things stand out. First, the sequence has no visible pattern: 5, 2, 10, 4, 20, 8, 17... Neighboring exponents land far apart. Second, every non-zero residue from 1 to 22 appears exactly once before the cycle restarts at 5^22 = 1. That makes 5 a generator of the group: its powers reach every possible value, so a secret exponent can map to any public value. (Not every base does this; modulo 23 the generators are 5, 7, 10, 11, 14, 15, 17, 19, 20 and 21.)

You can watch this hopping on our interactive Diffie-Hellman page, where the powers of 5 travel around a 23-hour clock before the page runs a real 2048-bit exchange in your browser.

The discrete logarithm: Eve's problem

Eve sees A = 8 and wants a such that 5^a mod 23 = 8. That is the discrete logarithm problem. At this size she just reads the table above: 8 sits under k = 6. Even without a table she tries at most 22 exponents. (Any exponent congruent to 6 mod 22 works too, such as 28 or 50, but they all give the same key.)

Forward is easy, backward is hard: computing 5^a takes a handful of squarings, while inverting it has no known shortcut on classical computers beyond very sophisticated sieving algorithms. At 23 that asymmetry is invisible. At real sizes it is everything.

Real sizes

A standard finite-field group, used in TLS and SSH before elliptic curves took over, is RFC 3526 group 14: a 2048-bit safe prime with generator 2. Written in decimal, that prime has 617 digits. Its hexadecimal form starts and ends with sixteen F's, and in decimal it begins 32317006071311007300.

  • Alice's work: roughly 2048 squarings and some multiplications, done in milliseconds.
  • Eve's work: the best known attack, the number field sieve, needs around 2^112 operations against a 2048-bit group. That is about 5.2 × 10^33 operations.

To get a feel for how that differs from guessing, compare with how long brute force takes against keys of different sizes.

Modern TLS mostly uses the elliptic-curve variant, X25519. Same protocol, different group: points on a curve instead of numbers on a clock. Because no sieve-style attack is known for well-chosen curves, it reaches about 128-bit security with 256-bit numbers, eight times smaller than the 2048-bit prime for a stronger margin.

Forward secrecy: throw the secrets away

In TLS 1.3, both sides generate fresh secrets a and b for every connection and delete them when it ends. This is called ephemeral Diffie-Hellman, and it gives forward secrecy: if an attacker records today's traffic and steals the server's long-term key next year, that key does not unlock past sessions, because it was never used to derive them. The secrets that did are gone.

This is a major difference from older RSA key transport, where the client encrypted the session key with the server's RSA public key. Steal that RSA private key and every recorded session encrypted to it opens.

Man in the middle: why TLS signs the exchange

Plain Diffie-Hellman proves you share a secret with someone, not with whom. An active attacker, Mallory, can sit between Alice and Bob:

  1. Alice sends A. Mallory intercepts it and sends Bob her own value M.
  2. Bob sends B. Mallory intercepts it and sends Alice M as well.
  3. Alice now shares a key with Mallory, and so does Bob. Mallory decrypts, reads and re-encrypts everything.

Neither side notices, because the math works perfectly; it just works with the wrong party. TLS prevents this by having the server sign the handshake, including its Diffie-Hellman share, with the private key that matches its certificate. The browser checks the signature against the certificate chain. Mallory can substitute her own value, but she cannot produce a valid signature for the real server's name.

Key exchange gives secrecy; signatures give identity. TLS needs both.

The post-quantum move

Diffie-Hellman's security rests on the discrete logarithm being hard. A large enough quantum computer running Shor's algorithm would solve it efficiently, for both the finite-field and elliptic-curve versions. Such a machine does not exist today, but traffic recorded now could be decrypted later, which is why the migration started early.

The response is ML-KEM, a lattice-based key encapsulation mechanism standardized by NIST as FIPS 203 in 2024. TLS deployments now combine it with X25519 in a hybrid key exchange: both run during the handshake and their outputs are combined. An attacker must break both to recover the key, so the connection stays at least as secure as X25519 alone even if a flaw turns up in the newer algorithm.

Summary

Toy exampleRFC 3526 group 14X25519
Groupnumbers mod 23numbers mod a 2048-bit primepoints on Curve25519
Size2 digits617 digits256-bit numbers
Eve's best attackread a 22-entry tableabout 2^112 operationsabout 2^128 operations

The protocol never changes: agree on public parameters, raise to a secret, swap, raise again. Only the size of the clock does.

Try it yourself

Reading numbers is one thing; watching them move is another. On the Diffie-Hellman interactive page you can step through this exact exchange with p = 23 and g = 5, see what Eve is left with, then generate a genuine 2048-bit shared secret in your browser. For the rest of the toolkit (AES, SHA-256, RSA and brute-force timing), start from the modern cryptography overview.

Related articles

How AES encryption works, step by step: we follow one real 16-byte block through key expansion and all 10 rounds of AES-128, with every hex value shown.
How SHA-256 works, step by step: we hash "Hello, world!" by hand, from padding and message schedule to one real round and the final 256-bit digest.
A full RSA example with small numbers: p = 61, q = 53, e = 17, d = 2753. Encrypt 65 to 2790 and back, with every step of the math shown and checked.