SECURITY ENGINEERING · PART 4 · CRYPTOGRAPHY IN PRACTICE · KEYS · 50 OF 229

Diffie-Hellman Key Exchange and Forward Secrecy

How two computers agree on a secret key over a network an attacker is recording: the Diffie-Hellman idea in plain words, the modern X25519 version with real output (both sides derive the same 32 bytes in 0.04 ms), why the exchange must be authenticated to stop a man in the middle, what forward secrecy means, and how a key derivation function turns the result into session keys.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Public values cross, private stay
  • both derive one secret
  • sign it to stop a man in the middle
  • ephemeral keys

Notes

The setting

The setting: a client and a server want one shared key for AES, and an attacker can read everything between them. One option from the last episode is to encrypt the key with the server's public key. That works, but it has a serious weakness. If the server's private key is stolen a year later, the attacker can go back and decrypt every conversation they recorded. Key exchange gives us a better way.

The problem to solve
  • client and server want one shared AES key
  • the attacker sees every byte that crosses the network
  • encrypting the key with a long-term public key works, but if that private key leaks later, all recorded traffic can be decrypted

The idea

The idea is often explained with paint. Both sides agree on a public colour. Each secretly picks a private colour, mixes it with the public one, and sends the mixture across. Then each adds their own private colour to the mixture they received. Both end with the same final colour, because it contains the same three ingredients. A watcher saw only the two mixtures, and separating mixed paint is not practical. In the real thing, the mixing is mathematics.

The paint analogy
  • both agree on a public colour
  • each adds a private colour and sends the mix across each adds their own private colour to what they received
  • both now hold the same final colour
  • a watcher saw only the two mixes, and cannot unmix

In real terms

In real terms: the client picks a random private value and sends the matching public value. The server does the same. Then the client combines its own private value with the server's public one, and the server combines its private value with the client's public one. The mathematics guarantees both get the same result. The attacker has both public values, but computing the secret from those alone is a problem nobody knows how to solve at these sizes.

The exchange
  • client: random private a, sends public A server: random private b, sends public B
  • client computes from a and B
  • server computes from b and A both get the same secret
  • attacker has A and B only; finding the secret from them is not feasible

X25519

The modern version is X two five five one nine, Diffie-Hellman on an elliptic curve. Here it is, run. Each side generates a private key. Each calls exchange with the other side's public key. The two results are equal, and thirty two bytes long. Each exchange took thirty six thousandths of a millisecond, and the public values are only thirty two bytes each. This is what your browser does at the start of almost every HTTPS connection today.

run it
a = X25519PrivateKey.generate()
b = X25519PrivateKey.generate()
s1 = a.exchange(b.public_key())
s2 = b.exchange(a.public_key())
s1 == s2, len(s1)
# (True, 32)

# 0.036 ms per exchange
# public values: 32 bytes each

Key derivation

The raw shared secret is not used as a key directly. It is passed through a key derivation function, usually HKDF, which turns it into clean, uniformly random keys. One secret can produce several keys by using different labels: one for client to server, one for server to client. TLS 1.3 does exactly this. Deriving separate keys for separate purposes is a habit worth copying in your own designs.

HKDF
key = HKDF(hashes.SHA256(),
    length=32, salt=None,
    info=b"handshake data"
).derive(shared_secret)
# a 32-byte AES key

# one secret gives many keys:
# client-to-server, server-to-
# client, each with its own label

Man in the middle

Here is what key exchange does not do. It does not tell you who you exchanged keys with. An attacker who can change traffic, not only read it, sits in the middle and runs one exchange with the client and another with the server. Each side has an encrypted channel, to the attacker, who reads and forwards everything. This is the man in the middle attack, and it means a key exchange must always be authenticated.

What it does not do
  • Diffie-Hellman does not say WHO you exchanged with an active attacker in the path runs one exchange with each side
  • both sides have a "secure" channel, to the attacker
  • so the exchange must be authenticated

Authenticate it

Protocols fix it by signing. In TLS, the server signs the handshake, including its key exchange value, with the private key of its certificate, and the client checks that signature. An attacker in the middle cannot produce it. In SSH, the host key does the same job, which is why that fingerprint prompt matters. WireGuard uses public keys configured in advance. Key exchange for secrecy, plus a signature for identity: together they are safe.

How protocols fix it
  • TLS: the server signs the handshake with its certificate key
  • SSH: the host key signs; you verify the fingerprint
  • WireGuard: public keys set up in advance
  • Signal: identity keys, safety numbers
  • exchange + signature = safe

Forward secrecy

