AnyLearn
All lessons
Programmingadvanced

Key Exchange and TLS 1.3

Every HTTPS connection negotiates a fresh secret over an untrusted network. Learn Diffie-Hellman and ECDH from first principles, why forward secrecy matters when private keys leak, how TLS 1.3 cut the handshake to one round-trip, and how certificate chains stop man-in-the-middle attacks.

Not signed in — your progress and quiz score won't be saved.
Lesson progress1 / 10

The key exchange problem

Alice and Bob want to communicate confidentially over a channel that Eve can read. They have never met. How do they establish a shared secret key?

Before 1976 this seemed impossible — the key had to be transmitted somehow, and any transmission Eve could intercept. Whitfield Diffie and Martin Hellman's 1976 paper showed a way: two parties can compute the same secret from information that is entirely public, as long as inverting a certain one-way function is hard.

This is the Diffie-Hellman key exchange. It does not provide authentication (Eve can still impersonate either party) — authentication is layered on top via certificates and digital signatures. The combination of key exchange + authentication + symmetric encryption is exactly what TLS provides.

Full lesson text

All 10 steps on one page — for reading, reference, and search.

Show

1. The key exchange problem

Alice and Bob want to communicate confidentially over a channel that Eve can read. They have never met. How do they establish a shared secret key?

Before 1976 this seemed impossible — the key had to be transmitted somehow, and any transmission Eve could intercept. Whitfield Diffie and Martin Hellman's 1976 paper showed a way: two parties can compute the same secret from information that is entirely public, as long as inverting a certain one-way function is hard.

This is the Diffie-Hellman key exchange. It does not provide authentication (Eve can still impersonate either party) — authentication is layered on top via certificates and digital signatures. The combination of key exchange + authentication + symmetric encryption is exactly what TLS provides.

2. Diffie-Hellman — the math

Choose a large prime pp and a generator gg (both public). Alice picks secret aa, Bob picks secret bb:

A=gamodp(Alice sends A)B=gbmodp(Bob sends B)A = g^a \bmod p \quad (\text{Alice sends } A) \qquad B = g^b \bmod p \quad (\text{Bob sends } B)

Both compute the shared secret:

S=Bamodp=gabmodp=AbmodpS = B^a \bmod p = g^{ab} \bmod p = A^b \bmod p

Eve sees g,p,A,Bg, p, A, B but must solve a=loggAmodpa = \log_g A \bmod p — the discrete logarithm problem — to derive SS. No polynomial-time classical algorithm is known for appropriately chosen pp.

Parameters must be chosen carefully: pp must be a safe prime (p=2q+1p = 2q+1 where qq is also prime); gg should generate the large-order subgroup; pp must be at least 2048 bits (3072 for 128-bit security). Pre-computed DH parameters in old software were the target of the Logjam attack (2015), which broke 768-bit DH for export ciphersuites.

3. ECDH — Diffie-Hellman on elliptic curves

Elliptic Curve Diffie-Hellman (ECDH) replaces modular exponentiation with elliptic curve scalar multiplication:

A=aG(Alice sends A)B=bG(Bob sends B)A = aG \quad (\text{Alice sends } A) \qquad B = bG \quad (\text{Bob sends } B)

Shared secret:

S=aB=a(bG)=b(aG)=bAS = aB = a(bG) = b(aG) = bA

Eve must solve aa from (G,aG)(G, aG) — the ECDLP. With Curve25519 (the standard for TLS 1.3 key exchange, also called X25519), 256-bit scalars give ~128-bit security with keys that fit in 32 bytes.

SchemeSecurityKey material transmittedSpeed
DH-2048112-bit256 bytesSlow
DH-3072128-bit384 bytesSlower
ECDH P-256128-bit65 bytes (uncompressed)Fast
X25519128-bit32 bytesVery fast

X25519 is the mandatory key exchange in TLS 1.3. DH-FFDHE groups are also supported but less common.

4. Forward secrecy — why ephemeral keys matter

Forward secrecy (also called perfect forward secrecy, PFS) means: a compromise of the server's long-term private key does not compromise past session keys.

