TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › The TLS 1.3 Key Schedule and HKDF

The TLS 1.3 Key Schedule and HKDF

A TLS 1.3 connection uses at least six different secrets: keys for the encrypted handshake in each direction, application keys in each direction, a key for Finished messages, an exporter secret, a resumption secret. They all come from one X25519 output (plus an optional pre-shared key) through the key schedule, a chain of HKDF calls in which each step is bound to a label and to the handshake transcript. Understanding it explains why TLS 1.3 keys are independent of each other, why SSLKEYLOGFILE decryption works, and how other protocols should derive keys.

HKDF in two steps

HKDF (RFC 5869, Krawczyk) is a key-derivation function built from HMAC:

  • Extract: PRK = HMAC(salt, input_key_material). Concentrates the entropy of an uneven input (such as a DH output) into a uniformly random key.
  • Expand: OKM = T(1) || T(2) || …, with T(i) = HMAC(PRK, T(i−1) || info || i). Stretches the key into as many bytes as needed, different for every info label.

TLS 1.3 wraps Expand as HKDF-Expand-Label ("tls13 " + label, plus a context, usually a transcript hash) and defines Derive-Secret(secret, label, messages) = HKDF-Expand-Label(secret, label, Hash(messages), Hash.length).

The schedule

text
            0 (or PSK)
            |
  0 ----> Extract  = Early Secret ------> binder, early traffic (0-RTT)
            |
         Derive-Secret(., "derived", "")
            |
  (EC)DHE -> Extract = Handshake Secret --> "c hs traffic", "s hs traffic"   (ClientHello..ServerHello)
            |
         Derive-Secret(., "derived", "")
            |
  0 ----> Extract  = Master Secret -------> "c ap traffic", "s ap traffic"   (ClientHello..server Finished)
                                            "exp master"; "res master" (ClientHello..client Finished)
each traffic secret -> HKDF-Expand-Label(secret, "key", "", key_len) and ("iv", "", 12)
finished_key = HKDF-Expand-Label(handshake traffic secret, "finished", "", Hash.length)

The properties this gives:

  • Independence: each key comes from its own label and transcript, so learning the client's handshake key reveals nothing about the server's application key.
  • Transcript binding: handshake keys depend on the hash of ClientHello…ServerHello, application keys on everything up to the server's Finished. An attacker who changes any message gets different keys and the Finished check fails.
  • Forward secrecy: the (EC)DHE secret enters in the middle; once it and the derived secrets are erased, recorded traffic can't be decrypted with the server's certificate key.
  • Key updates: either side can send KeyUpdate; the next secret is HKDF-Expand-Label(current, "traffic upd", "", Hash.length), and the old one is deleted.

The schedule in Python

The example implements HKDF-Expand-Label and Derive-Secret in a few lines and checks the first two values against RFC 8448 ("Example Handshake Traces for TLS 1.3"), whose early secret and derived secret are the same in every SHA-256 handshake without a PSK. The rest uses lab inputs (the RFC 7748 X25519 output and stand-in transcripts) to show the structure, so those values don't match any real connection.

python · try it yourself
import hashlib, hmac, struct

H = hashlib.sha256
HASH_LEN = 32
def hkdf_extract(salt, ikm): return hmac.new(salt, ikm, H).digest()
def hkdf_expand_label(secret, label, context, length):      # RFC 8446 section 7.1
    full = b"tls13 " + label
    info = struct.pack(">H", length) + bytes([len(full)]) + full + bytes([len(context)]) + context
    out, t, i = b"", b"", 1
    while len(out) < length:                                  # HKDF-Expand (RFC 5869)
        t = hmac.new(secret, t + info + bytes([i]), H).digest(); out += t; i += 1
    return out[:length]
def derive_secret(secret, label, transcript): return hkdf_expand_label(secret, label, H(transcript).digest(), HASH_LEN)

