Diffie-Hellman Key Exchange

Two strangers, Alice and Bob, want a shared secret key. They can only talk on a channel that an eavesdropper, Eve, can hear every word of. Nothing they say to each other is private. Yet somehow they need to end the conversation holding a number. Eve, despite hearing the entire exchange, cannot feasibly compute this number. This sounds paradoxical. For centuries of cryptographic practice it was: secret keys were shared by trusted couriers, not shouted across open wires. Diffie-Hellman key exchange, published in 1976, resolved the paradox. It did so by exploiting an asymmetry between two computations in the same mathematical structure. Combining a secret exponent with a public value is cheap. Reversing that combination without knowing the secret is believed to be intractable. This asymmetry — easy one direction, hard the other — is the founding idea of public-key cryptography. Diffie-Hellman is its oldest surviving practical instance. The protocol matters because it solves the Key-Distribution Problem. It does this without any prior shared secret. It also needs no trusted third party present during the exchange. Every time a browser opens an HTTPS connection, a version of this exchange runs. This is often "ephemeral" Diffie-Hellman, or ECDHE. It runs in milliseconds to produce a session key. This enables forward secrecy — even if a server's long-term key leaks later, past sessions stay unreadable. Messaging apps, VPNs, and SSH all lean on the same mathematical trick. This article builds the protocol from the Discrete Logarithm Problem up. It gives working pseudocode. It traces a full numeric example, including the arithmetic. Critically, it also dissects the man-in-the-middle vulnerability. Plain Diffie-Hellman does not solve this vulnerability on its own. That gap is precisely why the protocol needs authentication layered on top. This foreshadows its role inside the TLS Handshake.

Key takeaways
  • Diffie-Hellman lets two parties agree on a shared secret over a public channel with no prior secret.
  • Security rests on the Discrete Logarithm Problem: exponentiation mod a prime is easy, inversion is hard.
  • Each party picks a private random exponent, exchanges a public value, and computes the same shared secret independently.
  • Anyone eavesdropping sees only public values, and recovering the secret from them is (believed) computationally infeasible.
  • Plain Diffie-Hellman gives no authentication — a man-in-the-middle can impersonate both sides undetected.
  • Real systems fix this with signed exchanges (as in the TLS Handshake) and careful Key Management of parameters.
The core insight

Two parties can compute the same number from different private inputs by exploiting an operation that is easy to do forward and believed hard to undo — that shared number becomes their secret key, even though every message they exchanged was public.

The idea

Diffie-Hellman key exchange is a protocol, not an encryption scheme: it produces a shared secret value that two parties can later use as a symmetric key, but it does not itself encrypt messages. The protocol operates in a finite cyclic group, most classically the multiplicative group of integers modulo a large prime pp, generated by an element gg of large order. Both pp and gg are public and can be reused across many sessions or standardized in advance. The security of the exchange rests on the Discrete Logarithm Problem (DLP): given gg, pp, and ga  pg^a \bmod p, finding aa is believed to require time exponential in the bit-length of pp for the best known classical algorithms, even though computing ga  pg^a \bmod p from aa takes only polynomial time via fast modular exponentiation. A closely related assumption, the Computational Diffie-Hellman (CDH) assumption, states that given ga  pg^a \bmod p and gb  pg^b \bmod p alone, computing gab  pg^{ab} \bmod p is also hard — this is the precise assumption the protocol's secrecy needs, and it is implied by (but not obviously equivalent to) hardness of the DLP itself. The clean trick is commutativity of exponentiation in the exponent: (ga)b=gab=(gb)a(g^a)^b = g^{ab} = (g^b)^a. Alice raises the public generator to her secret power aa and sends the result; Bob does the same with his secret bb. Each then raises the other party's public value to their own private exponent, and both land on gab  pg^{ab} \bmod p without either ever transmitting aa, bb, or the final shared secret directly.

How it works

The protocol has three phases: public parameter setup (which can be done once and reused), private key generation, and the exchange itself.

