The 'Holy Grail' of network security is the ability for two parties to agree on a shared secret key without ever sending that key across the wire. If they just sent the key, an eavesdropper would have it. Diffie-Hellman (DH) solved this using the mathematical properties of modular exponentiation.
DH uses a large prime number ($p$) and a generator ($g$). Both parties agree on these publicly. Each picks a private secret ($a$ and $b$). They exchange $g^a \pmod p$ and $g^b \pmod p$. Through the magic of algebra, both can then compute $(g^a)^b \pmod p$, which equals $(g^b)^a \pmod p$. An eavesdropper seeing the public values cannot easily find $a$ or $b$ due to the Discrete Logarithm Problem.
๐ก The primary weakness of static DH is that if the private keys are ever stolen, all previous sessions can be decrypted. This is why we moved to 'Ephemeral' keys.
# Simple DH simulation (not for production!)
import random
p = 23 # Prime
g = 5 # Generator
# Alice
a_priv = random.randint(1, p-1)
a_pub = pow(g, a_priv, p)
# Bob
b_priv = random.randint(1, p-1)
b_pub = pow(g, b_priv, p)
# Shared Secret
alice_secret = pow(b_pub, a_priv, p)
bob_secret = pow(a_pub, b_priv, p)
print(f'Shared Secret: {alice_secret == bob_secret}' )While the logic above is correct, the prime $p$ in the real world must be thousands of bits long to prevent attackers from using algorithms like the Number Field Sieve to solve the logarithm.
Elliptic Curve Diffie-Hellman Ephemeral (ECDHE) is the modern standard. 'Ephemeral' means a new key pair is generated for every single session. Even if the server's long-term private key is stolen tomorrow, the attacker cannot decrypt yesterday's traffic because the session keys were never stored and were deleted from memory after the session ended.
โ ๏ธ Without PFS, a stolen server private key is a 'master key' to all historical traffic captured by an adversary (e.g., via the NSA's bulk collection).
| Algorithm | Mathematical Basis | Key Size (Typical) | PFS Support |
|---|---|---|---|
| DH | Modular Exponentiation | 2048+ bits | Only if Ephemeral (DHE) |
| ECDH | Elliptic Curves | 256 bits | Only if Ephemeral (ECDHE) |
| RSA Key Wrap | Integer Factoring | 2048+ bits | No |
TLS 1.3 has completely removed support for static RSA key exchange. It *mandates* a Diffie-Hellman based exchange (typically ECDHE) to ensure that Perfect Forward Secrecy is guaranteed for every connection.
Be wary of 'Logjam' attacks where attackers force the use of small primes (512-bit) to make the DH problem solvable.
Verify exercises to earn โ 150 XP and unlock next lab level.