zero = bytes(HASH_LEN)
early = hkdf_extract(b"\x00", zero)                           # no PSK
print("early secret  :", early.hex())
print("matches RFC 8448:", early.hex() == "33ad0a1c607ec03b09e6cd9893680ce210adf300aa1f2660e1b22e10f170f92a")
derived = derive_secret(early, b"derived", b"")
print("derived       :", derived.hex()[:32], "...")
print("matches RFC 8448:", derived.hex() == "6f2615a108c702c5678f54fc9dbab69716c076189c48250cebeac3576c3611ba")

# From here on: lab values (a fixed X25519 output and fake transcripts) to show the structure.
ecdhe = bytes.fromhex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742")   # RFC 7748 shared secret
hs = hkdf_extract(derived, ecdhe)
hello = b"ClientHello...ServerHello"                          # stands in for the real transcript bytes
c_hs = derive_secret(hs, b"c hs traffic", hello)
s_hs = derive_secret(hs, b"s hs traffic", hello)
master = hkdf_extract(derive_secret(hs, b"derived", b""), zero)
full = hello + b"...server Finished"
c_ap = derive_secret(master, b"c ap traffic", full)
s_ap = derive_secret(master, b"s ap traffic", full)
for name, sec in [("client handshake traffic", c_hs), ("server handshake traffic", s_hs),
                  ("client application traffic", c_ap), ("server application traffic", s_ap)]:
    key = hkdf_expand_label(sec, b"key", b"", 16); iv = hkdf_expand_label(sec, b"iv", b"", 12)
    print(f"{name:27} key {key.hex()[:16]}...  iv {iv.hex()[:12]}...")
fin = hkdf_expand_label(s_hs, b"finished", b"", HASH_LEN)
print("server Finished = HMAC(finished_key, H(transcript)):", hmac.new(fin, H(hello + b"...CertificateVerify").digest(), H).hexdigest()[:24], "...")
early secret  : 33ad0a1c607ec03b09e6cd9893680ce210adf300aa1f2660e1b22e10f170f92a
matches RFC 8448: True
derived       : 6f2615a108c702c5678f54fc9dbab697 ...
matches RFC 8448: True
client handshake traffic    key c920fc1e5e8798d0...  iv f4d975b3917a...
server handshake traffic    key 2da1f9910d76cd77...  iv b2f4fc7002ee...
client application traffic  key 9b8c6e68f83a824a...  iv a04f41eb83ae...
server application traffic  key d102a13fb240e7f9...  iv f7936ab69f25...
server Finished = HMAC(finished_key, H(transcript)): 63feff58eb3b1a8049e1aa9d ...

Four unrelated-looking keys from one shared secret, each with its own 12-byte IV. Per record, TLS 1.3 XORs that IV with the 64-bit record sequence number to form the AEAD nonce, so nonces never repeat within a key and never need to be sent.

The key log: a debugging tool and a risk

Clients can write their traffic secrets to a file in the SSLKEYLOGFILE format (browsers and curl honour the environment variable; openssl s_client has -keylogfile). Wireshark reads the file and decrypts a capture of the same connection. The session shows which secrets the client logged for one handshake, labels only; the values are secrets and are never printed.