Setup (once, can be public and long-lived). Choose a large prime pp and a generator gg of a large-order subgroup of Zp∗\mathbb{Z}_p^*. These are published or standardized (e.g., RFC 3526 / RFC 7919 groups for classical DH, or elliptic-curve groups for ECDH).

Per-session exchange. ``` // Public, agreed in advance: prime p, generator g // --- Alice --- function ALICE_STEP1(): a <- random_integer(1, p - 2) // Alice's private key A <- mod_exp(g, a, p) // A = g^a mod p send(A) to Bob store a, A function ALICE_STEP2(B): if not VALID_PUBLIC_VALUE(B, p): // reject 1, 0, p-1, etc. abort() s <- mod_exp(B, a, p) // s = B^a mod p = g^(ab) mod p return DERIVE_KEY(s) // e.g. K = KDF(s) // --- Bob --- function BOB_STEP1(): b <- random_integer(1, p - 2) // Bob's private key B <- mod_exp(g, b, p) // B = g^b mod p send(B) to Alice store b, B function BOB_STEP2(A): if not VALID_PUBLIC_VALUE(A, p): abort() s <- mod_exp(A, b, p) // s = A^b mod p = g^(ab) mod p return DERIVE_KEY(s) // --- Fast modular exponentiation (square-and-multiply) --- function mod_exp(base, exp, mod): result <- 1 base <- base mod mod while exp > 0: if exp is odd: result <- (result base) mod mod exp <- exp >> 1 base <- (base base) mod mod return result ``` `VALID_PUBLIC_VALUE` guards against small-subgroup and degenerate values (e.g. rejecting 11, 00, or p−1p-1) — a real-world hardening step absent from the textbook description but essential in practice. `DERIVE_KEY` runs the raw shared secret ss through a key-derivation function (a hash-based KDF) rather than using ss directly as a symmetric key, since ss is not uniformly random and may leak structure. At the end, Alice computed s=Ba  p=(gb)a  p=gab  ps = B^a \bmod p = (g^b)^a \bmod p = g^{ab} \bmod p, and Bob computed s=Ab  p=(ga)b  p=gab  ps = A^b \bmod p = (g^a)^b \bmod p = g^{ab} \bmod p — the same number, derived from different private inputs, using only publicly transmitted values AA and BB.

Figure
Diffie-Hellman exchange: public channel carries only AA and BB, never aa, bb, or gabg^{ab}
Alice Bob private a (secret) A = g^a mod p p, g public / agreed private b (secret) B = g^b mod p p, g public / agreed A → (public channel) ← B (public channel) Eve sees only p, g, A, B Recovering a from A (or b from B) = solving the Discrete Log Problem — believed hard s = B^a mod p = g^(ab) mod p s = A^b mod p = g^(ab) mod p

Complexity & correctness

Time complexity. Each party performs one modular exponentiation to produce their public value and one more to produce the shared secret — two calls to `mod_exp`. Using square-and-multiply, exponentiation with exponent of bit-length nn takes O(n)O(n) modular multiplications, and each multiplication of nn-bit numbers costs O(n2)O(n^2) with schoolbook arithmetic (or O(nlog⁡n)O(n \log n) with fast multiplication), giving each party O(n3)O(n^3) total bit operations in the naive analysis, or better with optimized big-integer libraries. For pp a 2048-bit prime, this is a few modular multiplications' worth of work — milliseconds on ordinary hardware. Total protocol cost is O(1)O(1) round trips and O(n3)O(n^3) (or better) computation per side; contrast this with brute-force discrete-log attacks, which cost O(p)O(\sqrt{p}) time using Pollard's rho for generic groups, or sub-exponential time Lp[1/3]L_p[1/3] using index calculus for the multiplicative group mod pp specifically — astronomically larger than the honest computation for well-chosen parameter sizes (2048+ bits).

Space complexity. Each party stores O(n)O(n) bits: the prime pp, generator gg, one private exponent, and one received public value. No party needs to store the other's private information, and no trusted third party's state is required at all.

