Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Systems · Security

A Secret, Agreed in Public.

When you connect to an https:// site, two computers that have never met must agree on a secret encryption key — and they have to do it over a network where anyone can read every packet. This sounds impossible, and it’s the quiet miracle the TLS handshake performs before any real data flows. It solves two problems at once. First, authentication: the server presents a certificate signed by a Certificate Authority your device already trusts, proving it really is who it claims — this is what stops an impostor. Second, key agreement: using ephemeral Diffie-Hellman, client and server each pick a private number, exchange the corresponding public numbers in the clear, and then each combines the other’s public number with their own private one to compute the exact same shared secret — a value that was never sent across the wire. An eavesdropper sees the public numbers but can’t feasibly work backward to the secret. Step through the messages and watch both sides arrive at the identical key.

certificate proves identity · ephemeral Diffie-Hellman derives the same secret · never transmitted
certificate

A server’s identity document, signed by a Certificate Authority your device trusts. Proves the server is who it claims.

Diffie-Hellman

A method where two parties derive a shared secret by exchanging only public numbers — the secret itself is never sent.

ephemeral

Fresh keys per session (the “E” in ECDHE). If a key later leaks, past sessions stay safe — forward secrecy.

forward secrecy

Recording today’s encrypted traffic and stealing the server’s key tomorrow still won’t decrypt it.

handshake.js — same secret, never sent
Ready
Client and server will agree on a secret key while an eavesdropper watches every packet. Press Next ▸ to send each handshake message. Watch the shared secret appear identically on both sides — computed, never transmitted.
a=?
client private
b=?
server private
🔓
shared secret
👁 Eavesdropper sees: nothing yet

How it works

The handshake’s cleverness is that secrecy and identity are solved by two different mechanisms, and it helps to keep them separate. Identity comes from the certificate chain: your device ships with a set of trusted Certificate Authority root keys, the server’s certificate is signed (transitively) by one of them, and the server proves it holds the matching private key — so you know you’re talking to the real site and not an impostor sitting in the middle. Secrecy comes from Diffie-Hellman, which rests on a one-way math trick: given public numbers A = gᵃ mod p and B = gᵇ mod p, computing the shared secret gᵃᵇ mod p is trivial if you know your own private exponent (the client computes Bᵃ, the server computes Aᵇ, and they’re equal), but an eavesdropper who sees only A and B would have to solve the discrete-logarithm problem to recover an exponent — infeasible at real key sizes. Making the DH keys ephemeral (a fresh pair per session, the “E” in ECDHE) adds forward secrecy: even if the server’s long-term private key is stolen later, yesterday’s recorded traffic can’t be decrypted, because the session key was thrown away and never derived from that long-term key.

1

ClientHello

The client sends its supported cipher suites, a random nonce, and its ephemeral Diffie-Hellman public value A = gᵃ mod p. Its private exponent a stays secret on the client.

2

ServerHello + Certificate

The server replies with its chosen cipher, its own DH public value B = gᵇ mod p, and its certificate — signed by a CA the client trusts — proving its identity. The private exponent b never leaves the server.

3

Both derive the same secret

The client computes Bᵃ mod p; the server computes Aᵇ mod p. Both equal gᵃᵇ mod p — the identical shared secret. It was never transmitted; each side built it from the other’s public value and its own private one.

✓

Finished — encrypted traffic

Both switch to symmetric encryption keyed from the shared secret and exchange Finished messages. Real application data now flows encrypted. The eavesdropper saw A and B but cannot compute the secret.

Identity
certificate (CA-signed)
Secrecy
ephemeral Diffie-Hellman
Sent in clear
A and B (public)
Never sent
the shared secret

The code

# Ephemeral Diffie-Hellman (tiny numbers, real math) p, g = 23, 5 # public parameters, known to all # Client picks a private exponent, sends only the public value a = 6; A = pow(g, a, p) # A = 8 (sent in the clear) # Server picks its own, sends only its public value + certificate b = 15; B = pow(g, b, p) # B = 19 (sent in the clear) # Each combines the OTHER's public value with its OWN private one client_secret = pow(B, a, p) # 19^6 mod 23 = 2 server_secret = pow(A, b, p) # 8^15 mod 23 = 2 assert client_secret == server_secret # same secret — never transmitted

The picture: a TLS 1.3 handshake, message by message

client server ClientHello: key_share A, cipher suites has key ServerHello: key_share B {Certificate, CertificateVerify, Finished} has key {Finished} + first request {application data, both ways} grey: in the clear · accent and {braces}: encrypted
The lab’s five steps map onto three flights. Only the two hellos travel in the clear. The server can derive the secret as soon as ClientHello arrives, so everything it sends after ServerHello, including the certificate, is already encrypted. CertificateVerify is the server’s signature over the whole conversation so far, made with the private key behind its certificate: it is what ties the key shares to the identity. The client’s request goes out after one round-trip.

Worked example: a man in the middle, with the lab’s numbers

Same public group as the lab: p = 23, g = 5, client secret a = 6, server secret b = 15. This time Mallory sits on the wire, can change packets, and picks her own exponent m = 3. Suppose nothing is signed.

StepWhoDoesValue
1ClientSends A = 5⁶ mod 238
2MalloryDrops A, sends M = 5³ mod 23 to the server10
3ServerSends B = 5¹⁵ mod 2319
4MalloryDrops B, sends the same M to the client10
5ClientSecret = Mᵃ = 10⁶ mod 236
6ServerSecret = Mᵇ = 10¹⁵ mod 235
7MalloryAᵐ = 8³ mod 23 and Bᵐ = 19³ mod 236 and 5
8With TLSServer signs the transcript holding B = 19; the client saw 10abort