Old TLS 1.2 cipher suites without PFS used the server's RSA private key to directly encrypt (or sign) the session key. An attacker who recorded traffic and later obtained the private key could decrypt all stored sessions retroactively. NSA bulk collection programs were designed around exactly this threat model.

PFS is achieved by using ephemeral DH or ECDH: fresh (a, b) values are generated per session and discarded immediately after the handshake. The server's long-term key is only used for authentication (signing the DH parameters), not key derivation.

TLS 1.3 mandates forward secrecy — all key exchange uses ECDHE or DHE. TLS 1.2 cipher suites starting with ECDHE_ or DHE_ have PFS; suites starting with RSA_ do not. Check your server's cipher list: if TLS_RSA_* suites are enabled, you are vulnerable to retrospective decryption.

5. Certificates, chains of trust, and PKI

ECDH gives Alice and Bob a shared secret, but how does Alice know she is talking to Bob and not Eve? The answer is certificates.

A certificate binds a public key to an identity (e.g., example.com) with a digital signature from a trusted third party — a Certificate Authority (CA). Your browser ships with ~150 root CA certificates in its trust store; any site certificate signed (directly or through intermediates) by one of those roots is trusted.

Chain of trust structure:

  • Root CA: self-signed; kept offline in an HSM.
  • Intermediate CA: signed by root; used for day-to-day issuance; can be revoked if compromised.
  • Leaf/End-entity certificate: signed by an intermediate; contains the server's public key and domain names (CN / SAN).

During TLS, the server presents the leaf + intermediates. The client verifies the chain up to a trusted root. If any signature is invalid, or the leaf's domain doesn't match, the handshake fails with a certificate error — not a transparent downgrade.

6. TLS 1.3 handshake

A TLS 1.3 full handshake completes in one round-trip (1-RTT) before application data flows:

sequenceDiagram
  participant C as Client
  participant S as Server
  C->>S: ClientHello (supported ciphers, key_share X25519 pubkey)
  S->>C: ServerHello (chosen cipher, key_share X25519 pubkey)
  S->>C: EncryptedExtensions
  S->>C: Certificate (leaf + intermediates)
  S->>C: CertificateVerify (signature over handshake hash)
  S->>C: Finished (HMAC over handshake)
  C->>S: Finished (HMAC over handshake)
  C->>S: Application Data (encrypted)
  S->>C: Application Data (encrypted)

7. TLS 1.3 key schedule — how keys are derived

TLS 1.3 replaced the ad-hoc PRF-based key derivation of TLS 1.2 with a clean HKDF-based schedule:

  1. ECDHE shared secret(EC)DHE input.
  2. Early secret = HKDF-Extract(0, PSK) (PSK = 0 for full handshake).
  3. Handshake secret = HKDF-Extract(derived_early, ECDHE).
  4. From handshake secret: derive client_handshake_traffic_secret and server_handshake_traffic_secret — used to encrypt the rest of the handshake.
  5. Master secret = HKDF-Extract(derived_handshake, 0).
  6. From master secret: derive client_application_traffic_secret and server_application_traffic_secret — used to encrypt application data.

Each direction uses independent keys — client→server and server→client never share a key. Re-keying (KeyUpdate) can happen mid-connection. The server's CertificateVerify signature covers a transcript hash of the entire handshake so far, binding the certificate to the specific key exchange.

8. MITM attacks and certificate validation