Correctness argument. The invariant to verify is purely algebraic and requires no probabilistic reasoning: exponentiation in Zp∗\mathbb{Z}_p^* obeys (ga)b≡gab≡(gb)a(modp)(g^a)^b \equiv g^{ab} \equiv (g^b)^a \pmod p, which follows directly from the group being abelian (multiplication mod pp commutes, so repeated multiplication — exponentiation — composes associatively and commutatively across exponents). Alice computes Ba  pB^a \bmod p where B=gb  pB = g^b \bmod p, so:

Ba≡(gb)a≡gba≡gab(modp).B^a \equiv (g^b)^a \equiv g^{ba} \equiv g^{ab} \pmod p.

Bob computes Ab  pA^b \bmod p where A=ga  pA = g^a \bmod p, so:

Ab≡(ga)b≡gab(modp).A^b \equiv (g^a)^b \equiv g^{ab} \pmod p.

Both expressions equal gab  pg^{ab} \bmod p exactly, with probability 1 — this is a deterministic algebraic identity, not a heuristic. The protocol terminates correctly on every run because modular exponentiation is a total, well-defined function on any input in Zp\mathbb{Z}_p.

Security argument (informal). Correctness (both sides land on the same value) is unconditional; secrecy is conditional on a computational assumption. An eavesdropper who sees pp, gg, A=gaA = g^a, and B=gbB = g^b but not aa or bb must compute gabg^{ab} — exactly the CDH problem. No efficient algorithm for CDH is known when pp is large and gg generates a large prime-order subgroup, so the protocol is secure against passive eavesdropping under this assumption. This is a crucial qualifier: the guarantee is computational (based on unproven hardness), not information-theoretic, and it says nothing about active attackers — the man-in-the-middle caveat discussed below.

Honest tradeoffs. Classical (finite-field) Diffie-Hellman needs large parameters (2048+ bit primes) to resist index-calculus attacks, making it slower than elliptic-curve variants (ECDH), which achieve comparable security with far smaller keys (256 bits) because no sub-exponential attack analogous to index calculus is known for well-chosen elliptic curve groups. Both variants are, as currently understood, breakable by a large-scale quantum computer running Shor's algorithm, which solves discrete log (and factoring) in polynomial time — motivating post-quantum key exchange research as a distinct, harder problem.

Worked example

Use small numbers purely for hand-tracing; real deployments use primes hundreds of digits long. Let the public parameters be:

p=23,g=5p = 23, \qquad g = 5

(55 generates a large subgroup of Z23∗\mathbb{Z}_{23}^*, which has order 22.)

StepAliceBob
1. Choose private exponenta=6a = 6b=15b = 15
2. Compute public valueA=56  23A = 5^6 \bmod 23B=515  23B = 5^{15} \bmod 23
3. Arithmetic56=156255^6 = 15625; 15625  23=815625 \bmod 23 = 8515  23=195^{15} \bmod 23 = 19 (via square-and-multiply)
4. Exchange over public channelsends A=8A = 8 to Bobsends B=19B = 19 to Alice
5. Compute shared secrets=Ba  p=196  23s = B^a \bmod p = 19^6 \bmod 23s=Ab  p=815  23s = A^b \bmod p = 8^{15} \bmod 23
6. Result196  23=219^6 \bmod 23 = 2815  23=28^{15} \bmod 23 = 2

Both parties arrive at s=2s = 2. Trace step 3 for Bob explicitly using square-and-multiply, since 15=1111215 = 1111_2:

51=5,52=25≡2,54≡22=4,58≡42=16(mod23)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}
515=58+4+2+1=58⋅54⋅52⋅51≡16⋅4⋅2⋅5(mod23)5^{15} = 5^{8+4+2+1} = 5^8 \cdot 5^4 \cdot 5^2 \cdot 5^1 \equiv 16 \cdot 4 \cdot 2 \cdot 5 \pmod{23}
16⋅4=64≡18,18⋅2=36≡13,13⋅5=65≡19(mod23)16 \cdot 4 = 64 \equiv 18, \quad 18 \cdot 2 = 36 \equiv 13, \quad 13 \cdot 5 = 65 \equiv 19 \pmod{23}

