Home DSA Diffie-Hellman Key Exchange — Establishing Shared Secrets

Diffie-Hellman Key Exchange — Establishing Shared Secrets

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Cryptography → Topic 4 of 8
Learn Diffie-Hellman key exchange — how two parties establish a shared secret over a public channel.
🔥 Advanced — solid DSA foundation required
In this tutorial, you'll learn:
  • DH protocol: share p,g publicly. Each party raises g to their private exponent mod p. Shared secret = g^(ab) mod p — same from both sides.
  • Security = discrete logarithm hardness: easy to compute g^x mod p, hard to recover x.
  • Forward secrecy: ephemeral DH generates fresh key pairs per session — past sessions secure even if long-term key is later compromised.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
⚡ Quick Answer
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.

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.

diffie_hellman.py · PYTHON
12345678910111213141516171819202122232425
import random

# Using small numbers for demonstration — real DH uses 2048+ bit primes
P = 23   # prime modulus (real: 2048+ bits)
G = 5    # generator

# Alice
alice_private = random.randint(2, P-2)
alice_public  = pow(G, alice_private, P)

# Bob
bob_private = random.randint(2, P-2)
bob_public  = pow(G, bob_private, P)

# Exchange public keys over insecure channel
# Alice computes shared secret
alice_secret = pow(bob_public, alice_private, P)
# Bob computes shared secret
bob_secret   = pow(alice_public, bob_private, P)

print(f'Alice public: {alice_public}')
print(f'Bob public:   {bob_public}')
print(f'Alice secret: {alice_secret}')
print(f'Bob secret:   {bob_secret}')
print(f'Match: {alice_secret == bob_secret}')
▶ Output
Alice public: 8
Bob public: 19
Alice secret: 2
Bob secret: 2
Match: True

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.

⚠️
Use ECDH, not classic DHClassic DH requires 2048-bit parameters for security equivalent to 112-bit symmetric encryption. Elliptic curve DH (ECDH with Curve25519) achieves equivalent security with 256-bit keys — 8x smaller keys, dramatically faster. TLS 1.3 mandates ECDHE and removed static DH entirely.

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.

🎯 Key Takeaways

  • DH protocol: share p,g publicly. Each party raises g to their private exponent mod p. Shared secret = g^(ab) mod p — same from both sides.
  • Security = discrete logarithm hardness: easy to compute g^x mod p, hard to recover x.
  • Forward secrecy: ephemeral DH generates fresh key pairs per session — past sessions secure even if long-term key is later compromised.
  • Use ECDH (Curve25519) not classic DH — equivalent security with 8x smaller keys.
  • TLS 1.3 mandates ECDHE and removed all cipher suites without forward secrecy.

Interview Questions on This Topic

  • QExplain the Diffie-Hellman key exchange from scratch — what do the parties share, what do they keep private?
  • QWhat is forward secrecy and why does ephemeral DH provide it?
  • QWhat is the discrete logarithm problem and why is it hard?
  • QWhy is ECDH preferred over classic Diffie-Hellman?

Frequently Asked Questions

Does DH authenticate the parties?

No — 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. TLS solves this by authenticating the server's DH public key with a certificate signed by a trusted CA.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousRSA Algorithm — Public Key CryptographyNext →AES — Advanced Encryption Standard
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged