Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Secure Protocols

The TLS Handshake and Certificates

Follow the TLS 1.3 handshake step by step: key exchange, certificates, chains of trust, hostname checks and common misconfigurations, with toy Python demos of each idea.

When your browser shows a padlock, TLS (Transport Layer Security) is doing three jobs at once. It provides confidentiality (eavesdroppers see scrambled bytes), integrity (changes in transit are detected) and authentication (you are talking to the real server, not an impostor). Almost every secure protocol today is TLS underneath: HTTPS, SMTP with STARTTLS, secure LDAP, database connections, VPN portals.

This lesson follows a TLS 1.3 connection from the first packet to encrypted application data. The Python programs are toy demonstrations: small numbers and simplified checks that show the ideas. They are not cryptographic code to reuse. In real software always use a vetted library and its defaults.

The handshake in six steps

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: ClientHello (versions, ciphers, key share, SNI)
    S->>C: ServerHello (chosen cipher, key share)
    Note over C,S: Both derive the same session keys
    S->>C: Certificate + signature (encrypted)
    S->>C: Finished
    C->>S: Finished
    C->>S: Application data (encrypted)

In TLS 1.3 everything after ServerHello is already encrypted, and the handshake takes one round trip.

  1. ClientHello. The client offers supported cipher suites and sends its half of a key exchange (an ephemeral key share). The SNI (server name indication) says which hostname it wants.
  2. ServerHello. The server picks a cipher suite and sends its key share.
  3. Key derivation. Both sides combine the key shares to get the same secret without ever sending it. Because the keys are ephemeral (used once and discarded), recorded traffic cannot be decrypted later even if the server's long-term key is stolen. This is forward secrecy.
  4. Authentication. The server sends its certificate and proves it owns the matching private key by signing the handshake transcript.
  5. Finished. Each side sends a MAC over the whole handshake. If an attacker altered anything (for example to downgrade the cipher), the MACs fail.
  6. Application data flows, encrypted with an AEAD cipher such as AES-GCM or ChaCha20-Poly1305.

TLS 1.2 is similar but needs two round trips and allowed weak options (RSA key transport without forward secrecy, CBC cipher suites). TLS 1.0 and 1.1 are deprecated; SSL 2 and 3 are broken. Modern guidance: enable TLS 1.3 and 1.2, disable the rest.

Key exchange: the idea in numbers

Diffie-Hellman lets two parties agree on a shared secret over a public channel. Each picks a private number, publishes a derived public value, and both compute the same result. Real TLS uses elliptic curves such as X25519 with 255-bit numbers; this toy uses tiny integers so you can see the algebra.

Python Toy Diffie-Hellman key agreement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An eavesdropper who sees only the two public values would have to solve the discrete logarithm problem to recover a private number, which is infeasible at real sizes.

But whom are you agreeing with?

Diffie-Hellman alone is vulnerable to a man-in-the-middle: an attacker can run one exchange with you and another with the server and relay traffic between them. The fix is authentication, which is why certificates exist.

Certificates and the chain of trust

A certificate (X.509) binds a public key to an identity, signed by a certificate authority (CA). It contains:

  • Subject and Subject Alternative Names (SAN), the hostnames it is valid for.
  • The public key.
  • A validity period (notBefore, notAfter). Public certificates are now valid for under a year and shrinking.
  • The issuer and the issuer's signature.
  • Key usage extensions (for example "may be used for server authentication").

Servers rarely have a certificate signed directly by a root CA. They send a chain: leaf, then an intermediate CA, and the client already trusts the root in its trust store. Validation walks upward: each certificate must be signed by the next one, none expired, none revoked, and the chain must end at a trusted root.

flowchart BT
    L["Leaf certificate<br/>shop.example.org"] -- "signed by" --> I["Intermediate CA"]
    I -- "signed by" --> R["Root CA<br/>(in the trust store)"]

Validating a certificate (simplified)

Real validation verifies signatures with public-key cryptography. The stand-in below skips the math and checks the logic around it: hostname match (with wildcards), expiry, and whether the chain ends at a trusted root.

Python A simplified certificate validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each failure corresponds to a browser warning you have probably seen. The most dangerous habit in software is disabling these checks to "make the error go away" (verify=False, InsecureSkipVerify, curl -k). Doing so removes the authentication that makes TLS secure and re-opens the man-in-the-middle attack.

Revocation and transparency

What if a private key leaks before the certificate expires? Revocation mechanisms exist: CRLs (lists) and OCSP (query a responder). OCSP stapling lets the server attach a fresh signed response so the client does not need to ask the CA (better for privacy and speed). Revocation is unreliable in practice, which is one reason lifetimes are shortened. Certificate Transparency logs make every issued public certificate visible so domain owners can detect certificates issued without their consent; you can monitor the logs for your own domains.

Mutual TLS and internal use

In ordinary TLS only the server proves its identity. In mutual TLS (mTLS) the client also presents a certificate. It is standard for service-to-service traffic in zero trust designs and microservices, where each workload gets a short-lived certificate from an internal CA.

Hardening checklist

  • Enable TLS 1.3 and 1.2 only; prefer AEAD ciphers with forward secrecy.
  • Use certificates from a trusted CA (or your internal CA for private services) and automate renewal (for example the ACME protocol) so they never silently expire.
  • Send HSTS (Strict-Transport-Security) so browsers refuse plain HTTP for your domain.
  • Protect private keys: restricted file permissions, hardware modules for high-value keys, never in source control.
  • Never disable certificate verification in client code.
  • Test configuration with scanners you are authorized to run against your own servers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What gives TLS 1.3 forward secrecy?

    Ephemeral key shares are discarded after the handshake, so stealing the server key later does not decrypt recorded traffic.
  2. 2. Why is anonymous Diffie-Hellman not enough on its own?

    Without authentication you cannot tell whether the key share came from the real server.
  3. 3. A wildcard certificate for *.example.org covers which name?

    A wildcard matches exactly one label in that position; the bare domain and deeper subdomains are not covered.
  4. 4. Which client-code change breaks TLS authentication?

    Disabling verification accepts any certificate, including an attacker's.
  5. 5. In mutual TLS, who presents a certificate?

    mTLS authenticates both ends, which suits service-to-service communication.

Summary

  • TLS gives confidentiality, integrity and server authentication; TLS 1.3 needs one round trip and encrypts most of the handshake.
  • Ephemeral key exchange gives forward secrecy; certificates authenticate the server and defeat man-in-the-middle attacks.
  • Validation checks hostname (SAN), validity dates, issuer chain and a trusted root; revocation and Certificate Transparency add safety nets.
  • mTLS authenticates both sides and is common between services.
  • Harden with TLS 1.3/1.2, automated renewal, HSTS and protected keys; never disable verification.

Next: DNS Security