Diffie-Hellman Key Exchange — Logjam and DH Group Pitfalls
512-bit DH groups let attackers decrypt TLS sessions in real time via Logjam.
20+ years shipping performance-critical code where algorithms decide the bill. Written from production experience, not tutorials.
- Diffie-Hellman lets two parties agree on a shared secret over an insecure channel
- Uses modular exponentiation: both compute g^(a*b) mod p without exposing a or b
- Security = discrete log problem: recovering a from g^a mod p is infeasible for 2048+ bit primes
- Ephemeral DH (DHE/ECDHE) provides forward secrecy — past sessions safe even if long-term key leaks
- TLS 1.3 mandates ECDHE; classic DH is obsolete due to performance and attack surface
- Biggest mistake: using static DH key pairs or insufficient prime size (e.g. 512 bits)
Diffie-Hellman solves a puzzle that sounds impossible: two people who have never met, communicating over a channel where everyone can listen, agree on a secret number that nobody else can figure out. The trick uses modular exponentiation's asymmetry — mixing colours is easy, separating them is hard — to let each party combine public and private values in a way that converges to the same result without ever transmitting the secret.
Whitfield Diffie and Martin Hellman published 'New Directions in Cryptography' in 1976 — the paper that invented public key cryptography. The Diffie-Hellman key exchange protocol solves the fundamental key distribution problem: how do two parties who have never met establish a shared secret over a public channel?
The protocol is used in every TLS handshake (HTTPS), every SSH connection, every Signal message. Its security rests on the discrete logarithm problem: given g^x mod p, computing x is computationally infeasible for large p. Ephemeral Diffie-Hellman (DHE/ECDHE) in TLS provides forward secrecy — past sessions remain secure even if the server's long-term key is later compromised.
Why Diffie-Hellman Is Not Just Key Exchange
Diffie-Hellman (DH) is a cryptographic protocol that lets two parties establish a shared secret over an untrusted channel without ever transmitting the secret itself. The core mechanic: each party generates a private key, computes a public value from a shared prime p and generator g, exchanges those public values, then combines their own private key with the other's public value to arrive at the same shared secret. The security rests on the discrete logarithm problem — given g^a mod p, it's computationally infeasible to recover a when p is large enough.
In practice, DH is not encryption or authentication — it's a key agreement primitive. The shared secret is then fed into a symmetric cipher (e.g., AES) for bulk encryption. Two properties matter: perfect forward secrecy (PFS) when ephemeral keys are used (DHE), and the fact that the server's long-term key only signs the DH parameters, never encrypts them. Without PFS, compromising the server's private key decrypts all past sessions.
Use DH when you need forward secrecy — TLS 1.3 mandates ephemeral DH for this reason. Avoid static DH (fixed server key) in new systems; it offers no PFS and complicates key rotation. DH is also the foundation of protocols like SSH, IPsec, and Signal's double ratchet. The cost: two extra round trips in TLS 1.2 (mitigated in 1.3), and CPU overhead that matters at scale but is negligible per connection.
The Protocol
Public parameters: large prime p, generator g. Alice chooses private a, sends A = g^a mod p. Bob chooses private b, sends B = g^b mod p. Shared secret = A^b = B^a = g^(ab) mod p. An eavesdropper sees p, g, A, B but cannot compute g^(ab) without solving the discrete log problem.
- Both parties agree on a shared paint color (p,g) — that's public.
- Each adds their own secret color (a or b) and gets a mixed color (g^a or g^b).
- They exchange mixed colors, then each adds their secret again — final color matches (g^(ab)).
- Eavesdropper sees all mixed paints but can't separate them — that's discrete log.
The Discrete Logarithm Problem
DH security rests on: given g, p, and g^x mod p, find x. This is the discrete logarithm problem. The best classical algorithms (Index Calculus, Number Field Sieve) run in sub-exponential time — which is why 2048-bit DH parameters are needed even though AES-128 is considered equivalent security.
Note: Shor's quantum algorithm solves discrete log in polynomial time. Elliptic curve Diffie-Hellman (ECDH) suffers the same quantum vulnerability. Post-quantum key encapsulation (CRYSTALS-Kyber) is the replacement being deployed in TLS 1.3 and Signal.
Forward Secrecy
DH enables forward secrecy — a property that makes past sessions immune to future key compromise. In classic RSA key exchange, the server's RSA private key encrypts the session key. If an attacker records encrypted traffic and later obtains the RSA key, they can decrypt all past sessions.
DHE (ephemeral DH): each TLS session generates a fresh DH key pair. Even if the server's certificate key is compromised, past session keys cannot be derived — they were never stored and the ephemeral DH keys are discarded after use. TLS 1.3 mandates ephemeral key exchange (ECDHE) and removed all non-forward-secret cipher suites.
Vulnerabilities and Attacks
Basic DH is vulnerable to man-in-the-middle attacks — an attacker can intercept both parties' public keys, replace them with their own, and establish separate shared secrets with each party. This is why TLS authenticates the DH public key using a certificate signed by a trusted CA.
- Logjam: Downgrade to export-grade 512-bit DH (CVE-2015-4000).
- Weak primes: Using a composite modulus instead of prime, or a generator that doesn't generate a large subgroup.
- Static DH: Reusing the same DH key pair across sessions destroys forward secrecy and enables replay attacks.
- Parameter injection: If the server doesn't validate the received public key is not 0, 1, or p-1, the shared secret can be forced to a known value (small subgroup attack).
DH_check_pub_key() does this. Missing validation allows an attacker to force the shared secret to 1.DH_check_pub_key(). Use a safe prime (p=2q+1)Implementation Best Practices
When implementing or deploying DH:
- Parameter generation: Use well-known groups (RFC 3526) instead of generating your own prime — DH parameter generation is slow and error-prone. For ECDH, use X25519 (RFC 7748) which has built-in guard against twist attacks.
- Key validation: Always verify received public keys are not in the trivial subgroup. For classic DH, check that 1 < pub_key < p-1 and that pub_key^q mod p != 1 (where q is the subgroup order).
- Ephemeral keys: Generate fresh DH key pairs for each session. Never reuse a static DH key pair across sessions.
- TLS configuration: Prefer ECDHE cipher suites with X25519. If classic DHE is required for legacy clients, use at least 2048-bit groups (RFC 7919).
- Fallback safety: If DHE key exchange fails (e.g., no compatible parameters), fail closed — do not fall back to RSA key exchange which breaks forward secrecy.
Why Diffie-Hellman Exists — The Shared Secret Problem
Before Diffie-Hellman, cryptography had a chicken-and-egg problem. If Alice wants to send Bob an encrypted message, she needs a key. But to get that key to Bob securely, she already needs encryption. That circular dependency meant exchanging keys required face-to-face meetings or trusted couriers. That's not scalable.
Diffie-Hellman broke the deadlock. It lets two parties generate an identical secret key over a public channel without ever transmitting the key itself. Eavesdroppers see magic numbers that are useless without solving the Discrete Logarithm Problem — a trapdoor function that's computationally infeasible with sufficiently large primes.
The real genius is that the shared secret never travels across the wire. Both parties compute it independently using their private components and the other party's public value. This design makes passive interception pointless. The math ensures that even if an attacker captures every exchanged message, they cannot reconstruct the final key.
Authenticated Diffie-Hellman — The Missing Integrity Layer
Raw Diffie-Hellman has a glaring vulnerability: it's trivially vulnerable to man-in-the-middle (MITM) attacks. If Mallory intercepts Alice's public value and replaces it with her own, both Alice and Bob will negotiate separate keys with Mallory — thinking they're talking directly to each other. Mallory then decrypts, reads, re-encrypts, and forwards everything. The protocol provides confidentiality but zero authentication.
The fix is Authenticated Diffie-Hellman. Instead of exchanging bare public values, each party signs their public value with a trusted private key (e.g., from a certificate). Bob validates Alice's signature using her public certificate before generating the shared secret. If the signature fails or the certificate is revoked, abort immediately.
This is what TLS 1.3 does in its key exchange. The handshake combines Diffie-Hellman ephemeral (DHE) keys with certificate-based signatures. The result is forward secrecy (ephemeral keys) and authentication (signatures). Without both, you're building a castle on sand. Never deploy raw Diffie-Hellman without an authentication layer.
Logjam Attack: When DH Export-Grade Primes Broke TLS
- Export-grade cryptography should never be trusted — it was deliberately weakened to allow government decryption.
- Always test with tools like nmap's ssl-dh-params script to verify DH group sizes in production.
- Prefer ECDHE (X25519) over classic DHE to avoid group size debates entirely.
nmap --script ssl-dh-params -p 443 <target>openssl s_client -connect <target>:443 -cipher 'EXPORT' -tls1Key takeaways
Common mistakes to avoid
4 patternsUsing static DH key pairs across sessions
Not validating received public key (small subgroup attack)
DH_check_pub_key() in OpenSSL, or switch to X25519 which enforces validation.Using small primes (< 2048 bits) for production
Generating DH parameters on every server restart
Practice These on LeetCode
Interview Questions on This Topic
Explain the Diffie-Hellman key exchange from scratch — what do the parties share, what do they keep private?
Frequently Asked Questions
20+ years shipping performance-critical code where algorithms decide the bill. Written from production experience, not tutorials.
That's Cryptography. Mark it forged?
5 min read · try the examples if you haven't