confirming B=19B = 19. An eavesdropper Eve who intercepts p=23p=23, g=5g=5, A=8A=8, B=19B=19 would need to solve 5a≡8(mod23)5^a \equiv 8 \pmod{23} for aa (or the analogous equation for bb) — trivial to brute-force here because pp is tiny (only 22 possible exponents), but this brute-forceability is exactly why toy primes are insecure: with pp a 2048-bit prime, the analogous search space makes brute force and even the best sub-exponential algorithms infeasible.

Common pitfalls & traps

PitfallWhy it happensConsequence
Treating DH as encryptionConfusing key agreement with key useNo confidentiality — DH alone sends no ciphertext, only produces a key for a separate symmetric cipher
Using raw ss as the keySkipping a KDFgab  pg^{ab} \bmod p is not uniformly random; using it directly can leak structure to a cryptanalyst
Small or reused primes/generatorsAssuming any p,gp, g is fine, or caching a "known good" small groupEnables precomputed index-calculus attacks (e.g. the real-world Logjam attack against common 512/1024-bit groups)
Not validating public valuesTrusting AA, BB blindlySmall-subgroup confinement attacks can force the shared secret into a tiny, guessable set
Assuming DH authenticates the peerConflating "shared secret" with "shared secret with the right person"Man-in-the-middle attack: Eve can run the protocol separately with each party and relay, decrypting everything
Reusing the same exponent aa across many sessions without forward secrecy designConvenience / performanceCompromise of one long-term key retroactively exposes all past sessions using that key

Pioneers & history

Origins · 1 minWhitfield Diffie and how this was discovered
WD
Whitfield Diffie
1944–present · Stanford / independent researcher, co-inventor of public-key cryptography

Diffie, working with Martin Hellman at Stanford in the mid-1970s, pursued the seemingly absurd goal of secret communication between parties who had never met and shared no prior secret. Their 1976 paper "New Directions in Cryptography" introduced the concept of public-key cryptography and the specific key-exchange protocol that bears their names, building on contributions from Ralph Merkle. The work reframed the Key-Distribution Problem as a solvable computational question rather than a purely logistical courier problem, and it is now recognized as one of the founding acts of modern cryptography — for which Diffie and Hellman received the 2015 Turing Award.

History
1976
Diffie and Hellman publish "New Directions in Cryptography," introducing public-key cryptography and the DH exchange.
1977
Rivest, Shamir, and Adleman publish RSA, the first full public-key encryption and signature scheme.
1997
British intelligence (GCHQ) declassifies earlier work by Malcolm Williamson (1974) and James Ellis showing equivalent ideas were discovered secretly years before the public paper.
2004–2015
Elliptic-curve Diffie-Hellman (ECDH) and ephemeral variants (DHE, ECDHE) become standard in TLS for forward secrecy.
2015
The Logjam attack demonstrates practical downgrade and precomputation attacks against widely reused, undersized DH groups, prompting stronger parameter standards.

Where this matters

Diffie-Hellman (and its elliptic-curve descendant ECDH) underlies session-key negotiation in the TLS Handshake used by HTTPS, securing the vast majority of web traffic. SSH uses DH-family key exchange to establish encrypted terminal sessions between clients and servers. The Signal Protocol, and by extension WhatsApp and other end-to-end encrypted messengers, layers a "triple DH" (X3DH) construction atop ECDH to bootstrap secure conversations asynchronously. IPsec VPNs negotiate tunnel keys via DH during the IKE (Internet Key Exchange) phase. In every one of these deployments, raw DH is never used alone — it is always composed with authentication (certificates, pre-shared identity keys, or signatures) precisely because of the man-in-the-middle gap, and understanding that gap is a prerequisite for understanding sound Key Management in any larger security architecture.