Now the answer to the weakness from the start. Both sides generate fresh private values for every connection and delete them when it ends. This is called ephemeral key exchange. If the server's long-term key is stolen next year, the attacker still cannot decrypt recorded sessions, because the values that made those keys no longer exist. That property is forward secrecy. TLS 1.3 always provides it; older configurations with static RSA do not.

Ephemeral keys
  • new private values for every connection (the E in ECDHE)
  • deleted when the session ends
  • if the server certificate key leaks next year, recorded sessions stay secret
  • TLS 1.3: always on TLS 1.2: only with ECDHE suites; static RSA has none

What you check

In practice you do not implement this; you configure and check it. The OpenSSL client shows what a server negotiated: the protocol version, the cipher suite and the temporary key, here X two five five one nine. When you audit a server, look for key exchange without forward secrecy, such as static RSA, and for old Diffie-Hellman groups under two thousand and forty eight bits, which have been attacked in practice. On SSH, expect a curve two five five one nine method.

see the key exchange
openssl s_client -connect \
  example.com:443 -brief
# Protocol version: TLSv1.3
# Ciphersuite: TLS_AES_256_GCM_...
# Peer Temp Key: X25519, 253 bits

# audit: no static RSA, no
# finite-field DH under 2048 bits
# SSH: curve25519-sha256

Common mistakes

Mistakes. A key exchange with no authentication, which invites a man in the middle. Disabling certificate checks in a client, which has the same effect. Static RSA key exchange, with no forward secrecy. One thousand and twenty four bit Diffie-Hellman groups. Reusing ephemeral keys across sessions. Using the raw shared secret as an encryption key without a derivation function. And accepting unknown SSH host keys without looking.

Avoid these
  • key exchange with no authentication
  • certificate checks disabled
  • static RSA key exchange
  • 1024-bit DH groups
  • reusing "ephemeral" keys
  • using the raw secret as the key, with no KDF
  • accepting unknown SSH host keys without checking

Say it like this

In the interview: forward secrecy means that stealing a server's long-term key later does not expose past sessions. It is achieved by deriving each session's keys from an ephemeral Diffie-Hellman exchange, such as X two five five one nine, and discarding those values afterwards. The long-term key is used only to sign the handshake, which stops a man in the middle. TLS 1.3 requires this, and I disable static RSA on older stacks.

In the interview
  • "Each session derives keys
  • from an ephemeral Diffie- Hellman exchange, such as X25519, and discards them.
  • The long-term key only signs
  • the handshake. So if it
  • leaks later, recorded
  • traffic still cannot be decrypted."

Interview questions

Q1What is Diffie-Hellman key exchange?

A method that lets two parties derive the same shared secret over a public channel. Each sends a public value computed from a private one; combining your private value with the other side's public value gives the same result on both sides, which an eavesdropper cannot compute.

Q2What is forward secrecy?

The property that compromise of a long-term private key does not expose past session keys. It is achieved with ephemeral key exchange: fresh key pairs per session that are discarded afterwards. It is also called perfect forward secrecy.

Q3Is Diffie-Hellman vulnerable to man-in-the-middle attacks?

Unauthenticated Diffie-Hellman is. An active attacker can perform separate exchanges with each side and relay traffic. Protocols prevent this by authenticating the exchange with signatures, certificates or pre-shared public keys.

Q4What is X25519?

An elliptic curve Diffie-Hellman function on Curve25519, designed to be fast and resistant to implementation errors. It uses 32-byte keys and is the default key exchange in TLS 1.3, modern SSH, WireGuard and Signal.

Q5What is the difference between DH, ECDH and ECDHE?

DH is the original scheme over large prime fields. ECDH performs the same exchange on an elliptic curve with much smaller keys. ECDHE is ECDH with ephemeral keys generated per session, which is what provides forward secrecy.

Q6Why is RSA key exchange no longer used in TLS?

In static RSA key exchange the client encrypts the session secret with the server's long-term public key, so a later compromise of that key decrypts all recorded sessions. TLS 1.3 removed it in favour of ephemeral Diffie-Hellman.

Q7What is a key derivation function (HKDF)?

A function that converts a shared secret or other key material into one or more cryptographically strong keys, using a hash and context labels. It ensures keys are uniform and that different purposes get independent keys.

Q8How do you check which key exchange a server uses?

Connect with openssl s_client and read the negotiated protocol, cipher suite and temporary key, or run a scanner such as testssl.sh or sslyze. Look for TLS 1.3 or ECDHE suites and the absence of static RSA and weak DH groups.