bash · try it yourself
P=$SAMPLES/pki
openssl s_server -accept 127.0.0.1:8443 -cert $P/lab.test.crt -key $P/lab.test.key -quiet >/dev/null 2>&1 &
for i in $(seq 50); do ss -Htln 'sport = :8443' | grep -q . && break; sleep 0.1; done
openssl s_client -connect 127.0.0.1:8443 -servername lab.test -CAfile $P/ca.crt -brief -keylogfile keys.log </dev/null 2>&1
echo "--- secrets the client derived (labels only; the values are secret):"
cut -d' ' -f1 keys.log
echo "--- force TLS 1.3 with ChaCha20-Poly1305:"
openssl s_client -connect 127.0.0.1:8443 -servername lab.test -CAfile $P/ca.crt -tls1_3 -ciphersuites TLS_CHACHA20_POLY1305_SHA256 -brief </dev/null 2>&1 | grep -E 'Protocol|Ciphersuite'
kill %1
CONNECTION ESTABLISHED
Protocol version: TLSv1.3
Ciphersuite: TLS_AES_256_GCM_SHA384
Peer certificate: C = XX, O = ExcelTAD Lab, OU = Web, CN = lab.test
Hash used: SHA256
Signature type: RSA-PSS
Verification: OK
Server Temp Key: X25519, 253 bits
--- secrets the client derived (labels only; the values are secret):
#
SERVER_HANDSHAKE_TRAFFIC_SECRET
EXPORTER_SECRET
SERVER_TRAFFIC_SECRET_0
CLIENT_HANDSHAKE_TRAFFIC_SECRET
CLIENT_TRAFFIC_SECRET_0
--- force TLS 1.3 with ChaCha20-Poly1305:
Protocol version: TLSv1.3
Ciphersuite: TLS_CHACHA20_POLY1305_SHA256

The five labels are the outputs of the schedule above (_0 is the first generation of application keys; KeyUpdate would produce _1). Anyone who holds this file and a capture can decrypt the session, so a key log is as sensitive as the traffic itself.

How key-derivation problems are detected

  • Key logs where they don't belong: SSLKEYLOGFILE set in production environments, container images, CI runners or shell profiles; key-log files on disk. EDR and configuration audits can check for the variable.
  • Custom protocols that use a DH output or a password directly as a key, reuse one key for both directions, or derive keys without binding the transcript.
  • Ad-hoc KDFs: sha256(shared_secret), key = secret[:16], md5(password) as a key.

How it is fixed

  • Use HKDF (or the protocol's standard KDF) with distinct labels per key and per direction, and include a transcript or context hash.
  • Use separate keys for each direction and purpose; derive nonces from counters as TLS does.
  • Allow key logging only in development and for named debug sessions; scan for it elsewhere.

Pitfalls

  • Using HKDF on a password: HKDF is fast, so it gives no protection against guessing. Passwords need Argon2id or scrypt (Password Storage).
  • Skipping Extract on non-uniform inputs; skipping labels "because there's only one key for now".
  • Treating exported keying material (RFC 5705/8446 exporters) as shareable: it is secret, and channel bindings built on it must stay inside the protocol.

Practice

1. Why does changing one byte of the ServerHello change the client's application traffic key?

The application secrets are derived with the hash of the transcript up to the server's Finished, which includes the ServerHello; any change gives a different hash and therefore different keys (and the Finished check fails first).

2. In the example, change the label b"key" to b"keys". What happens and why does it matter for interoperability?

Every key changes completely. Labels are part of the specification; implementations must use them byte for byte, which is also what makes keys for different purposes independent.

3. A developer sets SSLKEYLOGFILE=/tmp/keys in a production Dockerfile to debug an issue. What is the risk?

Every TLS session's secrets from that container are written to a file. Anyone with the file and captures (or access to the host) can decrypt the traffic, which removes forward secrecy in practice. Remove the variable and the file; treat the period as exposed.

Test yourself

What are HKDF's two steps?

  1. Encrypt and decrypt
  2. Extract and Expand
  3. Sign and verify
  4. Hash and salt

Why are the TLS 1.3 handshake keys bound to the transcript hash?

  1. To make them shorter
  2. So any tampering with the hello messages produces different keys
  3. To compress the handshake
  4. To allow 0-RTT

What could someone do with an SSLKEYLOGFILE and a packet capture of the same session?

  1. Nothing, the keys are hashed
  2. Decrypt the recorded TLS session
  3. Forge the server certificate
  4. Recover the server's private key

How does TLS 1.3 make per-record AEAD nonces unique?

  1. Random nonces in every record
  2. The 12-byte IV from the key schedule XORed with the record sequence number
  3. A timestamp
  4. The nonce is the record length