Cryptographic Protocol Design and Analysis Questions
Designing and reasoning about cryptographic protocols and secure channels: how message flows, key-exchange handshakes, and end-to-end encryption systems are constructed so that composing individual primitives yields a provably or informally verified secure whole. Covers authentication and key-exchange protocol design (mutual authentication, forward secrecy, key confirmation, key-compromise-impersonation resistance), message-flow and state-machine security, formal and informal protocol verification (BAN logic, symbolic tools such as ProVerif and Tamarin, game-based reduction proofs), protocol-level vulnerability analysis (downgrade, replay, padding-oracle, algorithm-confusion attacks), TLS handshake and key-schedule internals, and end-to-end encryption system design (ratcheting, group key agreement, key transparency, post-compromise security). This is the design and analysis layer: why a protocol construction is secure, not which library call or key-management process to run in production. Distinct from selecting and operating cryptographic primitives day to day (certificate lifecycle management, TLS deployment monitoring and incident response, key rotation operations, algorithm and parameter selection for a given constraint set), which belongs to applied cryptography and key management; from core cryptographic vocabulary and primitive fundamentals; and from implementation-level bugs (side-channel leakage, memory-safety flaws, timing attacks in code), which belong to cryptographic implementation security.
Analyze the FREAK vulnerability at a high level: explain the chain of issues that allowed clients and servers to fall back to weak 'export' RSA cipher suites, how a protocol-level analysis would detect susceptibility, and describe short- and long-term mitigations an operator should apply.
Sample Answer
Direct answer
FREAK ("Factoring RSA Export Keys") worked because three separate weaknesses lined up: a 1990s US export-control-era cipher suite that deliberately used weak, factorable 512-bit RSA keys was still implemented (and in some cases offered) by servers decades after export controls were lifted; many TLS (Transport Layer Security) client implementations had a bug that let an active MITM (man-in-the-middle, an attacker positioned between client and server) force that weak suite onto the connection even when the client never offered it; and once forced, a 512-bit RSA modulus was small enough for a well-resourced attacker to factor and recover the session's temporary key within a useful window, letting them decrypt the session or impersonate the server.
Structured elaboration
The chain of issues, in order:
- Legacy weak suites never removed. "RSA_EXPORT" cipher suites, originally required by 1990s US export law to use RSA keys of 512 bits or less, remained implemented in both client and server TLS stacks for backward compatibility long after the legal restriction was lifted.
- Missing negotiation-integrity check on the client. A correctly implemented client should never accept a ServerKeyExchange for an export-strength suite it did not itself offer. Several widely deployed TLS libraries were missing exactly that check, so a MITM could rewrite the negotiated suite (or otherwise trick the client's state machine) into accepting export-grade RSA parameters mid-handshake, without the client having asked for them.
- Weak modulus, feasible factoring. A 512-bit RSA modulus is small enough that general number field sieve factoring (the standard algorithm for factoring large composite numbers) has been within reach of well-resourced attackers since well before the vulnerability was disclosed; by the time cloud computing made that kind of compute broadly rentable, the threshold for "who can factor it" dropped substantially.
How a protocol-level analysis detects susceptibility: enumerate every cipher suite a server will actually negotiate (not just what a compliance document claims) and flag any suite whose name contains EXPORT; separately, drive a client implementation through a handshake and confirm it rejects (rather than silently accepts) a ServerKeyExchange for a suite outside the list it originally offered, since that missing check is the actual enabling bug, not merely the presence of a weak suite on the server.
Short-term mitigations: disable EXPORT-grade RSA and DHE cipher suites on every server and load balancer immediately; patch or upgrade any TLS client library known to be missing the "only accept what I offered" check; monitor for anomalous export-suite negotiation attempts as a detection signal in the interim.
Long-term mitigations: remove the legacy code paths entirely rather than special-casing them off by configuration, since a configuration flag can be silently reverted or missed on a new deployment; migrate toward TLS 1.3, which removed static RSA key exchange (and therefore this entire class of export-suite weakness) from the protocol altogether rather than relying on operators to keep disabling it correctly.
Worked example
The core lesson generalizes past FREAK specifically: any handshake step whose outcome is not covered by the connection's own authentication can be silently steered by an active attacker. Here, the choice of cipher suite was exactly such a step, negotiated in the clear early in the handshake and, due to the client-side bug, not actually held to "must be one of what I offered." That is structurally the same downgrade pattern later formalized as the FREAK/Logjam/DROWN family, and it is exactly why TLS 1.3 added an explicit downgrade-detection mechanism (a sentinel value the server embeds in its random field when it detects it is talking to a client that is being forced to negotiate an older protocol version) rather than relying purely on removing individual weak suites one at a time.
Trade-offs and pitfalls
- Keeping any export-grade or otherwise deliberately-weakened suite "for legacy compatibility" recreates this exact failure pattern; the fix that actually worked was removing the code path, not disabling it by policy, because policy can regress.
- Treating FREAK as "a server bug" misses two-thirds of the chain: a server offering only strong suites is still exploitable against a client with the missing negotiation-integrity check, so remediation has to cover both the server's offered suite list and every client implementation's handshake validation, not just one side.
Define forward secrecy and post-compromise security. Give concrete examples of protocol mechanisms that provide forward secrecy and explain what extra mechanisms are required to achieve post-compromise recovery in asynchronous messaging systems.
Sample Answer
Direct answer
Forward secrecy means that if an attacker compromises a party's long-term (identity) key today, they still cannot decrypt session traffic that was already exchanged in the past, because each past session used its own independent, ephemeral secret that was discarded after use and is not derivable from the long-term key alone. Post-compromise security (PCS, sometimes called future secrecy or self-healing) is the complementary property for ongoing conversations: even if an attacker fully compromises a party's current session state, right now, the protocol can automatically restore confidentiality and authenticity for future messages once fresh randomness is contributed again by an honest party, without any manual re-keying ceremony.
Structured elaboration
Mechanisms that provide forward secrecy: the common thread is a fresh, ephemeral Diffie-Hellman (DH) exchange per session (or per meaningful unit of the conversation) whose private half is deleted right after the shared secret is computed. TLS 1.3 mandates ephemeral (EC)DHE for every handshake, so compromising the server's long-term certificate signing key later does not expose any past session's traffic, since that key was never used to encrypt anything, only to authenticate the ephemeral exchange. Signal's Double Ratchet gets the same property at finer granularity through its DH ratchet, generating a fresh key pair every time the conversation changes direction.
What post-compromise security adds, and why it needs more than forward secrecy alone. Forward secrecy is a one-directional guarantee about the past: a future key compromise cannot reach backward. PCS is about the future: a compromise right now should not permanently compromise everything that comes after it. In a live, interactive protocol like a single TLS connection, this is almost free, since the next connection is simply a brand-new handshake with fresh ephemeral keys, so as long as the attacker is not actively intercepting every subsequent handshake too, the next session already "heals" on its own. The harder case is exactly what the question asks about: asynchronous messaging, where a recipient may be offline for hours or days, so there is no live round trip available to run a fresh interactive DH exchange the moment a message needs to be sent.
Extra mechanisms asynchronous systems need for PCS:
- Pre-published key material for the first message. Signal's X3DH (Extended Triple Diffie-Hellman) initial key agreement lets a sender establish a session with an offline recipient by combining the sender's own ephemeral key with several of the recipient's keys published in advance to a server (a signed identity key, a signed prekey, and a one-time prekey), so the very first message can already carry forward-secrecy-relevant freshness without either party being online simultaneously.
- Per-direction-turn DH contributions embedded in message headers, which is what the Double Ratchet's DH ratchet actually is: instead of needing a live round trip to exchange fresh public values, each party simply attaches its newly generated public key to the next message it sends, and the recipient incorporates it into the root-key derivation the next time it processes a message in that direction. This is what lets healing happen asynchronously, the fresh randomness rides along with ordinary message traffic instead of requiring a dedicated handshake.
- Continuous, per-message forward erasure, not just per-session: the symmetric-key ratchet derives and then immediately deletes a one-time message key for every single message, so even within one ongoing conversation (not just between separate sessions), an attacker who captures the current chain key cannot retroactively recover any already-processed message's key.
Worked example
Concretely: suppose an attacker fully compromises Bob's device the moment after he receives a message from Alice, capturing his current root key and chain keys. Bob has not yet sent anything back. As soon as Bob does reply, his client generates a brand-new DH key pair (this is the "healing" event), computes a fresh root key by combining that new private key with Alice's last-known public key, and Alice, on receiving Bob's reply, does the matching computation with her own keys to arrive at the identical new root key. The attacker, holding only Bob's OLD private DH key (deleted by then) and the compromised chain state, cannot reconstruct Bob's NEW private key, since it was generated fresh and independently, so the conversation's confidentiality is restored for everything from that reply onward, even though the compromise itself was never detected or remediated out of band.
Trade-offs and pitfalls
PCS is not free: it requires both sides to actually keep contributing fresh randomness through normal use (a conversation where one party only ever receives and never replies never triggers a DH ratchet turn on their side, so healing on that side is delayed until they do send something). It also does not protect a message that was already decrypted and is sitting in plaintext in a compromised device's memory or storage; PCS is a property of the key-management protocol, not of what an application does with the plaintext afterward. A common confusion in interviews is treating forward secrecy and PCS as the same guarantee stated twice, they are time-symmetric opposites (protects the past vs. heals the future), and a protocol can have one without the other, static-key protocols have neither, plain ephemeral-DH-per-session protocols like a single TLS connection have forward secrecy but no meaningful PCS concept within that one connection, and it takes the asynchronous-compatible ratchet construction above to get PCS in a system where parties cannot assume a live round trip.
You are auditing a protocol that uses ephemeral Diffie-Hellman for key agreement but omits any form of authentication for the DH public values. Sketch likely man-in-the-middle and downgrade attacks and propose concrete protocol fixes including authentication methods and recommended parameter choices for groups or curves.
Sample Answer
Direct answer
Ephemeral Diffie-Hellman (DH, a key-agreement method where both sides combine their own private value with the other's public value to reach a shared secret) without authentication gives you a shared secret with whoever you actually exchanged messages with, but it never proves who that was, so an active man-in-the-middle (MITM) can simply run two independent DH exchanges, one with each side, relaying nothing but its own substituted public values, and end up holding both resulting shared secrets while both victims believe they are talking directly to each other. The fix is not a stronger DH group by itself, it is binding each side's DH public value to a verifiable identity, typically a signature under a long-term key that both sides trust out of band.
Structured elaboration
The MITM attack. Call the two legitimate parties Alice and Bob, and the attacker Mallory. Alice computes her ephemeral DH key pair and sends her public value A, intending it for Bob. Mallory intercepts it, generates her own private value m1, and forwards M1=gm1modp to Bob in place of A. Bob computes his shared secret using M1, believing it came from Alice. Symmetrically, Mallory generates a second private value m2, sends M2 to Alice in place of Bob's real public value B, and Alice computes a shared secret with M2. Mallory now independently computes both shared secrets herself (Am1modp matching Alice's side, Bm2modp matching Bob's side), so she can decrypt, read, modify, and re-encrypt every message flowing in either direction, while Alice and Bob each believe they have a private channel with each other. Nothing about the DH math itself is broken, the group and exponents can be as large and well-chosen as you like; the vulnerability is that neither side had any way to verify whose public value they actually received.
Downgrade risk compounds this. Even once authentication is added, if the protocol allows negotiating the DH group or the authentication mechanism itself, an attacker who can still influence the negotiation (before authentication is established) can try to steer both sides toward the weakest mutually-supported group or a cipher suite with known weaknesses, which is why parameter/algorithm negotiation generally needs to be covered by the same authentication that covers the key exchange, not left for later.
Concrete fixes:
- Authenticate the DH public values themselves. Have each party sign their DH public value, plus enough context (a nonce, the peer's identity, the negotiated parameters) to prevent replay, using a long-term identity key whose authenticity is established independently, for example via a certificate chain to a trusted CA (Certificate Authority), a pre-shared identity key, or a manually pinned public key. This is exactly what TLS's ECDHE (Elliptic-Curve Diffie-Hellman Ephemeral) key exchange does: the server signs the ephemeral key-exchange parameters with its certificate's private key in the
CertificateVerifymessage, so a client that trusts the certificate chain can detect a substituted ephemeral public value. - Bind the signature to the full transcript, not just the DH value in isolation, so an attacker cannot splice a validly-signed public value from one exchange into a different one.
- Use a modern, well-vetted group or curve, not because it fixes the authentication gap, but because a weak group (a short classical modulus, or a non-standard curve without proper validation) opens a separate, compounding weakness: 2048-bit or larger finite-field groups from RFC 7919, or elliptic curves like X25519, are the current baseline; a small legacy DH group is what made the (separately covered) Logjam-class attacks practical even in protocols that did have authentication elsewhere.
Worked example
Using a deliberately tiny (insecure-size, illustrative only, real deployments use groups of 2048+ bits or curves like X25519) group so the arithmetic fits on one line, p=23, g=5:
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
p, g = 23, 5 # toy group, NOT cryptographically sized
def dh_public(priv): return pow(g, priv, p)
def dh_shared(pub, priv): return pow(pub, priv, p)
a, b = 6, 15 # Alice's and Bob's real ephemeral private values
m1, m2 = 3, 11 # Mallory's two private values (Alice-facing, Bob-facing)
A, B = dh_public(a), dh_public(b)
M1, M2 = dh_public(m1), dh_public(m2) # what Mallory forwards instead
alice_shared = dh_shared(M1, a)
mallory_alice_side = dh_shared(A, m1)
bob_shared = dh_shared(M2, b)
mallory_bob_side = dh_shared(B, m2)
print(f"Alice/Mallory match: {alice_shared == mallory_alice_side}")
print(f"Bob/Mallory match: {bob_shared == mallory_bob_side}")
print(f"Alice and Bob share the same secret: {alice_shared == bob_shared}")
# --- fix: sign the DH public value + transcript under a long-term identity key ---
bob_identity_key = Ed25519PrivateKey.generate()
transcript = f"A={A}".encode()
signature = bob_identity_key.sign(str(B).encode() + b"|" + transcript)
bob_public_signing_key = bob_identity_key.public_key() # pinned/certified out of band
def verify(claimed_B, sig, transcript, signer_pub):
try:
signer_pub.verify(sig, str(claimed_B).encode() + b"|" + transcript)
return True
except Exception:
return False
print("real B, real signature:", verify(B, signature, transcript, bob_public_signing_key))
print("Mallory's M2, Bob's real signature over B:", verify(M2, signature, transcript, bob_public_signing_key))
Output (actually executed):
Alice/Mallory match: True
Bob/Mallory match: True
Alice and Bob share the same secret: False
real B, real signature: True
Mallory's M2, Bob's real signature over B: False
Unauthenticated: Mallory successfully derives both sides' secrets, and Alice and Bob end up with two different, unrelated secrets despite believing they share one. Authenticated: Bob's signature was computed over his real public value B; presenting Mallory's substituted M2 against that same signature fails verification immediately, exactly the point where the attack is stopped.
Trade-offs and pitfalls
Signing the DH exchange only helps if the verifier actually has a trustworthy way to obtain the signer's long-term public key in the first place, trust-on-first-use or an unpinned, unvalidated certificate chain just relocates the same MITM problem one level up rather than solving it. Authenticating only one side (as in typical one-way TLS, where the server authenticates but the client does not) stops a MITM from impersonating the server but leaves client impersonation possible unless something else authenticates the client, which is exactly the gap mutual TLS closes. Finally, authentication and parameter negotiation must be covered by the same protected exchange; authenticating the DH value while leaving group or cipher-suite selection unauthenticated and negotiable in the clear reopens a downgrade path even though the key exchange itself is now signed.
Analyze the practical impact of the Logjam attack (weak DH parameters) combined with an infrastructure that still accepts export-grade or small-group DH. For a large organization, propose detection rules, short-term mitigations, and a prioritized remediation roadmap to eliminate weak DH usage across services and clients.
Sample Answer
Direct answer
Logjam (2015) combined a downgrade attack with a precomputation attack: it forced TLS (Transport Layer Security) connections down to export-grade Diffie-Hellman (DH), a deliberately weakened 512-bit key-exchange group left over from 1990s cryptography export restrictions, and exploited the fact that many servers reused the same small set of well-known DH primes, letting an attacker do the expensive part of breaking discrete logarithms for a given prime once, then break any individual connection using that prime cheaply and repeatedly afterward. The organizational response is a two-track roadmap: eliminate export-grade and small-group DH everywhere immediately, and separately track down and replace any remaining shared, non-unique DH primes, since either weakness alone is enough to make this attack practical.
Structured elaboration
How the attack works. TLS historically supported *_DHE_EXPORT cipher suites, a relic of US export-control rules that once restricted the strength of cryptography allowed in software shipped outside the country, forcing a small (512-bit) DH group. Even servers that no longer intended to actually use these suites often still had them enabled. An active attacker performing a man-in-the-middle (MITM) could rewrite the cipher suite list in a client's ClientHello to make it look like export-grade DHE was the only option, causing the server to negotiate the weak group even though both real endpoints supported something much stronger, the downgrade half of the attack. The precomputation half exploits a separate, compounding weakness: generating a fresh, safe DH prime is computationally expensive, so many implementations, and in particular many servers, shipped with the same small set of hard-coded, widely reused primes. The Number Field Sieve (NFS), the best known classical algorithm for computing discrete logarithms in this kind of group, has an expensive one-time precomputation phase that depends only on the prime itself, not on any particular connection; once that precomputation is done for a specific, widely-shared prime, computing any individual connection's discrete logarithm (and therefore its DH shared secret) using that same prime becomes comparatively cheap. Reusing the same prime across a huge number of deployments is exactly what turns a merely-expensive attack into one worth mounting at all, the cost is paid once and amortized across every server sharing that prime.
Detection. Fleet-wide TLS scanning for any negotiable *_DHE_EXPORT cipher suite, since offering it at all is the precondition for the downgrade half of the attack regardless of whether a legitimate client would ever choose it. Separately, scanning the actual DH group size (p) offered in non-export DHE negotiations and flagging anything below 2048 bits, and comparing offered primes against a known list of common, non-unique DH primes (the ones shipped as defaults in widely used server software), since a server using one of those, even at a larger bit size, inherits the same amortized-precomputation risk as export-grade DH does at a smaller one.
Short-term mitigations. Disable *_EXPORT cipher suites entirely in the server's TLS configuration, this removes the downgrade target outright and requires no code change. Require any remaining DHE groups to be at least 2048 bits, and prefer switching to elliptic-curve Diffie-Hellman (ECDHE) with a modern curve, or to the standardized finite-field groups defined in RFC 7919, both of which are large, well-vetted, and shared broadly enough by design that there is no incentive or ability for an attacker to precompute against one organization's bespoke small group.
Prioritized remediation roadmap:
- Immediate (config-only, no code change): disable export cipher suites fleet-wide via a policy push, closing the acute exposure the same day it is found.
- Short-term: inventory every remaining service still offering DH groups below 2048 bits, and migrate them to either ECDHE or an RFC 7919 standardized group; treat any custom, locally-generated DH parameters as suspect until confirmed unique and adequately sized.
- Medium-term: move affected services to TLS 1.3, which structurally removes export ciphers from the protocol and mandates modern (EC)DHE groups only, so the whole attack class becomes unavailable by protocol design rather than by configuration discipline.
- Ongoing: fold the weak-DH and export-cipher checks into recurring, automated external TLS scanning, so a regression, for example a newly deployed load balancer shipped with legacy defaults re-enabled, is caught automatically rather than by the next external audit.
Worked example
A large organization runs external TLS scanning across its public-facing fleet and finds that 40 of 300 scanned endpoints still offer at least one *_DHE_EXPORT suite, most of them older internal tools that were never explicitly configured, they simply inherited an old default TLS configuration template. Cross-referencing the non-export DHE groups offered by the remaining 260 endpoints against a list of known common DH primes shows 15 endpoints using one specific 1024-bit prime that ships as the default in a popular, older web-server package. The prioritized roadmap above would push the fix for the 40 export-suite endpoints to the top (config-only, same-day), and separately schedule the 15 shared-prime endpoints for a parameter regeneration or ECDHE migration in the short-term track, since neither weakness depends on the other to be exploitable.
Trade-offs and pitfalls
It is tempting to treat "increase the DH group size" as the whole fix, but a large, UNIQUE, freshly-generated prime is not the same mitigation as a large, WIDELY-SHARED one, size alone does not remove the amortized-precomputation incentive if thousands of other deployments use the identical prime; the standardized RFC 7919 groups solve this by being large enough that even shared, well-known use is not practically exploitable, rather than by being secret or unique. A second pitfall is treating this purely as a detection problem: a scanner that only checks for export suites and misses the separate small-or-shared-prime issue will report a fleet as clean while it is still carrying the compounding weakness that made Logjam practical at scale in the first place.
Explain the TLS 1.3 key schedule end-to-end: define early_secret, handshake_secret, master_secret, and the derivation of handshake and application traffic secrets. Describe how HKDF-Extract and HKDF-Expand-Label are used at each stage and how the transcript hash binds the handshake to keys.
Sample Answer
Direct answer
TLS (Transport Layer Security, the protocol that secures HTTPS and most other encrypted internet traffic) 1.3's key schedule is a single pipeline built out of HKDF (HMAC-based Key Derivation Function) calls, chained through three intermediate secrets, an early secret, a handshake secret, and a master secret. Each intermediate secret is not used directly; it is fed into HKDF-Expand-Label to derive the actual traffic secrets, and every one of those derivations also mixes in a running hash of the real handshake messages exchanged so far (the transcript hash), which is what ties the resulting keys to this specific handshake and makes them unusable if any earlier message was tampered with or swapped in from a different session.
Structured elaboration
HKDF has two primitives, and the schedule uses both for different jobs:
- HKDF-Extract(salt, IKM) -> PRK: takes input keying material that may not be uniformly random (a shared secret, a pre-shared key, or literally all-zeros) and concentrates it into a uniform pseudorandom key (PRK), computed as HMAC-Hash(salt, IKM).
- HKDF-Expand(PRK, info, L) -> OKM: stretches a PRK into as much output keying material as needed, bound to a context string
info. - HKDF-Expand-Label(Secret, Label, Context, Length): TLS 1.3's labeled wrapper around Expand. It builds
infofrom a fixed structure (a 2-byte length, the label prefixed with"tls13 ", and a context byte string), so two calls with different labels or different transcript hashes as Context always produce independent outputs even from the same Secret. - Derive-Secret(Secret, Label, Messages) = HKDF-Expand-Label(Secret, Label, Hash(Messages), Hash.length): the actual helper used throughout the schedule, where
Messagesis the relevant slice of the handshake transcript.
The three stages:
- Early Secret = HKDF-Extract(salt = 0, IKM = the pre-shared key, or an all-zero string if there is none). This feeds any 0-RTT (zero round-trip-time, meaning the client can send encrypted application data in its very first flight) traffic keys, and also produces
Derive-Secret(EarlySecret, "derived", ""), which becomes the salt for stage 2. Reusing an Extract output as the next stage's salt is what turns three separate HKDF calls into a one-way chain. - Handshake Secret = HKDF-Extract(salt = that derived-early value, IKM = the (EC)DHE shared secret from the key exchange). From this,
client_handshake_traffic_secretandserver_handshake_traffic_secretare each Derive-Secret with labels"c hs traffic"/"s hs traffic"and Context = the transcript hash covering ClientHello through ServerHello. These keys encrypt EncryptedExtensions, Certificate, CertificateVerify, and Finished. - Master Secret = HKDF-Extract(salt = Derive-Secret(HandshakeSecret, "derived", ""), IKM = an all-zero string). From this,
client_application_traffic_secret_0/server_application_traffic_secret_0are Derive-Secret with labels"c ap traffic"/"s ap traffic"and Context = the transcript hash covering the full handshake up through the server's Finished message. These derive the actual record-protection keys used for application data.
Transcript binding, mechanically: the Context argument to nearly every Derive-Secret call is a hash of the concatenated handshake messages seen so far. Because that hash covers every negotiated parameter and every prior message byte-for-byte, changing even one bit of one earlier message, or splicing in a message from a different handshake, changes the hash and therefore changes every key derived afterward. The Finished message (a MAC computed with a further Derive-Secret over that same transcript hash) is the explicit checkpoint where both sides prove they computed an identical transcript before any application data is exchanged.
Worked example
Running the real derivation with pinned, synthetic inputs (not a captured handshake, chosen only so the arithmetic is reproducible):
import hashlib, hmac
HASH = hashlib.sha256
HASH_LEN = HASH().digest_size # 32
def hkdf_extract(salt: bytes, ikm: bytes) -> bytes:
if salt == b"":
salt = b"\x00" * HASH_LEN
return hmac.new(salt, ikm, HASH).digest()
def hkdf_expand(prk: bytes, info: bytes, length: int) -> bytes:
t, okm, counter = b"", b"", 1
while len(okm) < length:
t = hmac.new(prk, t + info + bytes([counter]), HASH).digest()
okm += t
counter += 1
return okm[:length]
def hkdf_expand_label(secret: bytes, label: str, context: bytes, length: int) -> bytes:
full_label = b"tls13 " + label.encode()
hkdf_label = (length.to_bytes(2, "big")
+ len(full_label).to_bytes(1, "big") + full_label
+ len(context).to_bytes(1, "big") + context)
return hkdf_expand(secret, hkdf_label, length)
def derive_secret(secret: bytes, label: str, transcript_hash: bytes) -> bytes:
return hkdf_expand_label(secret, label, transcript_hash, HASH_LEN)
zero_ikm = b"\x00" * HASH_LEN
psk = b"\x00" * HASH_LEN # no external PSK -> zero string
dhe_shared_secret = bytes(range(HASH_LEN)) # stand-in for a real (EC)DHE output
empty_th = HASH(b"").digest()
ch_sh_th = HASH(b"ClientHello||ServerHello-synthetic-transcript").digest()
full_th = HASH(b"full-handshake-synthetic-transcript").digest()
early_secret = hkdf_extract(salt=b"", ikm=psk)
handshake_secret = hkdf_extract(salt=derive_secret(early_secret, "derived", empty_th), ikm=dhe_shared_secret)
client_hs_traffic_secret = derive_secret(handshake_secret, "c hs traffic", ch_sh_th)
master_secret = hkdf_extract(salt=derive_secret(handshake_secret, "derived", empty_th), ikm=zero_ikm)
client_app_traffic_secret = derive_secret(master_secret, "c ap traffic", full_th)
print("early_secret =", early_secret.hex()[:16], "...")
print("handshake_secret =", handshake_secret.hex()[:16], "...")
print("c_hs_traffic =", client_hs_traffic_secret.hex()[:16], "...")
print("master_secret =", master_secret.hex()[:16], "...")
print("c_ap_traffic =", client_app_traffic_secret.hex()[:16], "...")
Output (actually executed):
early_secret = 33ad0a1c607ec03b ...
handshake_secret = ddbe37614d014a8c ...
c_hs_traffic = 852fe0085c54fa15 ...
master_secret = 055796c9a2f048dd ...
c_ap_traffic = 60eee21029d2e538 ...
Every value above is fully determined by the pinned psk, dhe_shared_secret, and the three synthetic transcript hashes; rerunning the exact code reproduces the exact same hex every time, which is the point: nothing in the key schedule depends on hidden randomness once the (EC)DHE exchange and the transcript are fixed.
Trade-offs and pitfalls
Because each stage's salt is itself an output of the previous stage's Extract, the chain only runs forward: recovering the master secret gives no way back to the handshake secret or early secret, since HMAC is not invertible. Combined with an ephemeral (EC)DHE shared secret that is discarded once the handshake finishes, this is the structural basis for forward secrecy, meaning a later compromise of the server's long-term certificate key cannot decrypt this session's recorded traffic. A common implementation bug is hashing the wrong slice of the transcript for a given Derive-Secret call (RFC 8446 pins exactly which messages are covered at each point); the HKDF arithmetic will run fine but the two sides silently desync. Mid-connection rekeying (KeyUpdate) reuses this same Derive-Secret machinery on the current application traffic secret rather than restarting all three stages, which is cheap but means it only protects future traffic relative to a key compromise, it is not a substitute for a fresh handshake if the long-term identity key itself is suspected to be compromised.
Unlock Full Question Bank
Get access to all 21 Cryptographic Protocol Design and Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.