Without a signature, Mallory holds both keys (6 with the client, 5 with the server) and can decrypt, read and re-encrypt everything while each side believes the handshake worked. Diffie-Hellman did its job; it just did it with the wrong party. Row 8 is the fix: CertificateVerify signs the transcript, the client checks it against the certificate’s public key, and Mallory cannot produce that signature without the server’s private key. A passive eavesdropper has it worse still. To recover a from A = 8 in the toy group she tries 5¹, 5², … and hits 8 on the 6th try, because there are only 22 exponents. Real handshakes use groups such as X25519, where the best known attacks need on the order of 2¹²⁸ operations: the same search, out of reach.

Cost and trade-offs: round-trips before the first byte

A handshake mostly costs latency, not CPU. Time is counted to the first byte of the response, including the TCP handshake where there is one, with an illustrative 100 ms round-trip.

CaseTimeSpaceWhy
TLS 1.2, full (ECDHE)4 RTT = 400 mstwo handshake flightsTCP 1 + TLS 2 + request 1.
TLS 1.3, full3 RTT = 300 msone key share each wayKey shares ride in the hellos, so TLS needs 1 RTT.
TLS 1.3, 0-RTT resumption2 RTT = 200 msa stored resumption secretRequest rides in the first flight; it can be replayed.
QUIC (HTTP/3), full2 RTT = 200 msTLS 1.3 inside the transportTransport and crypto handshakes are one.
QUIC with 0-RTT1 RTT = 100 mssame replay caveatRequest goes in the very first packets.
TLS 1.2 static RSAsame as 1.2no ephemeral keyNo forward secrecy: one leaked server key opens every recorded session. Removed in 1.3.

The pattern: every round-trip saved is one RTT off every new connection, which is why 1.3 moved the key shares into the hellos and why QUIC folded the transport handshake in too. 0-RTT is the one row that buys speed with security: early data is not protected against replay, so servers should accept it only for requests that are safe to run twice.

Common mistakes

  • Turning verification off

    curl -k, verify=False or a trust-everything client still encrypts, and that is exactly the worked example: an encrypted line to whoever answered. The certificate check is the half that names who is on the other end.

  • Checking the chain but not the name

    A certificate can be perfectly valid for attacker.example. The client must also check that the name on it matches the host it meant to reach.

  • Serving an incomplete chain

    Leave out the intermediate certificate and some browsers still connect, because they cached or fetched it, while curl, mobile apps and other servers fail. Send the full chain up to, but not including, the root.

  • Accepting 0-RTT for anything

    Early data can be captured and replayed. A replayed “transfer £100” is a second transfer. Limit it to idempotent requests or turn it off.

  • Assuming HTTPS hides which site you visit

    The ClientHello normally carries the server name (SNI) in the clear, so an observer learns the host even though the pages are encrypted. Encrypted Client Hello exists to close that gap.

Where this shows up

  • Every HTTPS request

    openssl s_client -connect example.com:443 or curl -v https://… prints the version, cipher suite and certificate chain the two sides settled on: the same handshake, with real numbers.

  • Mutual TLS between services

    In a service mesh both sides present certificates, so the server authenticates the client too. Meshes issue short-lived workload certificates automatically and rotate them, which is the only way that scales.

  • Certificate automation and outages

    ACME clients request and renew certificates without a human. Expired certificates remain a classic cause of outages, because the handshake fails closed: no valid certificate, no connection.

  • Interview angle

    In “what happens when you type a URL”, be ready to say why both pieces are needed (the worked example), what forward secrecy protects, and why 1.3 is 1-RTT. A strong extra: TLS 1.3 encrypts the certificate, so a passive observer of a 1.3 handshake sees the key shares and the server name, not the certificate.

Quick check

1. During the handshake, what actually travels across the network in the clear?

2. What does the server’s certificate provide?

3. Why does using ephemeral (per-session) DH keys give forward secrecy?

FAQ

What is the TLS handshake?

The negotiation two computers perform before exchanging encrypted data over HTTPS. It does two jobs: it authenticates the server (via a CA-signed certificate proving identity) and establishes a shared secret key (via Diffie-Hellman, where both sides derive the same key from public values without ever sending it). Then both switch to fast symmetric encryption for the actual data.

How can two computers agree on a secret key over an open network?

Through Diffie-Hellman key exchange. Each side picks a private number and computes a public value (A = gᵃ mod p), exchanges the public values in the clear, then combines the other’s public value with its own private number — both arrive at the identical gᵃᵇ mod p. An eavesdropper sees only the public values and would have to solve the discrete-logarithm problem to recover a private exponent, which is infeasible. The secret is agreed but never sent.

What is the difference between TLS 1.2 and TLS 1.3?

TLS 1.3 is a major simplification and speed-up: it cut handshakes from two round-trips to one (1-RTT), removed old weak ciphers, and made forward-secret ephemeral key exchange mandatory. TLS 1.2 allowed non-forward-secret exchange (static RSA) and had more footguns. TLS 1.3 also supports 0-RTT resumption for returning clients, trading a little security for lower latency.

What stops a man-in-the-middle attack during the handshake?

The certificate. Diffie-Hellman alone stops a passive eavesdropper but not an active attacker relaying messages and doing a separate exchange with each side. The defense is authentication: the server signs the handshake with the key matching its certificate, which is CA-signed and in the client’s trust store. An attacker can relay but can’t forge a valid certificate for the real domain, so the client detects the mismatch and aborts. Encryption without authentication isn’t enough.

Keep going

▶  Watch it explained

The TLS handshake: how HTTPS agrees on a secret in the open

Finished this one? 0 / 61 Labs done
NextThe Load Balancer Next on the “Down the wire” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs