यह किताब अभी हिन्दी में उपलब्ध नहीं है। संस्करण: English।
University Computer Science — Year 3 · स्नातक वर्ष 3
28Public-Key Cryptography and Secure Protocols
The ciphers and MACs of the previous chapter assume that the two parties already share a key. Two strangers on a network do not: the town hall and the library have never met, and every message between them can be read and changed. This chapter shows how they agree on a key in public, with Diffie–Hellman; how one of them can publish a key that encrypts for it and checks its signatures, with RSA and Schnorr; how a browser knows that a public key belongs to a name, with certificates; and how TLS 1.3 puts it all together in one handshake. It ends with the problem that every web service has: storing passwords so that a stolen table is of little use. As in the previous chapter, every attack runs against the chapter’s own toy code, and every group and key is far too small or too simple for real use.
You already know
Computing by repeated squaring, Bézout’s theorem, inverses modulo , Fermat’s little theorem, the Chinese remainder theorem and a miniature RSA come from the mathematics volumes, which also define groups, the order of an element and Lagrange’s theorem: the order of an element divides the order of the group. The Miller–Rabin test declares a number prime with an error probability of at most after random bases (Year 2 volume), where TLS was also met as the layer that secures HTTP. Hash functions, MACs, HMAC and authenticated encryption are from Chapter 27.
28.1 Key exchange
Definition 28.1 (Public-key cryptography, key pair)
Public-key cryptography uses a key pair for each party: a private key, kept secret, and a public key, computed from it and published, such that computing the private key from the public one is infeasible.
Diffie and Hellman published the first public-key method in 1976, a way for two parties to agree on a secret by exchanging only public values. It works in a group where exponentiation is easy and its inverse is hard.
Definition 28.2 (Diffie–Hellman key exchange, discrete-logarithm problem, man-in-the-middle attack)
Let be a prime, a prime dividing , and an integer of order modulo , all public. In the Diffie–Hellman key exchange, one party picks a secret in and sends ; the other picks and sends ; both compute , and derive their keys from with a hash. The discrete-logarithm problem is to find from ; the Diffie–Hellman problem is to find from and . A man-in-the-middle attack is one in which the attacker relays, reads and changes the messages between two parties, who each believe they talk to the other.
The subgroup has prime order so that every element except 1 generates it, and an eavesdropper who knows the factors of a group’s order cannot split the problem into smaller ones. Solving the discrete logarithm solves Diffie–Hellman; no faster way is known in well-chosen groups.
def keypair():
x = rng.randrange(1, q) # private
return x, pow(g, x, p) # public: g^x mod p
def shared(private, other_public):
s = pow(other_public, private, p)
return hashlib.sha256(s.to_bytes(16, "big")).hexdigest()[:16] # derive a key
a, A = keypair() # the town hall
b, B = keypair() # the library
print("town hall sends A =", A)
print("library sends B =", B)
print("town hall's key:", shared(a, B), " library's key:", shared(b, A))
e1, E1 = keypair() # Eve replaces A by E1 on its way to the library,
e2, E2 = keypair() # and B by E2 on its way to the town hall
print("with Eve in the middle:")
print(" town hall's key:", shared(a, E2), " Eve's key with it:", shared(e2, A))
print(" library's key: ", shared(b, E1), " Eve's key with it:", shared(e1, B))
$ python dh.py
p = 224189015200134973710120659971458926861
q = 12161315482320826121
g = 14504459002980742145430293009894764158
town hall sends A = 165458073772900276266583869536907828011
library sends B = 114595641503270752125673678182881220769
town hall's key: f623e5ab31830ccd library's key: f623e5ab31830ccd
with Eve in the middle:
town hall's key: bb0a7d5d26257d9e Eve's key with it: bb0a7d5d26257d9e
library's key: ccaf84b7d07c056b Eve's key with it: ccaf84b7d07c056b
Diffie–Hellman protects against an eavesdropper, not against an active attacker: the public values must be authenticated, by a signature from a key that the other side already trusts. The rest of the chapter builds that.
How hard is the discrete logarithm? Trying every exponent costs multiplications. Shanks’s baby-step giant-step method of 1971 needs only about , trading time for memory.
Method 28.3 (Baby-step giant-step)
To find with in a group of order : let and write the unknown with . Baby steps: store for in a hash table. Giant steps: for , look up ; when it is , answer . At most multiplications for the table, and at most for the giant steps.
def bsgs(g, h, p, q):
"""Return x with g^x = h mod p, 0 <= x < q, and the number of multiplications."""
m = math.isqrt(q - 1) + 1 # m = ceil(sqrt(q)), so x = i*m + j with i, j < m
baby, e = {}, 1
for j in range(m): # baby steps: g^0, g^1, ..., g^(m-1)
baby.setdefault(e, j)
e = e * g % p
step = pow(g, -m, p) # g^(-m)
gamma = h
for i in range(m): # giant steps: h, h g^-m, h g^-2m, ...
if gamma in baby:
return i * m + baby[gamma], m + i
gamma = gamma * step % p
raise ValueError("h is not a power of g")
$ python bsgs.py
bits of q 2*sqrt(q) most steps mean steps mean/sqrt(q) (20 logs each)
20 1,512 1,509 1,220 1.61
24 6,862 6,673 4,963 1.45
28 24,514 24,429 18,739 1.53
32 94,300 92,242 71,277 1.51
36 463,662 455,172 349,149 1.51
So a group of order gives at most bits of security, and a 64-bit subgroup like the one of Output 28.1 gives 32. The weekend problem draws the consequence. Methods specific to the integers modulo , beyond this chapter, also require itself to be much longer than : NIST pairs a 256-bit with a 3072-bit .
28.2 RSA and its correct use
Definition 28.4 (RSA, textbook RSA, OAEP)
RSA key generation picks two large random primes , sets and , chooses with , commonly , and computes . The public key is , the private key . Textbook RSA encrypts a number as and decrypts as . OAEP (optimal asymmetric encryption padding) is a randomised encoding of the message applied before the exponentiation.
Rivest, Shamir and Adleman published the method in 1978.
Theorem 28.5 (Correctness of RSA)
For every with , .
Proof. Facts used: Euler’s theorem, when , which follows from Lagrange’s theorem in the group of invertible residues modulo , of order . Since , write with . Then . ∎
The theorem holds for every , including the rare ones that share a factor with (exercise 28.7). The primes come from Miller–Rabin on random odd numbers, and Python’s integers do the rest.
def keygen(bits, rng):
"""Two random primes of bits/2 bits each, with e = 65537 invertible mod phi(n)."""
while True:
p, q = random_prime(bits // 2, rng), random_prime(bits // 2, rng)
phi = (p - 1) * (q - 1)
if p != q and gcd(E, phi) == 1 and (p * q).bit_length() == bits:
d = pow(E, -1, phi) # e d = 1 mod phi(n)
return {"n": p * q, "e": E}, {"n": p * q, "d": d, "p": p, "q": q}
def encrypt(pub, m):
assert 0 <= m < pub["n"]
return pow(m, pub["e"], pub["n"]) # c = m^e mod n
def decrypt(priv, c):
return pow(c, priv["d"], priv["n"]) # m = c^d mod n
$ python rsa_demo.py
n has 2048 bits; e = 65537
c starts 0x68a0114c3e19eec2 ...
decrypted: meet at the town hall at noon
with the CRT: True
direct: 3,055 products mod n: 3,128,320 word products
CRT: 3,044 products mod p, q: 779,264 word products
ratio 4.01
The private key holder knows and , so it can decrypt modulo and modulo separately, with exponents and of half the length, and recombine (exercise 28.6). The count of products barely changes, but each is a product of numbers half as long, and a schoolbook product of -bit numbers costs about word products: four times less work.
Textbook RSA is a function, not yet a secure cipher. It is deterministic, so anyone can test a guess by encrypting it with the public key; and it is malleable, since .
$ python rsa_malleable.py
Eve's guess 'yes' matches: False
Eve's guess 'no' matches: True
the treasurer decrypts the forged order: 3000
Real systems therefore never encrypt with textbook RSA. The older PKCS#1 v1.5 padding was shown insufficient for some messages, and OAEP, which mixes random bytes into the message through hash functions before exponentiation, is the encoding to use in any new application. In practice RSA, or Diffie–Hellman, only carries a fresh symmetric key, and the data goes through the authenticated encryption of the previous chapter.
Facts as of 2026
NIST’s key-management guide (SP 800-57 Part 1, revision 5, May 2020) compares strengths: 112-bit security needs an RSA modulus of 2048 bits or a Diffie–Hellman group with of 2048 bits and of 224; 128-bit security, as AES-128, needs 3072 bits and of 256 bits, or an elliptic-curve group of 256 to 383 bits; 256-bit security needs a 15360-bit modulus. The guide counts 112-bit strength acceptable for protecting data through 2030 and disallows it from 2031, and warns that its estimates will change when quantum computing becomes practical.
28.3 Elliptic curves
Definition 28.6 (Elliptic curve)
An elliptic curve over a field , in cryptography, is the set of points with , where , together with a point at infinity . The points form a commutative group, written additively, with as its neutral element: the line through and (the tangent if ) meets the curve in a third point, and is the mirror image of that point in the -axis.
ec_add.py: the chord through and meets the curve again at , and .def add(P, Q, a, mod=None):
"""P + Q on y^2 = x^3 + a x + b; None is the point at infinity, the neutral one."""
if P is None or Q is None:
return P or Q
(x1, y1), (x2, y2) = P, Q
inv = (lambda z: pow(z, -1, mod)) if mod else (lambda z: 1 / F(z))
if x1 == x2 and (y1 + y2 == 0 or (mod and (y1 + y2) % mod == 0)):
return None # vertical line: P + (-P) = O
if P == Q:
slope = (3 * x1 * x1 + a) * inv(2 * y1) # the tangent
else:
slope = (y2 - y1) * inv(x2 - x1) # the chord
x3 = slope * slope - x1 - x2
y3 = slope * (x1 - x3) - y1
return (x3 % mod, y3 % mod) if mod else (x3, y3)
$ python ec_add.py
P + Q = (-11/9, 17/27) third point on the chord: (-11/9, -17/27)
on the curve: True
y^2 = x^3 + 2x + 3 mod 97: 100 points
Hasse: |100 - 98| <= 2 sqrt(p) = 19.7
G = (0, 10) has order 50, which divides 100: True
Over a finite field with elements a curve has points with , a theorem that Hasse proved in 1933. Diffie–Hellman works in the group of points just as in the integers modulo , with in place of . For well-chosen curves no discrete-logarithm method faster than generic ones like baby-step giant-step is known, so a group of about points gives 128-bit security with 256-bit keys, against 3072 bits for RSA. RFC 7748 specifies X25519, Diffie–Hellman on a curve over the prime field of elements, for the 128-bit level. The chapter does not implement it: its arithmetic must run in constant time, which a library does and toy code does not.
28.4 Signatures and certificates
Definition 28.7 (Digital signature, hash-then-sign, Schnorr signature)
A digital signature scheme gives a key pair; signing a message uses the private key, and anyone can check a signature with the public key; no one without the private key can produce a valid signature on a new message, even after seeing signatures on messages of its choice. Hash-then-sign signs a fixed-length hash of the message instead of the message. A Schnorr signature works in a group of prime order generated by , with a hash into ; the private key is , the public key . To sign : pick a fresh random nonce , set , , ; the signature is . To verify: check that and that is a group element, then that with .
A signature differs from a MAC: a MAC’s key is shared, so either party could have produced a tag, while only the private key’s holder can sign, and anyone can check. RSA also signs, with the roles of the exponents exchanged: the full-domain hash method hashes the message to the size of the modulus and raises the result to the power , and PSS, a randomised encoding, is the standard replacement for the older PKCS#1 v1.5 signatures. Schnorr published his scheme in 1991.
Theorem 28.8 (Correctness of Schnorr signatures)
A signature produced by the signing algorithm passes verification.
Proof. Facts used: , so exponents of count modulo . The signer returns , so , and is a group element. And , with the same that the verifier computes. ∎
def challenge(r, m):
data = r.to_bytes(128, "big") + m
return int.from_bytes(hashlib.sha256(data).digest(), "big") % Q
def keygen(rng):
x = rng.randrange(1, Q)
return x, pow(G, x, P) # private x, public y = g^x
def sign(x, m, rng):
k = rng.randrange(1, Q) # a fresh secret nonce for every signature
r = pow(G, k, P)
e = challenge(r, m)
return r, (k + e * x) % Q
def verify(y, m, sig):
r, s = sig
if not (0 <= s < Q and 1 < r < P):
return False
return pow(G, s, P) == r * pow(y, challenge(r, m), P) % P # g^s = r y^e
$ python schnorr.py
valid: True
other message: False
same r in both signatures: True
private key recovered: True
The nonce is as secret as the key: two signatures with one make two linear equations in the unknowns and (exercise 28.11). Implementations therefore derive from the private key and the message, or draw it from the operating system’s generator, never from a seeded one.
A public key is only useful if its owner is known. A browser cannot hold the keys of every server, but it can hold a few keys that it trusts, and accept another key when one of them vouches for it.
Definition 28.9 (Certificate, certificate chain, trust anchor, revocation)
A certificate is a signed statement binding a public key to a name, with an issuer, a validity period and the uses allowed, such as whether the key may sign certificates; the issuer of a certificate allowed to sign others is a certification authority (CA). A certificate chain is a list of certificates, each signed with the key of the next, up to a trust anchor, a public key the verifier holds in advance. Revocation withdraws a certificate before its expiry, for instance after its private key leaks.
def check_chain(chain, anchors, today):
"""chain[0] is the server's certificate, each signed by the next; the last must be
signed by a trust anchor. Return "ok" or the reason for refusing."""
for i, cert in enumerate(chain):
body = cert["body"]
if not body["not_before"] <= today <= body["not_after"]:
return f"{body['subject']}: expired or not yet valid"
if i + 1 < len(chain):
issuer = chain[i + 1]["body"]
if issuer["subject"] != body["issuer"] or not issuer["ca"]:
return f"{body['subject']}: issuer is not a CA in the chain"
y = issuer["key"]
elif body["issuer"] in anchors:
y = anchors[body["issuer"]]
else:
return f"{body['subject']}: no trust anchor named {body['issuer']}"
data = json.dumps(body, sort_keys=True).encode()
if not schnorr.verify(y, data, cert["sig"]):
return f"{body['subject']}: bad signature"
return "ok"
$ python toy_cert.py
library's chain: ok
checked in 2028: library.example: expired or not yet valid
leaf with Eve's key: library.example: bad signature
Eve's own chain: Regional CA: bad signature
library's leaf used as a CA: town.example: issuer is not a CA in the chain
Real certificates have a standard binary format and are checked by a library, along with many more rules. Revocation is the hard part: a certificate stays valid in every copy until it expires, so the client must learn from somewhere else, at connection time, that it was withdrawn.
28.5 Secure protocols: TLS 1.3 and passwords
TLS 1.3, specified in RFC 8446 in August 2018, establishes a secure channel in one round trip of handshake messages. The client sends a ClientHello with its Diffie–Hellman share; the server answers with its share, and from then on everything it sends is encrypted under keys derived from the shared secret: its extensions, its certificate chain, a CertificateVerify that signs the whole handshake so far with the certificate’s key, and a Finished message, a MAC over the whole handshake. The client checks them and sends its own Finished. Keys come from a key schedule built on HKDF: each secret is bound to a label and to the hash of the messages exchanged so far, so that a change to any message changes every key that follows. TLS 1.3 removed the static RSA and static Diffie–Hellman key exchanges, so every exchange based on public keys gives forward secrecy.
Definition 28.10 (Forward secrecy)
A key exchange has forward secrecy if a later compromise of the long-term private keys does not reveal the session keys of earlier sessions.
HKDF, from RFC 5869, is the key-derivation function of TLS 1.3: an extract step that turns the Diffie–Hellman output into a uniform key, and an expand step that derives as many keys as needed from it, each bound to a context string (exercise 28.12).
$ python hkdf_vector.py
PRK 077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5
OKM 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
as in RFC 5869: True
The next program runs the shape of the TLS 1.3 handshake between two Python objects, with the chapter’s group, signatures and certificates, and HKDF.
early = extract(b"", bytes(32))
shared_s = pow(int.from_bytes(t[0][2], "big"), b, P).to_bytes(128, "big")
hs = extract(derive(early, "derived", []), shared_s) # handshake secret
s_hs = derive(hs, "s hs traffic", t)
t.append(("server", "{EncryptedExtensions}", b"no extensions"))
t.append(("server", "{Certificate}", repr(CHAIN).encode()))
th = hashlib.sha256(b"".join(m for *_, m in t)).digest()
# the server's long-term key signs the transcript so far
r, s = schnorr.sign(LIB_X, th, rng)
sig = r.to_bytes(128, "big") + s.to_bytes(20, "big")
t.append(("server", "{CertificateVerify}", sig))
t.append(("server", "{Finished}", finished_mac(s_hs, t)))
# The client: the same computation on what it received
$ python tls13_trace.py
--> ClientHello + key_share 128 bytes
<-- ServerHello + key_share 128 bytes
<-- {EncryptedExtensions} 13 bytes
<-- {Certificate} 817 bytes
<-- {CertificateVerify} 148 bytes
<-- {Finished} 32 bytes
--> {Finished} 32 bytes
client checks: {'chain': True, 'signature': True, 'server Finished': True}
same application secret on both sides: True
with Eve's key share, client checks: {'chain': True, 'signature': False, 'server Finished': False}
same application secret on both sides: False
The signature authenticates the Diffie–Hellman exchange, which is what Output 28.1 lacked; the ephemeral secrets and are erased after the handshake, which is what gives forward secrecy (exercise 28.10).
Definition 28.11 (Password hashing, salt, key-derivation function)
Password hashing stores, for each account, not the password but the output of a deliberately slow function of it, so that a stolen table can only be attacked by guessing, one costly guess at a time. A salt is a random value stored with each account and hashed with its password, so that equal passwords give different stored values and no guess can be tested against all accounts at once. A key-derivation function derives keys from a secret: HKDF from a secret that is already random, and PBKDF2 or scrypt from a password, with a cost parameter that sets the work per guess.
NIST’s guidelines require stored passwords to be salted and hashed with a password-hashing scheme that takes a cost factor, with a salt of at least 32 bits and a cost factor as high as practical and raised over time. PBKDF2 iterates HMAC a chosen number of times; scrypt also fills and reads back a table of bytes, so that each guess needs memory as well as time.
N, R, PAR = 2**14, 8, 1 # scrypt cost: 2^14 x 128 x 8 bytes = 16 MiB of memory
def store(password):
salt = secrets.token_bytes(16)
h = hashlib.scrypt(password.encode(), salt=salt, n=N, r=R, p=PAR, dklen=32)
return salt, h
def check(password, record):
salt, h = record
guess = hashlib.scrypt(password.encode(), salt=salt, n=N, r=R, p=PAR, dklen=32)
return hmac.compare_digest(guess, h) # takes the same time wherever they differ
$ python passwords.py
same password, same stored hash: False
check right / wrong: True False
SHA-256 once: 3,040,225 guesses per second
PBKDF2, 600,000 rounds: 9.3 guesses per second
scrypt, n = 2^14, r = 8: 35.1 guesses per second
slowdown: PBKDF2 326,279x, scrypt 86,535x
A fast hash lets a stolen table be tested at millions of guesses per second on one core; scrypt with and costs 16 MiB and tens of milliseconds per guess, which a user logging in does not notice and an attacker trying a billion passwords does.
28.6 Exercises
Exercise 28.1 ★
Take and , of order 11. The town hall picks and the library . Compute the values they send and the key they share, by hand.
Solution
Solution of Exercise 28.1.
, , so and . The town hall computes ; the library computes , and , , , so . Both get 6. And : with .
Exercise 28.2 ★
With , and , compute , and ; encrypt and decrypt the result.
Solution
Solution of Exercise 28.2.
, . The extended Euclidean algorithm on 3120 and 17 gives : . Encryption: ; decryption: . A test checks the four numbers.
Exercise 28.3 ★
The town hall sends the library a budget, signed with its private key. Which of these does the signature guarantee: that no one else read the budget; that it was not changed; that it comes from the town hall; that the town hall cannot later deny sending it to anyone, not just to the library? Which of them would a MAC with a shared key guarantee?
Solution
Solution of Exercise 28.3.
The signature guarantees that the budget was not changed and that it comes from the holder of the town hall’s private key, and, since anyone can check it, the town hall cannot deny it to a third party. It does not hide the budget: confidentiality needs encryption. A MAC with a key shared by the town hall and the library also shows that the budget was not changed and, to the library, that it comes from the town hall; but the library could have computed the same tag, so a third party learns nothing from it, and there is no undeniability.
Exercise 28.4 ★
Without running bsgs.py, say how many baby steps it takes for , and the largest and smallest numbers of steps it can report.
Solution
Solution of Exercise 28.4.
, since . The program always makes the 1001 baby steps and reports , where is the index of the successful giant step, between 0 and : at least 1001, when , and at most 2001.
Exercise 28.5 ★★
verify_buggy in exercises/ex5_schnorr_range.py checks but not . Show that it accepts a signature the signer never produced, explain why that matters when signatures are used to identify payments, and fix it.
Solution
Solution of Exercise 28.5.
has order , so , and passes the check : the buggy verifier of the exercise file accepts it. The signer never produced that pair, yet it signs the same message, so the scheme is malleable: if a system names a payment by the hash of its signed record, anyone can make a second, valid record of the same payment with a different name, and the payer may be asked to pay twice or see a payment reported as missing. The fix restores , and also checks that is a group element, as verify in schnorr.py does; the test checks that the twin is then refused on ten signatures.
Exercise 28.6 ★★
Write decrypt_crt(priv, c): compute and likewise, and recombine them into . Prove the recombination formula you use, and test the function against plain decryption.
Solution
Solution of Exercise 28.6.
exercises/ex6_crt.py. First, : if both sides are 0; otherwise by Fermat’s little theorem, so exponents count modulo . So and . Recombination: and . Modulo , ; modulo , . And . By the Chinese remainder theorem, the only number in congruent to modulo and is , so . The test compares it with plain decryption on 20 random messages and on messages divisible by or ; rsa_demo.py uses it for its count.
Exercise 28.7 ★★
Prove that for every , including those with .
Solution
Solution of Exercise 28.7.
Facts used: Fermat’s little theorem; the Chinese remainder theorem. Write . Modulo : if , then ; otherwise and . In the same way . So is divisible by the distinct primes and , hence by , for every . The proof never divides by , which is why it covers the case that Euler’s theorem leaves out.
Exercise 28.8 ★★
Prove that baby-step giant-step returns the discrete logarithm, and that it uses at most multiplications. If is uniform, what is the expected number of giant steps?
Solution
Solution of Exercise 28.8.
Let and ; write with and , so . The table holds for ; these powers are distinct since and has order . At giant step , is in the table, so the method stops at step or earlier. If it stops earlier, at with , then with , so the two are equal, which contradicts . So the answer is . Cost: multiplications for the table, one for by fast exponentiation (a few dozen, not counted), and table look-ups with at most multiplications: at most . If is uniform, is nearly uniform on , so about giant steps are expected, steps in all, as Output 28.2 shows.
Exercise 28.9 ★★
From Output 28.10, how long does an attacker with one core need to try a list of common passwords against one stolen SHA-256 hash, and against one scrypt hash? Against a table of a million accounts, with and without salts?
Solution
Solution of Exercise 28.9.
The printed rates are about 3 million SHA-256 guesses and about 35 scrypt guesses per second; the numbers vary from run to run, the ratio less. One SHA-256 hash: guesses in about 330 seconds, five and a half minutes. One scrypt hash: about seconds, some eleven months. A table of a million unsalted accounts costs no more than one: each guess is hashed once and looked up among all the stored values. With salts each account must be attacked separately: a million times longer, about ten years of one core for SHA-256 and hundreds of thousands of years for scrypt. Salts multiply the attacker’s work by the number of accounts; the slow function multiplies the cost of each guess.
Exercise 28.10 ★★★
In a model where each session uses fresh exponents , , erased at its end, and the long-term keys only sign, argue that an attacker who records a session and later steals both parties’ long-term keys learns nothing about the session key beyond what solving Diffie–Hellman on , would give. Why does static RSA key transport, where the client encrypts the session key with the server’s long-term RSA key, lack this property?
Solution
Solution of Exercise 28.10.
The session key is derived from and the public transcript only. The long-term keys enter the session only through signatures over the transcript; they are not inputs to the key derivation. An attacker who later steals them holds , and the transcript from the recording, plus the long-term private keys, which tell nothing about or : those were chosen independently and erased. So computing the session key from what it holds is the Diffie–Hellman problem on , with no help from the stolen keys. Stolen signing keys only let the attacker impersonate a party in future sessions. With static RSA key transport, the session key is encrypted under the server’s long-term key and sent: whoever later obtains that private key decrypts every recorded session. That is why TLS 1.3 removed it.
Exercise 28.11 ★★★
Two Schnorr signatures on and on share the nonce . Derive from them, say when the formula fails, and prove that it is correct. Does a nonce that is merely predictable, say , also leak ?
Solution
Solution of Exercise 28.11.
Facts used: is prime, so every non-zero residue has an inverse modulo . Let . Then and , so , and if , . The formula fails only when , which for different messages requires a collision of the hash modulo . A predictable nonce leaks the key too: if , then , and the same division gives ; any known relation between two nonces gives one linear equation too many. schnorr.py and a test recover the key this way.
Exercise 28.12 ★★★
Implement HKDF from RFC 5869 with HMAC-SHA-256: extract(salt, ikm), with an empty salt replaced by 32 zero bytes, and expand(prk, info, length), with . Pass test cases 1 to 3 of the RFC.
Solution
Solution of Exercise 28.12.
exercises/ex12_hkdf.py: extract is , with 32 zero bytes when the salt is empty; expand chains , each the HMAC under the PRK of the previous block, the info and the block number as one byte, and keeps the first length bytes, refusing more than . The test passes test cases 1, 2 and 3 of RFC 5869: in case 2, 82 output bytes need three blocks; in case 3 the salt and info are empty.
28.7 Weekend problem
Problem 28.1
Weekend problem — A shared key for the town hall and the library
The town hall and the library want a shared key for their nightly exchange of records. A consultant proposes Diffie–Hellman in a small group, “since no one is listening”. The problem works through the exchange, the attack that breaks it, and the size the group must have.
Part I — Diffie–Hellman in a small group.
- Check that has order 23 modulo .
- The town hall picks and the library . What do they send?
- Compute the shared value both ways.
- Why does the protocol use a subgroup of prime order rather than all the residues modulo 47?
- Find from by trying exponents. How many tries does it take at most?
- Which of , , , , , and the shared value are public?
Part II — The man in the middle.
- In Output 28.1, why does each side’s key agree with Eve’s and not with the other side’s?
- What can Eve do with the records that pass that night?
- Would the town hall notice anything in the values it receives?
- The library publishes a certificate for a signing key, issued by a CA both trust. What must the library sign during the exchange?
- In Output 28.9, which check fails when Eve changes the server’s share, and why can Eve not repair it?
- Could Eve instead present a certificate for her own key? What stops her?
Part III — Baby-step giant-step on small groups.
- From Output 28.2, how does the mean number of steps grow when grows 16 times?
- Check that no run exceeded , and say why none can.
- Explain why the mean is close to .
- How much memory does the table take for , and for ?
- The 64-bit subgroup of Output 28.1: how many steps would baby-step giant-step take?
- Why can an eavesdropper who records the exchange tonight attack it at leisure later?
Part IV — How large q must be.
- For bits of security against baby-step giant-step, how many bits must have?
- What does that give for 128-bit security?
- What size of does NIST’s table pair with that , and why must be longer than ?
- What elliptic-curve group gives the same security, and what is gained?
- Why is 112-bit strength not enough for records that must stay secret until 2035?
- Sum up: how does baby-step giant-step scale, and what does 128-bit security need?
Solution
Solution of Problem 28.1.
1. 23 is prime, so the order of 2 is 1 or 23; , and , which a test checks, so the order is 23.
2. and .
3. and .
4. All the non-zero residues modulo 47 form a group of order 46: its elements’ powers reveal the exponent modulo 2, by checking whether the 23rd power is 1, so an eavesdropper learns one bit of for free, and in general the discrete logarithm splits along the factors of the group’s order. A subgroup of prime order has no smaller pieces.
5. At most 22 tries, the exponents 1 to 22; here the fifth power is the first to give 32.
6. , , and are public; , and the shared value 24 are secret.
7. The town hall computed with , believing it came from the library, so its key is , which Eve can compute from and ; likewise the library’s key is . Neither key involves both and .
8. Decrypt each record with one key, read it, change it if she likes, re-encrypt it with the other key, and pass it on; or drop it, or inject new ones.
9. No: is an element of the group like any other, and nothing in it says who chose it.
10. Its Diffie–Hellman share, or better the whole transcript of the exchange including both shares, with the key its certificate names; the town hall checks the certificate chain and then the signature.
11. The signature check: the server signed the transcript containing its own share , while the client’s transcript contains Eve’s share; the Finished MAC fails too, since the two sides derived different keys. To repair it Eve would have to sign the altered transcript with the library’s private key, which she does not have.
12. Only if a CA the town hall trusts issued a certificate binding her key to the library’s name. Issuing such certificates only to the owners of the names is the CA’s whole job, and a chain that Eve signs herself ends at no trust anchor, as Output 28.7 shows.
13. By about 4, the square root of 16, as expected; the measured ratios are 3.8, from 4,963 to 18,739 between 24 and 28 bits, and 4.9, from 71,277 to 349,149 between 32 and 36, since each mean is of only 20 random logarithms.
14. The largest counts, 1,509, 6,673, 24,429, 92,242 and 455,172, are below in each row. The program counts with , so at most with , which is up to rounding.
15. Every run makes the baby steps; the giant step that succeeds has an index nearly uniform between 0 and , so about on average: .
16. entries for , tens of megabytes as Python objects. For , entries: at 16 bytes per entry in a compact table, 64 GiB, and several times more in Python. Memory, not time, limits the method first; variants trade some time back for less memory.
17. , so about steps on average and at most: hours of computation, with a table of a few billion entries.
18. The values and and the encrypted records can be recorded tonight and attacked whenever the attacker is ready: solving the logarithm later still yields the key, and with it every recorded record.
19. About operations, so needs bits.
20. A 256-bit .
21. NIST’s table pairs of 256 bits with of 3072 bits. Baby-step giant-step only uses the group operation, so it depends on ; but the integers modulo also allow methods that use their arithmetic, beyond this chapter, whose cost depends on the size of .
22. An elliptic-curve group of 256 to 383 bits, such as the one X25519 uses: keys and shares of 32 bytes instead of 384, and faster operations, because no method better than the generic ones is known on such curves.
23. NIST counts 112-bit strength acceptable for protecting data only through 2030, and asks that protection not be applied with an algorithm whose lifetime ends before the data’s security life does: records that must stay secret until 2035 need 128-bit strength now.
24. Baby-step giant-step solved logarithms in groups of order to in at most about steps, on average, so a group gives only half its size in bits of security. 128-bit security needs , with a 3072-bit , or a 256-bit elliptic-curve group; and whatever the size, the exchange must be authenticated, or Eve simply sits in the middle.
इस अध्याय में परिभाषित शब्द
- Certificate, certificate chain, trust anchor, revocation
- Diffie–Hellman key exchange, discrete-logarithm problem, man-in-the-middle attack
- Digital signature, hash-then-sign, Schnorr signature
- Elliptic curve
- Forward secrecy
- Password hashing, salt, key-derivation function
- Public-key cryptography, key pair
- RSA, textbook RSA, OAEP