TLS
TLS (Transport Layer Security) puts a secure channel on top of TCP (QUIC has it built in). It's the "S" in HTTPS, and also secures email, database connections and most APIs. TLS gives you three guarantees:
| Guarantee | Meaning | Provided by |
|---|---|---|
| Confidentiality | eavesdroppers can't read the data | symmetric encryption (AES-GCM, ChaCha20-Poly1305) |
| Integrity | tampering is detected | authenticated encryption (AEAD) |
| Authentication | you're really talking to bank.example, not an impostor |
certificates + digital signatures |
The current version is TLS 1.3 (RFC 8446, 2018). TLS 1.2 is still common; SSL and TLS 1.0/1.1 are obsolete and disabled in modern browsers.
The TLS 1.3 handshake
Client Server
ClientHello
+ supported versions, cipher suites
+ key_share (client's ephemeral public key)
+ server_name (SNI: "shop.example.com") -------->
ServerHello
+ key_share (server's ephemeral public key)
{EncryptedExtensions}
{Certificate}
{CertificateVerify} (signature)
<-------- {Finished}
{Finished} -------->
[Application data] <-------> [Application data]Everything in {} is already encrypted. The full handshake takes just one round trip (TLS 1.2 needed two).
Key exchange: agreeing on a secret in public
Both sides send a public value and keep a private one; combining their own private value with the other's public value gives both the same shared secret, while an eavesdropper who sees only the public values can't compute it. Real TLS uses elliptic-curve Diffie-Hellman (X25519). Here is classic Diffie-Hellman with deliberately tiny numbers, so you can follow the arithmetic:
p, g = 23, 5 # public parameters: a prime and a generator (real ones are huge)
client_private = 6 # chosen secretly, fresh for every connection
server_private = 15
client_public = pow(g, client_private, p) # sent in ClientHello key_share
server_public = pow(g, server_private, p) # sent in ServerHello key_share
print("on the wire:", client_public, server_public)
client_secret = pow(server_public, client_private, p)
server_secret = pow(client_public, server_private, p)
print("client computes", client_secret, "| server computes", server_secret)
# An eavesdropper knows p, g and both public values. With small p it can brute-force:
for guess in range(1, p):
if pow(g, guess, p) == client_public:
print("brute force finds client's private value:", guess, "-> real keys use 256-bit curves")
breakon the wire: 8 19
client computes 2 | server computes 2
brute force finds client's private value: 6 -> real keys use 256-bit curves
Because the private values are fresh for each connection (ephemeral), recording traffic today and stealing the server's long-term key tomorrow still doesn't decrypt it. This property is called forward secrecy, and TLS 1.3 requires it.
Deriving keys
The shared secret isn't used directly. Both sides run it through a key derivation function (HKDF, based on HMAC-SHA256) together with a hash of the handshake messages, producing separate keys for each direction. Any tampering with the handshake changes the hash, so the keys won't match and the handshake fails.
import hashlib
import hmac
def hkdf_extract(salt, ikm):
return hmac.new(salt, ikm, hashlib.sha256).digest()
def hkdf_expand(prk, info, length=16):
out, block, counter = b"", b"", 1
while len(out) < length:
block = hmac.new(prk, block + info + bytes([counter]), hashlib.sha256).digest()
out += block
counter += 1
return out[:length]
shared_secret = (2).to_bytes(32, "big") # the toy DH result from above (2)
transcript = hashlib.sha256(b"ClientHello...ServerHello...").digest()
prk = hkdf_extract(b"\x00" * 32, shared_secret)
client_key = hkdf_expand(prk, b"c ap traffic" + transcript)
server_key = hkdf_expand(prk, b"s ap traffic" + transcript)
print("client->server key:", client_key.hex())
print("server->client key:", server_key.hex())
tampered = hashlib.sha256(b"ClientHello...ServerHello(modified)...").digest()
print("keys change if the handshake is tampered with:",
hkdf_expand(prk, b"c ap traffic" + tampered) != client_key)client->server key: 2503bd83e0808451bcaa76fa15cc6ee9
server->client key: f68b0f7ce2ae0dd850c6b4445ebddd33
keys change if the handshake is tampered with: True
Certificates and the chain of trust
How does the client know the server's key really belongs to shop.example.com? The server sends a certificate: its public key and name, signed by a Certificate Authority (CA). The CA's certificate is in turn signed by a root CA that your OS or browser already trusts. The client checks:
- the chain of signatures leads to a trusted root,
- the certificate's name (Subject Alternative Name) matches the host you asked for,
- it's within its validity dates and not revoked,
- the server proves it owns the private key (the CertificateVerify signature over the handshake).
from datetime import date
chain = [
{"subject": "shop.example.com", "issuer": "Example TLS CA R3", "san": ["shop.example.com", "*.cdn.example.com"],
"not_before": date(2026, 8, 1), "not_after": date(2026, 10, 30)},
{"subject": "Example TLS CA R3", "issuer": "Example Root X1", "san": [],
"not_before": date(2024, 1, 1), "not_after": date(2029, 1, 1)},
]
TRUSTED_ROOTS = {"Example Root X1"}
def name_matches(host, pattern):
if pattern.startswith("*."):
return host.count(".") == pattern.count(".") and host.endswith(pattern[1:])
return host == pattern
def verify(host, chain, today):
leaf = chain[0]
if not any(name_matches(host, san) for san in leaf["san"]):
return f"FAIL: certificate is not valid for {host}"
for cert, parent in zip(chain, chain[1:]):
if cert["issuer"] != parent["subject"]:
return f"FAIL: broken chain at {cert['subject']}"
for cert in chain:
if not cert["not_before"] <= today <= cert["not_after"]:
return f"FAIL: {cert['subject']} expired or not yet valid"
if chain[-1]["issuer"] not in TRUSTED_ROOTS:
return "FAIL: unknown root CA"
return "OK: chain " + " -> ".join(c["subject"] for c in chain) + " -> " + chain[-1]["issuer"]
for host, today in [("shop.example.com", date(2026, 10, 17)), ("img.cdn.example.com", date(2026, 10, 17)),
("a.b.cdn.example.com", date(2026, 10, 17)), ("shop.example.com", date(2026, 11, 2)),
("evil.example.net", date(2026, 10, 17))]:
print(f"{host:<20} {today} {verify(host, chain, today)}")shop.example.com 2026-10-17 OK: chain shop.example.com -> Example TLS CA R3 -> Example Root X1
img.cdn.example.com 2026-10-17 OK: chain shop.example.com -> Example TLS CA R3 -> Example Root X1
a.b.cdn.example.com 2026-10-17 FAIL: certificate is not valid for a.b.cdn.example.com
shop.example.com 2026-11-02 FAIL: shop.example.com expired or not yet valid
evil.example.net 2026-10-17 FAIL: certificate is not valid for evil.example.net
(Signatures are left out here; real verification checks each one cryptographically.) Notice that a wildcard covers exactly one label: *.cdn.example.com matches img.cdn.example.com but not a.b.cdn.example.com.
Inspecting TLS for real
openssl s_client -connect example.com:443 -servername example.com -brief < /dev/nullSample output:
CONNECTION ESTABLISHED
Protocol version: TLSv1.3
Ciphersuite: TLS_AES_256_GCM_SHA384
Peer certificate: C=US, ST=California, L=Los Angeles, O=Internet Corporation for Assigned Names and Numbers, CN=www.example.org
Hash used: SHA256
Signature type: ECDSA
Verification: OK
Server Temp Key: X25519, 253 bitsNote: TLS protects the contents, but the SNI (server name in the ClientHello), the server's IP address and the traffic's timing and size are still visible to the network. Encrypted Client Hello (ECH) is the newer extension that hides the SNI too.
Go further: TLS Records and the ClientHello parses a real ClientHello byte by byte and shows what defenders learn from it.
Test yourself
What does forward secrecy protect against?
- Expired certificates
- Decrypting recorded traffic later if the server's long-term private key is stolen
- Packet loss
- DNS spoofing
How many round trips does a full TLS 1.3 handshake take?
- 0
- 1
- 2
- 3
Does a certificate for *.example.com match a.b.example.com?
- Yes
- No, a wildcard matches exactly one label
- Only on Sundays
- Only with TLS 1.2