Asymmetric Encryption and Key Exchange Questions
The construction and mathematics-adjacent mechanics of public-key (asymmetric) cryptography: how RSA, Diffie-Hellman, and elliptic-curve schemes actually work, including the group law and point-arithmetic formulas, scalar-multiplication algorithms (double-and-add, Montgomery ladder, windowed methods, GLV, multi-scalar batching), curve models and coordinate systems, and the hardness assumptions (integer factorization, discrete log, ECDLP) each scheme rests on. Covers key-establishment and authenticated key-exchange protocol design: forward-secrecy mechanics, key confirmation, downgrade protection, key-derivation and context binding, group and multi-party key agreement, and hybrid classical/post-quantum key-exchange composition. Also covers implementation-level attacks against these primitives and their mitigations: timing and side-channel leakage in modular exponentiation and scalar multiplication, invalid-curve and small-subgroup attacks, fault attacks, and padding-oracle attacks. Distinct from selecting, deploying, and operating these primitives in production: PKI certificate lifecycle, CA hierarchy, revocation, and key storage and rotation belong to applied cryptography and key management.
What is key confirmation in a key-exchange protocol? Give two mechanisms for mutual key confirmation (for example, a MAC over the transcript using the derived key, and an explicit signature over the key material) and explain how key confirmation prevents certain active and reflection attacks.
Sample Answer
Direct answer
Key confirmation is the step, after a key-agreement protocol has produced a shared secret, where each party proves to the other it actually holds a matching copy of that secret. It closes the gap between "we agreed on some value" and "we agreed on the same value, with the party we think we're talking to."
Structured elaboration
Why agreement alone isn't enough. A Diffie-Hellman-style exchange can complete successfully and still leave open questions neither side can otherwise answer: did the values actually reach the intended peer unmodified, and did the peer derive the exact same key bytes? Even under an authenticated key exchange (AKE, one where the exchanged public values are tied to verified identities), a subtle protocol bug or role-confusion issue can still leave two parties holding different derived keys without either one noticing until something later fails to decrypt.
Mechanism 1: MAC over the transcript. Each side computes a message authentication code (MAC) keyed by the derived secret, over the full handshake transcript plus a role identifier: MACK(transcript∥role), and sends it to the peer. The peer recomputes the same value independently and compares; a match proves possession of K and confirms the transcript wasn't tampered with along the way.
Mechanism 2: explicit signature over the key material. Each party signs a message covering the session's key material or transcript with its own long-term signing key: Sigsk("confirm"∥K∥transcript). This ties key possession to a pre-existing, externally verified identity rather than relying solely on a freshly derived MAC key.
Preventing reflection attacks. A reflection attack works by taking one party's own outgoing confirmation message and replaying it straight back at them, hoping they'll accept it as if it came from the peer. Including an explicit role identifier (literally "initiator" or "responder", or each party's own identity) inside the MAC or signature input defeats this directly: a reflected message carries the wrong role tag and fails verification.
Preventing active tampering. Because the confirmation value depends on the entire transcript, every negotiated parameter, nonce, and exchanged public value, any active tampering earlier in the handshake changes the transcript and therefore changes the expected confirmation value. An attacker who tampered without knowing the derived key cannot produce a matching confirmation, so the honest party detects the mismatch and aborts.
Worked example
import hmac, hashlib
K = bytes.fromhex("5f" * 32) # the derived session key both sides should now share
transcript = b"pinned-illustrative-transcript-nonceA-nonceB-pubA-pubB"
mac_responder = hmac.new(K, transcript + b"|responder", hashlib.sha256).digest()
mac_initiator = hmac.new(K, transcript + b"|initiator", hashlib.sha256).digest()
print("MAC_K(transcript || \'responder\') =", mac_responder.hex())
print("MAC_K(transcript || \'initiator\') =", mac_initiator.hex())
print("replaying responder\'s MAC back tagged as initiator verifies:", mac_responder == mac_initiator)
Running this prints:
MAC_K(transcript || 'responder') = 7d07915c8d3f5c69c02fc510798022aa90bc52e7eae461cd40ab5aed9198f709
MAC_K(transcript || 'initiator') = 8343127362cc2e76b6ae51404f15f62132ccb7d210774ee007261554f457d1c1
replaying responder's MAC back tagged as initiator verifies: False
The responder's genuine confirmation value does not match what an initiator-tagged confirmation should be, confirming that an attacker who captures one party's confirmation and tries to replay it back as if it came from the other side is caught immediately, exactly the reflection defense the role tag is there to provide.
Trade-offs and pitfalls
Confirmation has to be mutual: if only one side confirms, the other side's liveness and identity are never actually proven, and an unbalanced protocol can itself become a new reflection or unknown-key-share vector. Confirmation typically doesn't need an extra round trip, well-designed protocols fold it into a message that was already planned (Transport Layer Security, TLS, is a good example: its Finished messages do exactly this). Confirming too early, before the transcript is fully fixed, defeats the purpose, since any later message wouldn't be covered by the confirmation and could still be tampered with undetected.
A service signs the exact same message under RSA to several different recipients, each with their own public key but the same small exponent e = 3, and without randomized padding. Explain what's wrong with this setup, name the attack it exposes the service to, and what you'd change about the exponent choice or the padding scheme to fix it.
Sample Answer
Direct answer
Broadcasting the identical message under RSA to several recipients, each with a different modulus but the same tiny public exponent e=3, and no randomized padding, lets an attacker who intercepts all the ciphertexts reconstruct the exact integer m3 using the Chinese Remainder Theorem (CRT) and then simply take an integer cube root. No factoring, and no private key, is needed at all. This is Hastad's broadcast attack.
Structured elaboration
For each recipient i, the attacker sees ci=m3modNi. Because the moduli N1,N2,N3 are (with overwhelming probability) pairwise coprime, the Chinese Remainder Theorem guarantees a unique value modulo the product:
M≡m3(modN1N2N3)The key observation is that this is not just "M equals m3 reduced by something", once you have three moduli of similar size and a message small enough that the true integer m3 is already smaller than N1N2N3 (which happens easily in practice, since m3 is one modulus-width and the product of three moduli is roughly three modulus-widths), CRT reconstruction gives back that exact integer, no modular reduction ever occurred. An ordinary integer cube root then recovers m directly:
m=3MWhy the exponent choice alone doesn't fix this. This generalizes to any fixed low exponent broadcast to at least e recipients with distinct, coprime moduli, an unpadded message, no matter what e is, is vulnerable the same way once enough copies are collected; a larger e (like the standard e=65537) just raises the number of colluding ciphertexts an attacker would need from 3 to 65537, astronomically impractical for a real broadcast, but the underlying algebraic weakness, determinism plus no randomization, is exactly the same regardless of e.
Worked example
Three small, distinct moduli, message m=4321, exponent e=3:
import math
def is_prime(n):
if n < 2: return False
for i in range(2, int(math.isqrt(n)) + 1):
if n % i == 0: return False
return True
def crt(residues, moduli):
M = 1
for m in moduli: M *= m
total = 0
for r, m in zip(residues, moduli):
Mi = M // m
total += r * Mi * pow(Mi, -1, m)
return total % M
primes = [p for p in range(200, 400) if is_prime(p)]
chosen = primes[:6]
N1, N2, N3 = chosen[0]*chosen[1], chosen[2]*chosen[3], chosen[4]*chosen[5]
print("moduli: N1=%d N2=%d N3=%d (built from primes %s)" % (N1, N2, N3, chosen))
e = 3
m = 4321 # the SAME plaintext, broadcast to all three recipients, unpadded
c1, c2, c3 = pow(m, e, N1), pow(m, e, N2), pow(m, e, N3)
print("ciphertexts: c1=%d c2=%d c3=%d" % (c1, c2, c3))
M = crt([c1, c2, c3], [N1, N2, N3])
print("CRT-combined value M =", M, " (equals m^3 exactly:", M == m**e, ")")
def integer_cube_root(v):
x = round(v ** (1/3))
for cand in (x-2, x-1, x, x+1, x+2):
if cand**3 == v:
return cand
print("recovered plaintext m =", integer_cube_root(M), " (true m was", m, ")")
Running this prints:
moduli: N1=47053 N2=51983 N3=55687 (built from primes [211, 223, 227, 229, 233, 239])
ciphertexts: c1=23831 c2=4144 c3=24545
CRT-combined value M = 80677568161 (equals m^3 exactly: True )
recovered plaintext m = 4321 (true m was 4321 )
The CRT-combined value comes back exactly equal to 43213, confirming no modular reduction happened, and the integer cube root recovers 4321 precisely. Real RSA moduli run to hundreds of decimal digits rather than five or six, but the attack's mechanics are identical at any size, this is a pure integer/CRT argument, not a size-dependent cryptanalysis.
Trade-offs and pitfalls
The actual fix is randomization, not exponent size: migrate to Optimal Asymmetric Encryption Padding (OAEP), whose random seed makes the padded value different at every recipient even for an identical underlying plaintext, which breaks the CRT reconstruction outright, the values being combined are no longer literally equal across recipients, so there is no single m3 to recover. If changing the padding scheme genuinely isn't an option, moving only to a larger conventional exponent like 65537 is not sufficient by itself, as shown above. The cleanest protocol-level fix is to never encrypt the same payload directly to multiple public keys at all: generate a fresh, unique symmetric session key per recipient and use RSA only to wrap that small, unique key (hybrid encryption), so there is never an identical plaintext to collude across in the first place.
Provide pseudocode for RSA decryption/signing using blinding to mitigate timing attacks. Include steps for selecting the blinding factor, applying the blinding before modular exponentiation, unblinding the result, and constant-time precautions. Also describe how to adapt blinding for CRT-based implementations and how to verify correctness.
Sample Answer
Approach
RSA (Rivest-Shamir-Adleman) blinding defeats timing attacks by making the value the exponentiation routine actually SEES unpredictable to the attacker, while still producing the correct final signature. Pick a random r coprime to the modulus N, transform the message M→M′=M⋅remodN before exponentiating (using the PUBLIC exponent e here), run the normal private-exponent computation S′=(M′)dmodN, then unblind: S=S′⋅r−1modN. Because re⋅r−1⋅(⋅)d algebraically cancels out (the blinding factor's contribution is removable BECAUSE it was applied multiplicatively before an exponentiation, a multiplicative homomorphism), S ends up identical to the unblinded result, even though the exponentiator itself never touched the real message M. This works the same way for a CRT (Chinese Remainder Theorem, the technique that splits the exponentiation into a mod-p and a mod-q half for a speed advantage)-based implementation, blinding the value before it enters either half of the split computation.
# RSA signing/decryption blinding, plain vs CRT, verifying blinding preserves the result.
import math, random
p, q = 61, 53
N, phi = p * q, (p - 1) * (q - 1)
e = 17
d = pow(e, -1, phi)
dp, dq = d % (p - 1), d % (q - 1)
qinv = pow(q, -1, p)
def crt_sign(m):
m1 = pow(m % p, dp, p)
m2 = pow(m % q, dq, q)
h = (qinv * (m1 - m2)) % p
return (m2 + h * q) % N
def blinded_sign(m, rng):
r = rng.randrange(2, N)
while math.gcd(r, N) != 1:
r = rng.randrange(2, N)
r_e = pow(r, e, N)
m_blinded = (m * r_e) % N # exponentiation now operates on this randomized value
s_blinded = pow(m_blinded, d, N)
r_inv = pow(r, -1, N)
s = (s_blinded * r_inv) % N
return s, r, m_blinded
if __name__ == "__main__":
m = 65
s_plain = pow(m, d, N)
s_crt = crt_sign(m)
print(f"message m={m}")
print(f"plain S = m^d mod N = {s_plain}")
print(f"CRT S = CRT(m^dp,m^dq) = {s_crt} (matches plain: {s_crt == s_plain})")
rng = random.Random(20260901) # seeded for reproducibility; real code uses secrets/os.urandom
for _ in range(2):
s_b, r, m_blinded = blinded_sign(m, rng)
print(f"blinding factor r={r:4d} -> exponentiator sees m'={m_blinded:4d} (m itself is {m})"
f" unblinded S={s_b} (matches plain: {s_b == s_plain})")
Output:
message m=65
plain S = m^d mod N = 588
CRT S = CRT(m^dp,m^dq) = 588 (matches plain: True)
blinding factor r=1889 -> exponentiator sees m'=1471 (m itself is 65) unblinded S=588 (matches plain: True)
blinding factor r= 87 -> exponentiator sees m'= 464 (m itself is 65) unblinded S=588 (matches plain: True)
Key points
- Blinding does not change WHAT gets computed, it changes what an attacker measuring timing sees INPUT to the expensive step; two different random r values on the same message produce two different intermediate values M′, decorrelating any timing signal across repeated signing operations on the same M.
- For the CRT branch specifically, blinding can be applied to the combined value before splitting, or per-prime by reducing r modulo p and q separately; either way each half still only ever sees a randomized intermediate value, not the real message reduced mod p or q.
- Computing remodN is cheap (small public exponent, typically 65537) relative to the private-exponent operation it protects, so blinding's overhead is small, one cheap public exponentiation and one modular inverse per signature, against one expensive private exponentiation either way.
- A verification step after unblinding (Se≡?M(modN)) doubles as a cheap sanity check that catches both blinding-implementation bugs and certain fault-injection attacks in one place.
Complexity
Blinding adds one modular exponentiation with the small public exponent e (cheap, since e is small, typically only a handful of bits) and one modular inverse computation, on top of the existing private-key exponentiation that dominates cost either way. As a fraction of total signing time this overhead is small, typically well under the cost of the private exponentiation itself, which is why blinding is close to a "free" mitigation relative to the security it buys.
Edge cases
- r not coprime to N. Must be re-sampled if gcd(r,N)=1 (otherwise r has no modular inverse and unblinding fails); for RSA moduli this is astronomically rare for a random r, but a correct implementation still checks, since silently proceeding with a non-invertible r would corrupt the result rather than just being slow.
- CRT blinding must cover BOTH branches. Blinding only the combined value before CRT-splitting, without ensuring each of the two per-prime branches also sees a decorrelated value, can leave a timing side channel specifically in the smaller mod-p or mod-q computation; blinding needs to protect the actual exponentiation steps, not just the value that feeds into the CRT recombination.
- Reusing the same r across multiple signatures. Defeats the entire point, a fixed r makes the intermediate value just as correlated across repeated signing of related messages as no blinding at all; r must be freshly random EVERY call.
- Skipping the post-exponentiation verification. Not blinding-specific, but common alongside it: a fault-injection attack (distinct from a timing attack) can corrupt the exponentiation itself even with blinding in place, and only an explicit Se≡M check catches a corrupted output before it is released.
A library you're reviewing computes an ECDH shared secret straight from whatever public key a peer sends, with no validation at all before use. Walk through the full set of checks you'd insist go in before that value is trusted, from confirming the point actually belongs to the curve through to how you'd handle its subgroup, and for each one, name the specific class of attack it closes off.
Sample Answer
Direct answer
Before ever using a received Elliptic Curve Diffie-Hellman (ECDH) public value to derive a shared secret, I would check that it decodes to coordinates actually in range, that it truly satisfies this curve's equation, that it isn't the group's identity element, and that it lies in the correct large-prime-order subgroup, or is cofactor-cleared into it. Skipping any one of these hands an active attacker a lever, either to crash the exchange or to leak bits of the static private key one exchange at a time.
Structured elaboration
| Check | What it verifies | Attack it closes |
|---|---|---|
| Coordinate-range / decode | x,y are valid field elements in range for the chosen encoding | Malformed-input crashes and parser confusion that could bypass the checks below entirely |
| Point-on-curve | The point satisfies this curve's equation | Invalid-curve attacks: a peer supplies a point that is valid on a different, weaker curve sharing the same field, one where the attacker already knows the discrete-log structure |
| Not the identity element | The point is not the group's identity (informally, "point at infinity") | A trivially forced shared secret (the identity itself), enabling denial-of-service or degenerate key confirmation |
| Subgroup / cofactor | The point lies in the intended large-prime-order subgroup, verified directly ([n]P=O) or enforced via cofactor multiplication before deriving the secret | Small-subgroup confinement: an attacker supplies a low-order point and, from the handful of possible shared secrets that can result, learns bits of the static private key across repeated exchanges |
Worked example
The small-subgroup leak, made concrete on a small illustrative curve y2=x3+2x+3mod97 (nowhere near production size, but the mechanics are identical at real curve sizes):
p, a, b = 97, 2, 3 # small illustrative curve: y^2 = x^3 + 2x + 3 mod 97
def on_curve(P):
if P is None: return True
x, y = P
return (y*y - (x**3 + a*x + b)) % p == 0
def ec_add(P, Q):
if P is None: return Q
if Q is None: return P
x1, y1 = P; x2, y2 = Q
if x1 == x2 and (y1 + y2) % p == 0:
return None
if P == Q:
lam = (3*x1*x1 + a) * pow(2*y1, -1, p) % p
else:
lam = (y2 - y1) * pow((x2 - x1) % p, -1, p) % p
x3 = (lam*lam - x1 - x2) % p
y3 = (lam*(x1 - x3) - y1) % p
return (x3, y3)
# points with y = 0 have order exactly 2 (they are their own additive inverse)
order2 = [(x, 0) for x in range(p) if (0 - (x**3 + a*x + b)) % p == 0]
T = order2[0]
print("T =", T, " on_curve(T) =", on_curve(T), " 2*T =", ec_add(T, T))
def ec_mul(k, P):
R, Q = None, P
while k > 0:
if k & 1: R = ec_add(R, Q)
Q = ec_add(Q, Q)
k >>= 1
return R
for k in [7, 8, 13, 20]:
print("k =", k, "-> k*T =", ec_mul(k, T), " (k is", "odd" if k % 2 else "even", ")")
# invalid-curve check: a point that satisfies a DIFFERENT curve (a=5, b=9), not this one
for x in range(p):
rhs2 = (x**3 + 5*x + 9) % p
hit = None
for y in range(p):
if (y*y) % p == rhs2:
hit = (x, y); break
if hit:
print("point valid on a DIFFERENT curve:", hit, " on_curve(this curve) =", on_curve(hit))
break
Running this prints:
T = (30, 0) on_curve(T) = True 2*T = None
k = 7 -> k*T = (30, 0) (k is odd )
k = 8 -> k*T = None (k is even )
k = 13 -> k*T = (30, 0) (k is odd )
k = 20 -> k*T = None (k is even )
point valid on a DIFFERENT curve: (0, 3) on_curve(this curve) = False
The point T genuinely lies on the curve (its coordinates satisfy the curve equation) and has order exactly 2, adding it to itself gives the group's identity element. An implementation that skips the subgroup check and just multiplies whatever point it receives by its private scalar k would compute k*T, and that result is either the identity element or T, depending only on whether k is even or odd, handing the attacker one bit of the private key per malicious exchange. The last two lines show the complementary invalid-curve check: a point that is perfectly valid on a different curve (with different curve parameters a,b) fails the on-curve equation for the real one, exactly what the on-curve check exists to catch before it ever reaches the shared-secret computation.
Trade-offs and pitfalls
The small-subgroup leak above is most dangerous against a static, long-lived private key, repeating the attack with different low-order points across many exchanges eventually recovers the whole key; a one-time ephemeral private key limits the attacker to a single leaked bit before it's discarded, still worth preventing, but a much smaller blast radius. Cofactor multiplication (multiplying the received point by the curve's cofactor before using it) is cheaper than an explicit subgroup-order check, but it only closes the leak if every implementation on both sides applies it consistently. Curves purpose-built with a small, fixed cofactor and a Montgomery-ladder scalar multiplication (like Curve25519) bake correct handling into key generation itself via scalar "clamping", which makes most of this validation close to automatic, but that convenience is curve-specific and should never be assumed to generalize to an arbitrary Weierstrass curve.
Design a hybrid key-exchange composition that combines an IND-CCA secure post-quantum KEM and ECDH so that the final session key remains secure if at least one component remains secure. Provide a formal composition strategy (how to mix secrets with HKDF or PRF) and explain why naive concatenation or XOR can be unsafe.
Sample Answer
Direct answer
A hybrid key exchange should mix the post-quantum KEM (Key Encapsulation Mechanism, the mechanism by which two parties agree on a shared secret using a scheme believed hard even for a quantum computer to break) shared secret and the ECDH shared secret through a proper key-derivation function, specifically HKDF (HMAC-based Key Derivation Function), NEVER via raw concatenation-then-single-hash or XOR. The security goal is "IND-CCA if EITHER component remains secure" (IND-CCA: indistinguishable under chosen-ciphertext attack, informally, an attacker who can even ask for decryptions of chosen ciphertexts still cannot distinguish the real key from random), and only a properly-keyed pseudorandom construction actually delivers that guarantee; naive combiners can silently degrade to "as weak as the WORSE component," which defeats the entire point of hybridizing in the first place.
Structured elaboration
- Recommended construction: dual-extract HKDF. Feed spq (the KEM secret) into an HKDF-Extract as the input keying material, keyed by a transcript-derived salt; feed the RESULT as the salt for a second HKDF-Extract keyed by sec (the ECDH secret); expand the final pseudorandom key with a labeled
infostring bound to the handshake transcript. Each stage treats HMAC as a PRF (pseudorandom function): security holds as long as EITHER of the two keying inputs is a good PRF key for its stage, which is exactly the "secure if either component is secure" property being designed for. - Why naive concatenation fails. Hashing
s_pq || s_econce, with no transcript binding, has two separate problems: it provides NO protection if an attacker can influence or predict structure in either input (concatenation preserves more exploitable structure than a proper extract step), and with no transcript label, the SAME pair of secrets produces the SAME derived key regardless of which specific handshake produced them, opening the door to cross-session or cross-protocol key reuse if the underlying KEM/ECDH outputs are ever reused or confused between contexts. - Why naive XOR fails, specifically and demonstrably. XOR is only safe if BOTH inputs are independently, uniformly random; the moment ONE component is compromised (an attacker learns sec, say, through a future cryptanalytic break of ECDH or an implementation bug), XORing the KNOWN value back out of the derived key hands the attacker the OTHER component directly, with zero additional work. This is the precise failure mode "secure if either component remains secure" is meant to prevent, and XOR provides the OPPOSITE: full compromise the moment ONE side falls.
Worked example
I implemented all three combiners against the same pair of stand-in secrets and demonstrated the XOR failure concretely (recovering spq exactly once sec is known), the concatenation failure (identical output across two supposedly-different sessions with no transcript binding), and the recommended construction resisting both:
# Hybrid PQ-KEM + ECDH combiner. Demonstrates WHY naive concatenation/XOR is unsafe by building
# an actual "confirmation" oracle attack surface, and shows the real HKDF-based dual-PRF combiner
# defeats it. Uses toy stand-in secrets (real ML-KEM/ECDH shared secrets are just fixed-length byte
# strings by the time they reach the combiner, so nothing about the combiner logic depends on how
# they were produced).
import hmac, hashlib, random
def hkdf_extract(salt, ikm):
return hmac.new(salt, ikm, hashlib.sha256).digest()
def hkdf_expand(prk, info, length=32):
okm, t, counter = b"", b"", 1
while len(okm) < length:
t = hmac.new(prk, t + info + bytes([counter]), hashlib.sha256).digest()
okm += t
counter += 1
return okm[:length]
def dual_prf_combine(s_pq, s_ec, transcript, label=b"HybridKEX-v1"):
"""The recommended construction: run BOTH secrets through HKDF as independent IKMs feeding one
extract-then-expand chain, bound to the transcript. This is a PRF of (s_pq, s_ec); security holds
if EITHER secret is a good PRF key, because HMAC-SHA256 is being used as a PRF keyed by one input
with the other as message-like data at each stage."""
prk1 = hkdf_extract(salt=hashlib.sha256(b"stage1" + transcript).digest(), ikm=s_pq)
prk2 = hkdf_extract(salt=prk1, ikm=s_ec)
return hkdf_expand(prk2, info=label + transcript, length=32)
def naive_concat_combine(s_pq, s_ec):
"""The unsafe construction: just concatenate and hash once."""
return hashlib.sha256(s_pq + s_ec).digest()
def naive_xor_combine(s_pq, s_ec):
"""The other unsafe construction: XOR the two (requires equal length, silently truncates/pads)."""
n = min(len(s_pq), len(s_ec))
return bytes(a ^ b for a, b in zip(s_pq[:n], s_ec[:n]))
if __name__ == "__main__":
transcript = b"client-hello||server-hello||cert||sig"
# -------- demonstration 1: XOR combiner leaks structure when one component is attacker-known --------
# scenario: the classical ECDH component is later broken (e.g. a future large quantum computer,
# or simply an implementation bug that lets an attacker learn s_ec). The PQ KEM component is untouched.
rng = random.Random(555111) # pinned seed, so re-running reproduces every number below
s_pq = rng.randbytes(32) # genuinely secret in both scenarios
s_ec_real = rng.randbytes(32) # the "broken" component -- attacker will learn this exact value
K_naive_xor = naive_xor_combine(s_pq, s_ec_real)
# attacker who has learned s_ec_real can XOR it back out of the session key directly:
recovered_pq_from_xor = bytes(a ^ b for a, b in zip(K_naive_xor, s_ec_real))
print("XOR combiner:")
print(f" K = s_pq XOR s_ec = {K_naive_xor.hex()}")
print(f" attacker knows s_ec_real, computes K XOR s_ec_real = {recovered_pq_from_xor.hex()}")
print(f" recovered value equals s_pq exactly: {recovered_pq_from_xor == s_pq}")
print(" -> XOR of a broken 32-byte secret with the session key hands the attacker s_pq outright,")
print(" collapsing hybrid security to 'as strong as whichever component the attacker attacked'.\n")
# -------- demonstration 2: concat+single-hash has no transcript binding -> replay across contexts --------
K_naive_concat_ctx1 = naive_concat_combine(s_pq, s_ec_real)
K_naive_concat_ctx2 = naive_concat_combine(s_pq, s_ec_real) # SAME secrets, different session context
print("Naive concat+hash combiner (no transcript/label binding):")
print(f" session A key = {K_naive_concat_ctx1.hex()}")
print(f" session B key = {K_naive_concat_ctx2.hex()} (identical inputs -> identical output)")
print(f" keys match across two unrelated sessions that happened to reuse KEM/ECDH outputs: "
f"{K_naive_concat_ctx1 == K_naive_concat_ctx2}")
print(" -> nothing in the construction binds the derived key to a SPECIFIC handshake transcript,")
print(" so a session-key-reuse or cross-protocol confusion bug becomes silently exploitable.\n")
# -------- demonstration 3: HKDF dual-stage combiner fixes both, verified end to end --------
K_good_A = dual_prf_combine(s_pq, s_ec_real, transcript)
K_good_B_diff_transcript = dual_prf_combine(s_pq, s_ec_real, transcript + b"-session-B")
print("Recommended HKDF dual-extract combiner (labeled, transcript-bound):")
print(f" session A key = {K_good_A.hex()}")
print(f" session B key (same secrets, different transcript) = {K_good_B_diff_transcript.hex()}")
print(f" keys differ once the transcript differs: {K_good_A != K_good_B_diff_transcript}")
# even if s_ec is fully known to the attacker, the HKDF output is still a PRF of s_pq (HMAC's
# security holds with EITHER argument treated as the secret key), so a brute-force check across
# small message space cannot invert s_pq back out of K the way XOR allowed:
K_if_ec_leaked = dual_prf_combine(s_pq, s_ec_real, transcript)
assert K_if_ec_leaked == K_good_A
guess_wrong_pq = rng.randbytes(32)
K_with_wrong_pq = dual_prf_combine(guess_wrong_pq, s_ec_real, transcript)
print(f" swapping in a WRONG s_pq guess (same known s_ec, same transcript) changes the key completely:")
print(f" K(guess) = {K_with_wrong_pq.hex()}")
print(f" K(real) = {K_good_A.hex()}")
print(f" equal: {K_with_wrong_pq == K_good_A} (no structural leakage of s_pq for an attacker who")
print(f" only ever holds s_ec, unlike the XOR case above)")
Output:
XOR combiner:
K = s_pq XOR s_ec = 56ea702f3c1f3410b6e74cc73d3c5528a7af6f7bb81dba8502c17a849fbcfa27
attacker knows s_ec_real, computes K XOR s_ec_real = 63982cb35c2bbe6a469b4c2e76062ac3fc9b92a54be212474c2d2886b30ed4cf
recovered value equals s_pq exactly: True
-> XOR of a broken 32-byte secret with the session key hands the attacker s_pq outright,
collapsing hybrid security to 'as strong as whichever component the attacker attacked'.
Naive concat+hash combiner (no transcript/label binding):
session A key = 4705aea89d4ddd7cb41c66403b7e9110f8b246a02a6167bd47c888d5f0cb2ebd
session B key = 4705aea89d4ddd7cb41c66403b7e9110f8b246a02a6167bd47c888d5f0cb2ebd (identical inputs -> identical output)
keys match across two unrelated sessions that happened to reuse KEM/ECDH outputs: True
-> nothing in the construction binds the derived key to a SPECIFIC handshake transcript,
so a session-key-reuse or cross-protocol confusion bug becomes silently exploitable.
Recommended HKDF dual-extract combiner (labeled, transcript-bound):
session A key = 8504efe7c48913e251e7d8f6bf3a871517475e90b7491e960f97734d2182ce5d
session B key (same secrets, different transcript) = a65d455ec7e52f4d72f85f259d6f03f3d05ceddf2e4d37da2b4d8ba587643b08
keys differ once the transcript differs: True
swapping in a WRONG s_pq guess (same known s_ec, same transcript) changes the key completely:
K(guess) = ad1d750d402efb8f7fbbf7f5e9279e0f14e451cdc6cdc309c9146d1d6e548a8e
K(real) = 8504efe7c48913e251e7d8f6bf3a871517475e90b7491e960f97734d2182ce5d
equal: False (no structural leakage of s_pq for an attacker who
only ever holds s_ec, unlike the XOR case above)
With the XOR combiner, knowing the compromised component (sec) and the session key together hands the attacker spq EXACTLY, with a single XOR operation, no cryptanalysis needed. The dual-extract HKDF construction, by contrast, produces keys that differ once the transcript differs (defeating the concatenation weakness) and does not leak spq even when sec is fully known and the attacker tries substituting a wrong spq guess (defeating the XOR weakness): the derived key changes completely and unpredictably, exactly the behavior expected of a proper PRF.
Trade-offs and pitfalls
- The combiner is cheap; getting it wrong is not. HKDF's extra HMAC calls are computationally negligible compared to the KEM and ECDH operations themselves, so there is essentially no performance argument for the naive constructions; they are simpler to WRITE, not cheaper to RUN, which makes them an easy trap for an implementation under time pressure.
- Transcript binding matters as much as the combiner algebra. Even a properly-keyed HKDF construction that omits transcript binding in its
infoparameter reopens the cross-session key-reuse risk the concatenation example demonstrates; the label and transcript hash need to be part of the derivation, not an afterthought. - "Secure if either component is secure" is a DESIGN GOAL that must be proven, not assumed from using HKDF alone. The formal security argument (a proper hybrid-PRF or dual-PRF security proof) depends on the SPECIFIC extract-then-expand structure and how the transcript is bound in; swapping in a differently-shaped construction that merely "also uses HKDF somewhere" does not automatically inherit the same guarantee.
Unlock Full Question Bank
Get access to all Asymmetric Encryption and Key Exchange interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.