Use Diffie-Hellman key exchange
Diffie-Hellman allows two parties to establish a shared secret over an insecure channel without ever transmitting the secret itself. The foundation of TLS key exchange.
- 1
Diffie-Hellman works in a cyclic group: both parties agree on a generator g and prime p. Each picks a secret random exponent (a, b), sends g^a and g^b publicly, and computes (g^b)^a = (g^a)^b = g^(ab) as the shared secret. An eavesdropper sees g, p, g^a, g^b but cannot compute g^(ab) without solving the discrete logarithm problem.
- 2 Prime Generator →
Generate a safe prime p (p = 2q + 1 where q is also prime). For DH, use a 2048-bit or larger prime. The prime must be shared and public — it can be a well-known group (RFC 7919) or generated fresh.
- 3 Modular Exponentiation →
Compute g^a mod p where a is your secret random exponent. Send the result to the other party. Receive their g^b mod p and compute (g^b)^a mod p to get the shared secret.
- 4
Use ECDH (Elliptic Curve Diffie-Hellman) instead of classic DH — it is faster and uses smaller keys for equivalent security. P-256 (NIST) or Curve25519 are standard choices. Always use ephemeral keys (DHE/ECDHE) for forward secrecy in TLS.
Frequently asked questions
- What is forward secrecy?
- Each session uses a fresh ephemeral key pair that is discarded after the session. If the long-term key is later compromised, past session keys cannot be recovered because the ephemeral keys no longer exist. TLS 1.3 mandates forward secrecy.
- DH vs ECDH?
- ECDH uses elliptic curve groups instead of multiplicative groups modulo a prime. It achieves the same security with much smaller keys (256-bit curve ≈ 3072-bit DH), making it faster and more efficient. Use ECDH with Curve25519 or P-256.
Learn more
Want to understand why?