A man-in-the-middle (MITM) attacker who controls the network can intercept the ClientHello, present their own certificate, and relay traffic. TLS stops this because the attacker cannot forge a certificate signed by a trusted root (without compromising a CA or the client's trust store).

Real-world MITM scenarios:

  • Rogue CA: Lenovo's Superfish (2015) installed a self-signed root CA on laptops with the same private key on every unit — leaked, and trivially exploited.
  • CA compromise: DigiNotar (2011) was hacked; fraudulent *.google.com certificates were issued and used to intercept Iranian Gmail.
  • Certificate pinning: apps that hardcode the expected certificate or public key hash bypass the CA system. Defeats all CA-based MITM, but makes rotation painful.
  • HSTS: Strict-Transport-Security header tells browsers to reject any non-TLS connection to a domain for a set period — prevents SSL stripping (downgrade to HTTP before TLS starts).

9. TLS 1.2 vs 1.3 — what was removed and why

TLS 1.3 (RFC 8446, 2018) is a breaking cleanup of 1.2:

FeatureTLS 1.2TLS 1.3
Handshake RTTs2-RTT1-RTT (0-RTT resumption available)
RSA key exchangeAllowed (no PFS)Removed
Static DHAllowedRemoved
RC4, 3DES, export ciphersAllowedRemoved
CBC-mode ciphersAllowedRemoved
Cipher suites~300+5 (all AEAD)
Key derivationAd-hoc PRFHKDF
Downgrade attacksPossible (POODLE, BEAST)Cryptographically prevented

The 0-RTT resumption feature (session tickets) allows a client to send data in the first flight — but this data has no forward secrecy and is replay-vulnerable. Only use 0-RTT for idempotent requests (GET, not POST with side effects).

10. Deploying TLS correctly — common mistakes

Getting TLS right in practice requires more than enabling HTTPS:

  1. TLS version: disable TLS 1.0 and 1.1 (POODLE, BEAST). Enforce TLS 1.2+ minimum; prefer TLS 1.3 only where possible.
  2. Cipher suite order: put ECDHE+AESGCM suites first; disable RSA key exchange suites in TLS 1.2.
  3. Certificate management: automate renewal (Let's Encrypt / ACME) — human processes miss expirations. Expired certs cause outages, not security incidents, but they erode trust.
  4. HSTS preloading: submit your domain to hstspreload.org for inclusion in browser preload lists — eliminates first-visit SSL stripping.
  5. OCSP stapling: include the CA's revocation response in the handshake so clients don't need to make a separate revocation check (privacy + performance).
  6. Pinning vs CT: Certificate Transparency (CT) logs are a scalable alternative to pinning — misissuance is publicly detectable; clients can require SCTs.

Validate your config with testssl.sh or Qualys SSL Labs; a grade below A- signals exploitable misconfigurations.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. Alice and Bob exchange Diffie-Hellman public values $A = g^a \bmod p$ and $B = g^b \bmod p$ over a channel Eve can read. What can Eve compute with only $g$, $p$, $A$, $B$?
    • The shared secret $S = g^{ab} \bmod p$ directly, since she has both public values.
    • Nothing useful — she must solve the discrete logarithm $a = \log_g A$ or $b = \log_g B$ to find $S$.
    • The shared secret using the Pohlig-Hellman algorithm, provided $p-1$ is smooth.
    • The product $ab \bmod p$ directly from $A \cdot B \bmod p$.
  2. A server's long-term RSA private key is stolen from a backup. Which TLS configuration protects all previously recorded sessions?
    • TLS 1.2 with RSA key exchange and AES-256-GCM.
    • TLS 1.2 with ECDHE key exchange (ECDHE-RSA-AES256-GCM-SHA384).
    • TLS 1.1 with a 4096-bit RSA key for the certificate.
    • TLS 1.2 with DHE using a 1024-bit DH group.
  3. In TLS 1.3, what prevents a man-in-the-middle attacker from substituting their own X25519 public key during the handshake?
    • X25519 key pairs are registered with a CA before the connection.
    • The server signs a transcript of the entire handshake (including key shares) with its certified private key in CertificateVerify.
    • The client and server independently verify that both X25519 public keys are on the approved NIST curve list.
    • TLS 1.3 uses quantum-resistant key encapsulation that cannot be intercepted.
  4. TLS 1.3's 0-RTT resumption lets the client send application data in the first flight. What is the main security downside?
    • 0-RTT data is encrypted with the server's long-term public key, losing forward secrecy.
    • 0-RTT data can be replayed by a network attacker against the server.
    • 0-RTT bypasses certificate validation for the resumed session.
    • 0-RTT requires the client to reveal its session ticket to any intermediate proxy.
  5. DigiNotar (2011) was a Certificate Authority that was compromised, leading to fraudulent certificates. What property of the PKI system did this break?
    • Forward secrecy — the attacker could decrypt old TLS sessions.
    • The chain of trust — a trusted CA issued certificates for domains it had no authority over.
    • Certificate pinning — the fraudulent certificates bypassed app-level pinning checks.
    • OCSP stapling — the attacker disabled revocation checking on all affected servers.

Related lessons