← All lessons
How HTTPS works
Send a password over HTTP, then HTTPS
Browser
Café Wi-Fi
shop.test
browser.js
// http:// sends the request as plain textawait fetch("http://shop.test/login", { method: "POST", body: JSON.stringify({ password }),}); // https:// is the same call. TLS encrypts it firstawait fetch("https://shop.test/login", { method: "POST", body: JSON.stringify({ password }),});server.js
import https from "node:https"; // TLS decrypts each request before your code sees ithttps.createServer({ key, cert }, app).listen(443); app.post("/login", (req, res) => { const { password } = req.body;});The handshake agrees on a key in the open
Browser
shop.test
handshake.js
// browserconst mine = await generateKey("ECDH P-256");send({ hello: "TLS 1.3", keyShare: mine.public }); // serverconst its = await generateKey("ECDH P-256");send({ keyShare: its.public, cert }); // browsercheckCert(cert, "shop.test"); // both sides, each with its own private keyconst secret = ecdh(mine.private, its.public);const key = hkdf(secret, "tls13 key");Every message is sealed and any change breaks the seal
What travels on the wire
key
nonce
sealed
record.js
// a fresh nonce for every recordconst iv = crypto.getRandomValues(new Uint8Array(12));const sealed = await crypto.subtle.encrypt( { name: "AES-GCM", iv }, sessionKey, message,);send(iv, sealed); // the server, with the same session keyconst text = await crypto.subtle.decrypt( { name: "AES-GCM", iv }, sessionKey, sealed,);// one changed byte and decrypt() throwsCertificates prove who you're talking to or the browser stops you
https://shop.test
Certificate
An attacker can copy a real certificate, but without its private key they can't finish the handshake
browser.js
function checkCert(cert, host) { const ca = trustStore[cert.issuer]; if (!ca || !verify(ca.publicKey, cert)) { return "not private: unknown signer"; } if (cert.subject !== host) { return "not private: wrong name"; } if (Date.now() > cert.notAfter) { return "not private: expired"; } return "secure";}Topics
Next: How JWT login works
Open lesson