Ask the tutor: How does the TLS handshake use ephemeral Diffie-Hellman to achieve forward secrecy while still authenticating the server?

Does Diffie-Hellman encrypt messages directly?

No. Diffie-Hellman is strictly a key-agreement protocol: its entire output is a shared secret value, typically passed through a key-derivation function to produce a symmetric key. That key is then used with a separate symmetric cipher, such as AES, to actually encrypt application data. This division of labor is deliberate and standard in modern systems — DH (or ECDH) negotiates the key inside the TLS Handshake, while a fast symmetric algorithm handles bulk encryption afterward, since public-key operations are far more computationally expensive than symmetric ones.

If Eve records the entire exchange, why can't she compute the shared secret later?

Eve sees pp, gg, A=ga  pA = g^a \bmod p, and B=gb  pB = g^b \bmod p, but never aa or bb themselves. Computing the shared secret gab  pg^{ab} \bmod p from only AA and BB is the Computational Diffie-Hellman problem, which is at least as hard as the Discrete Logarithm Problem for well-chosen groups. For large primes (2048+ bits) or appropriately sized elliptic curves, no efficient classical algorithm is known to solve this, so recording the traffic does not let Eve retroactively compute the key — assuming the underlying hardness assumption holds and a large-scale quantum computer is not available.

What exactly is the man-in-the-middle attack against plain DH, step by step?

Eve intercepts Alice's public value AA and substitutes her own value AE=gaEA_E = g^{a_E} sent to Bob; she intercepts Bob's BB and substitutes BE=gbEB_E = g^{b_E} sent to Alice. Alice computes a shared secret with Eve (believing it's shared with Bob); Bob computes a different shared secret with Eve (believing it's shared with Alice). Eve now holds both keys, decrypting and re-encrypting every message that flows through her in real time, invisibly to both endpoints, unless the public values are cryptographically bound to verified identities.

How does TLS prevent this man-in-the-middle attack while still using Diffie-Hellman?

The TLS Handshake has the server sign its ephemeral DH public value with its long-term private key, and the client verifies that signature against a certificate chain rooted in a trusted certificate authority. Any tampering with the DH values in transit invalidates the signature, so an active attacker cannot substitute their own public value without detection, provided the client correctly validates the certificate. This combination — ephemeral DH for forward secrecy plus signatures for authentication — is exactly why raw DH is never deployed unaccompanied in production protocols.

Why do modern systems prefer elliptic-curve Diffie-Hellman (ECDH) over classical DH?

ECDH operates in the group of points on an elliptic curve rather than Zp∗\mathbb{Z}_p^*, and no sub-exponential attack comparable to index calculus is known for well-chosen curves. This means ECDH achieves comparable security to classical DH using far smaller keys — roughly 256-bit curve parameters instead of 2048-bit or larger primes — which translates into faster computation, smaller handshake messages, and lower bandwidth, all valuable for constrained devices and high-volume servers alike.

What happens to Diffie-Hellman security if a large-scale quantum computer is built?

Shor's algorithm solves the discrete logarithm problem (and integer factorization) in polynomial time on a sufficiently large, fault-tolerant quantum computer, which would let an attacker recover private exponents from public values efficiently, breaking both classical DH and ECDH. This risk motivates active research into post-quantum key exchange, such as lattice-based schemes, intended as drop-in replacements that resist both classical and quantum attackers, though this is a separate design space from the discrete-log-based protocols described here.

Why is a KDF applied to the raw DH output instead of using it as the key directly?

The raw shared secret s=gab  ps = g^{ab} \bmod p is a specific element of a mathematical group, not a uniformly random bit string, and its distribution can have subtle structure (for instance, being confined to a smaller subgroup). Feeding ss into a cryptographic key-derivation function produces a fixed-length, effectively uniform key suitable for symmetric algorithms, and also allows deriving multiple independent keys (for encryption and authentication) from a single DH exchange safely.

Before this

Where this leads