Luke a Pro

Luke Sun

Developer & Marketer

đŸ‡ș🇩

Diffie-Hellman Key Exchange

| , 4 minutes reading.

Diffie-Hellman Key Exchange

Introduction: The “Mixing Colors” Analogy

Alice and Bob want to agree on a secret color without Eve (the spy) knowing it.

  1. They agree on a Public Color (Yellow). Eve knows this.
  2. Alice picks a Secret Color (Red) and mixes it with Yellow to get Orange. She sends Orange to Bob.
  3. Bob picks a Secret Color (Blue) and mixes it with Yellow to get Green. He sends Green to Alice.
  4. Eve sees Orange and Green, but she can’t easily “un-mix” them to find Red or Blue.
  5. The Magic: Alice adds her Secret Red to Bob’s Green. Bob adds his Secret Blue to Alice’s Orange.
  6. Both now have the exact same result (Brown)! Eve is left with nothing.

Diffie-Hellman (DH) uses modular arithmetic to perform this “mixing” mathematically.

What Problem does it solve?

  • Secure Handshake: Allowing two parties to establish a shared secret key (for AES) over a public, monitored internet connection.
  • The Promise: Perfect Forward Secrecy. Even if a hacker steals the server’s long-term private key later, they can’t decrypt past conversations.

How it Works (The Math)

  1. Pick a large prime pp and a generator gg. (Public).
  2. Alice picks secret aa, sends A=ga(modp)A = g^a \pmod p to Bob.
  3. Bob picks secret bb, sends B=gb(modp)B = g^b \pmod p to Alice.
  4. Alice calculates S=Ba(modp)S = B^a \pmod p.
  5. Bob calculates S=Ab(modp)S = A^b \pmod p.
  6. Since (gb)a=(ga)b(g^b)^a = (g^a)^b, they both have the same secret SS.

Typical Business Scenarios

  • ✅ HTTPS / TLS 1.3: This is the primary method used to establish the “Session Key” when you visit a website.

  • ✅ End-to-End Encryption: WhatsApp and Signal use DH variants (like X3DH) to ensure only the sender and receiver can read messages.

  • ✅ VPNs: Establishing secure tunnels between offices.

  • ❌ Authentication: DH by itself does not prove identity. Eve could sit in the middle (Man-in-the-Middle) and pretend to be Bob to Alice, and Alice to Bob. You must combine DH with Digital Signatures to be safe.

Performance & Complexity

  • Speed: Fast, but involves large number exponentiation (see Chapter 7.1).
  • Variants: ECDH (Elliptic Curve Diffie-Hellman) is the modern version that uses smaller keys for the same security.

Summary

"Diffie-Hellman is the 'Magic Mirror' of the internet. It allows two people to look into the mirror and see the same secret, while a spy looking over their shoulder sees only gibberish."