कंप्यूटर विज्ञान · किताब 5 · स्नातक वर्ष 3

University Computer Science — Year 3

यह किताब अभी हिन्दी में उपलब्ध नहीं है। संस्करण: 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 ae mod na^e \bmod n by repeated squaring, Bézout’s theorem, inverses modulo nn, 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 4−k4^{-k} after kk 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 pp be a prime, qq a prime dividing p−1p - 1, and gg an integer of order qq modulo pp, all public. In the Diffie–Hellman key exchange, one party picks a secret aa in {1,…,q−1}\{1, \ldots, q - 1\} and sends A=ga mod pA = g^a \bmod p; the other picks bb and sends B=gb mod pB = g^b \bmod p; both compute K=Ba=Ab=gab mod pK = B^a = A^b = g^{ab} \bmod p, and derive their keys from KK with a hash. The discrete-logarithm problem is to find xx from gx mod pg^x \bmod p; the Diffie–Hellman problem is to find gabg^{ab} from gag^a and gbg^b. 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))
Listing 28.1. A key pair, the shared key from the other side’s public value, and Eve replacing both public values. code/bachelor-3/28-public-key-cryptography/listings/dh.py
$ 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
Output 28.1. A 64-bit subgroup of the integers modulo a 128-bit prime. The two sides agree; with Eve in the middle, each side agrees with Eve.
Diffie–Hellman with Eve in the middle. Nothing in the exchange says who sent a public value, so each side runs the protocol correctly with Eve. Eve decrypts each message with one key and re-encrypts it with the other.
Diffie–Hellman with Eve in the middle. Nothing in the exchange says who sent a public value, so each side runs the protocol correctly with Eve. Eve decrypts each message with one key and re-encrypts it with the other.

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 qq multiplications. Shanks’s baby-step giant-step method of 1971 needs only about 2q2\sqrt{q}, trading time for memory.

Method 28.3 (Baby-step giant-step)

To find xx with gx=hg^x = h in a group of order qq: let m=⌈q ⌉m = \lceil \sqrt{q}\, \rceil and write the unknown x=im+jx = im + j with 0≤i,j<m0 \le i, j < m. Baby steps: store gj↦jg^j \mapsto j for j=0,…,m−1j = 0, \ldots, m - 1 in a hash table. Giant steps: for i=0,1,…i = 0, 1, \ldots, look up h⋅g−imh \cdot g^{-im}; when it is gjg^j, answer x=im+jx = im + j. At most mm multiplications for the table, and at most mm 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")
Listing 28.2. Baby steps into a dictionary, then giant steps of g−mg^{-m} from hh; the second value returned counts the multiplications. code/bachelor-3/28-public-key-cryptography/listings/bsgs.py
$ 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
Output 28.2. Five group sizes, 20 logarithms each: never more than 2q2\sqrt{q} steps, about 1.5q1.5\sqrt{q} on average.

So a group of order qq gives at most 12log⁡2q\frac{1}{2}\log_2 q 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 pp, beyond this chapter, also require pp itself to be much longer than qq: NIST pairs a 256-bit qq with a 3072-bit pp.

28.2 RSA and its correct use

Definition 28.4 (RSA, textbook RSA, OAEP)

RSA key generation picks two large random primes p≠qp \ne q, sets n=pqn = pq and φ(n)=(p−1)(q−1)\varphi(n) = (p - 1)(q - 1), chooses ee with gcd⁡(e,φ(n))=1\gcd(e, \varphi(n)) = 1, commonly e=65537e = 65537, and computes d=e−1 mod φ(n)d = e^{-1} \bmod \varphi(n). The public key is (n,e)(n, e), the private key dd. Textbook RSA encrypts a number 0≤m<n0 \le m < n as c=me mod nc = m^e \bmod n and decrypts as m=cd mod nm = c^d \bmod n. 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 mm with gcd⁡(m,n)=1\gcd(m, n) = 1, (me)d≡m(modn)(m^e)^d \equiv m \pmod{n}.

Proof. Facts used: Euler’s theorem, mφ(n)≡1(modn)m^{\varphi(n)} \equiv 1 \pmod n when gcd⁡(m,n)=1\gcd(m, n) = 1, which follows from Lagrange’s theorem in the group of invertible residues modulo nn, of order φ(n)\varphi(n). Since ed≡1(modφ(n))ed \equiv 1 \pmod{\varphi(n)}, write ed=1+kφ(n)ed = 1 + k\varphi(n) with k≥0k \ge 0. Then med=m⋅(mφ(n))k≡m⋅1k=m(modn)m^{ed} = m \cdot (m^{\varphi(n)})^k \equiv m \cdot 1^k = m \pmod n. ∎

The theorem holds for every mm, including the rare ones that share a factor with nn (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
Listing 28.3. Key generation, encryption and decryption, in textbook form. code/bachelor-3/28-public-key-cryptography/listings/rsa.py
$ 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
Output 28.3. A 2048-bit key from a seeded generator. Decrypting with the Chinese remainder theorem gives the same message for a quarter of the work.

The private key holder knows pp and qq, so it can decrypt modulo pp and modulo qq separately, with exponents d mod (p−1)d \bmod (p - 1) and d mod (q−1)d \bmod (q - 1) 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 bb-bit numbers costs about (b/64)2(b/64)^2 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 (me)(se)=(ms)e(m^e)(s^e) = (ms)^e.

$ python rsa_malleable.py
Eve's guess 'yes' matches: False
Eve's guess 'no' matches: True
the treasurer decrypts the forged order: 3000
Output 28.4. A two-letter vote is found by encrypting the two candidates; multiplying a ciphertext by 2e2^e doubles the amount it hides.

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 pp of 2048 bits and qq of 224; 128-bit security, as AES-128, needs 3072 bits and qq 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 KK, in cryptography, is the set of points (x,y)∈K2(x, y) \in K^2 with y2=x3+ax+by^2 = x^3 + ax + b, where 4a3+27b2≠04a^3 + 27b^2 \ne 0, together with a point at infinity OO. The points form a commutative group, written additively, with OO as its neutral element: the line through PP and QQ (the tangent if P=QP = Q) meets the curve in a third point, and P+QP + Q is the mirror image of that point in the xx-axis.

The group law on y2 = x3 - x + 1 over the reals, with the points computed by ec_add.py: the chord through P = (0, 1) and Q = (3, 5) meets the curve again at R = (-11/9, -17/27), and P + Q = (-11/9, 17/27).
The group law on y2=x3−x+1y^2 = x^3 - x + 1 over the reals, with the points computed by ec_add.py: the chord through P=(0,1)P = (0, 1) and Q=(3,5)Q = (3, 5) meets the curve again at R=(−11/9,−17/27)R = (-11/9, -17/27), and P+Q=(−11/9,17/27)P + Q = (-11/9, 17/27).
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)
Listing 28.4. Addition of points with exact fractions, or modulo a prime: the same formulas. code/bachelor-3/28-public-key-cryptography/listings/ec_add.py
$ 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
Output 28.5. The figure’s points, then a curve over the field of 97 elements: 100 points, and an element of order 50.

Over a finite field with qq elements a curve has NN points with ∣N−(q+1)∣≤2q|N - (q + 1)| \le 2\sqrt{q}, a theorem that Hasse proved in 1933. Diffie–Hellman works in the group of points just as in the integers modulo pp, with kP=P+⋯+PkP = P + \cdots + P in place of gkg^k. For well-chosen curves no discrete-logarithm method faster than generic ones like baby-step giant-step is known, so a group of about 22562^{256} 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 2255−192^{255} - 19 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 qq generated by gg, with a hash HH into {0,…,q−1}\{0, \ldots, q - 1\}; the private key is xx, the public key y=gxy = g^x. To sign mm: pick a fresh random nonce kk, set r=gkr = g^k, e=H(r ∥ m)e = H(r \,\|\, m), s=k+ex mod qs = k + ex \bmod q; the signature is (r,s)(r, s). To verify: check that 0≤s<q0 \le s < q and that rr is a group element, then that gs=r⋅yeg^s = r \cdot y^e with e=H(r ∥ m)e = H(r \,\|\, m).

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 dd, 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: gq=1g^q = 1, so exponents of gg count modulo qq. The signer returns s=k+ex mod qs = k + ex \bmod q, so 0≤s<q0 \le s < q, and r=gkr = g^k is a group element. And gs=gk+ex=gk(gx)e=r⋅yeg^s = g^{k + ex} = g^k (g^x)^e = r \cdot y^e, with the same e=H(r ∥ m)e = H(r \,\|\, m) 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
Listing 28.5. Signing and verifying in a 160-bit subgroup modulo a 1024-bit prime. code/bachelor-3/28-public-key-cryptography/listings/schnorr.py
$ python schnorr.py
valid: True
other message: False
same r in both signatures: True
private key recovered: True
Output 28.6. A signature checks for its message and fails for another. A signer whose generator restarts from the same state uses the same nonce twice, and two signatures give away the private key.

The nonce is as secret as the key: two signatures with one kk make two linear equations in the unknowns kk and xx (exercise 28.11). Implementations therefore derive kk 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.

A certificate chain. The client checks each signature with the key in the certificate above it, the validity dates, and that every signer may sign; the chain must end at a key the client already holds.
A certificate chain. The client checks each signature with the key in the certificate above it, the validity dates, and that every signer may sign; the chain must end at a key the client already holds.
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"
Listing 28.6. Checking a chain: dates, issuer names, permission to sign, and each signature. code/bachelor-3/28-public-key-cryptography/listings/toy_cert.py
$ 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
Output 28.7. The chain checks today and fails in 2028; a leaf with a substituted key, a chain Eve signed herself, and a leaf acting as a CA are all refused.

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
Output 28.8. Test case 1 of RFC 5869.

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
Listing 28.7. The server’s side: the handshake secret from the Diffie–Hellman value, a traffic secret bound to the transcript, the signature over the transcript, and the Finished MAC. code/bachelor-3/28-public-key-cryptography/listings/tls13_trace.py
$ 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
Output 28.9. Seven messages, as in RFC 8446. When Eve replaces the server’s key share, the chain still checks, but the signature, made over the transcript the server saw, does not: the client stops.
The TLS 1.3 full handshake, from RFC 8446, with its key schedule. Messages in braces are encrypted with the handshake traffic keys; CertificateVerify signs the transcript up to the certificate, and each Finished is a MAC over the transcript.
The TLS 1.3 full handshake, from RFC 8446, with its key schedule. Messages in braces are encrypted with the handshake traffic keys; CertificateVerify signs the transcript up to the certificate, and each Finished is a MAC over the transcript.

The signature authenticates the Diffie–Hellman exchange, which is what Output 28.1 lacked; the ephemeral secrets aa and bb 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 128⋅r⋅N128 \cdot r \cdot N 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
Listing 28.8. Storing a password with a fresh 16-byte salt and scrypt, and checking it with a comparison whose time does not depend on where the values differ. code/bachelor-3/28-public-key-cryptography/listings/passwords.py
$ 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
Output 28.10. On the author’s laptop, one core, best of three: the slow functions cut an attacker’s guessing rate by a factor of tens to hundreds of thousands.

A fast hash lets a stolen table be tested at millions of guesses per second on one core; scrypt with N=214N = 2^{14} and r=8r = 8 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 p=23p = 23 and g=4g = 4, of order 11. The town hall picks a=3a = 3 and the library b=7b = 7. Compute the values they send and the key they share, by hand.

Solution

Solution of Exercise 28.1.

42=164^2 = 16, 44=256≡34^4 = 256 \equiv 3, so A=43=64≡18A = 4^3 = 64 \equiv 18 and B=47=44⋅42⋅4≡3⋅16⋅4=192≡8(mod23)B = 4^7 = 4^4 \cdot 4^2 \cdot 4 \equiv 3 \cdot 16 \cdot 4 = 192 \equiv 8 \pmod{23}. The town hall computes Ba=83=512≡6B^a = 8^3 = 512 \equiv 6; the library computes Ab=187≡(−5)7A^b = 18^7 \equiv (-5)^7, and 52≡25^2 \equiv 2, 54≡45^4 \equiv 4, 57≡4⋅2⋅5=40≡175^7 \equiv 4 \cdot 2 \cdot 5 = 40 \equiv 17, so (−5)7≡−17≡6(-5)^7 \equiv -17 \equiv 6. Both get 6. And 411≡14^{11} \equiv 1: with 411=44⋅44⋅42⋅4≡3⋅3⋅16⋅4=576=25⋅23+14^{11} = 4^4 \cdot 4^4 \cdot 4^2 \cdot 4 \equiv 3 \cdot 3 \cdot 16 \cdot 4 = 576 = 25 \cdot 23 + 1.

Exercise 28.2 ★

With p=61p = 61, q=53q = 53 and e=17e = 17, compute nn, φ(n)\varphi(n) and dd; encrypt m=65m = 65 and decrypt the result.

Solution

Solution of Exercise 28.2.

n=61⋅53=3233n = 61 \cdot 53 = 3233, φ(n)=60⋅52=3120\varphi(n) = 60 \cdot 52 = 3120. The extended Euclidean algorithm on 3120 and 17 gives d=2753d = 2753: 17⋅2753=46,801=15⋅3120+117 \cdot 2753 = 46{,}801 = 15 \cdot 3120 + 1. Encryption: 6517 mod 3233=279065^{17} \bmod 3233 = 2790; decryption: 27902753 mod 3233=652790^{2753} \bmod 3233 = 65. 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 q=1,000,003q = 1{,}000{,}003, and the largest and smallest numbers of steps it can report.

Solution

Solution of Exercise 28.4.

m=⌈1,000,003 ⌉=1001m = \lceil \sqrt{1{,}000{,}003}\, \rceil = 1001, since 10002=1,000,000<1,000,0031000^2 = 1{,}000{,}000 < 1{,}000{,}003. The program always makes the 1001 baby steps and reports m+im + i, where ii is the index of the successful giant step, between 0 and m−1m - 1: at least 1001, when x<1001x < 1001, and at most 2001.

Exercise 28.5 ★★

verify_buggy in exercises/ex5_schnorr_range.py checks gs=ryeg^s = r y^e but not 0≤s<q0 \le s < q. 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.

gg has order qq, so gs+q=gsg^{s + q} = g^s, and (r,s+q)(r, s + q) passes the check gs′=ryeg^{s'} = r y^e: 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 0≤s<q0 \le s < q, and also checks that rr 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 mp=cd mod (p−1) mod pm_p = c^{d \bmod (p-1)} \bmod p and mqm_q likewise, and recombine them into m mod nm \bmod n. Prove the recombination formula you use, and test the function against plain decryption.

Solution

Solution of Exercise 28.6.

exercises/ex6_crt.py. First, cd mod (p−1)≡cd(modp)c^{d \bmod (p - 1)} \equiv c^d \pmod p: if p∣cp \mid c both sides are 0; otherwise cp−1≡1c^{p-1} \equiv 1 by Fermat’s little theorem, so exponents count modulo p−1p - 1. So mp≡m(modp)m_p \equiv m \pmod p and mq≡m(modq)m_q \equiv m \pmod q. Recombination: h=q−1(mp−mq) mod ph = q^{-1}(m_p - m_q) \bmod p and m′=mq+hqm' = m_q + hq. Modulo qq, m′≡mqm' \equiv m_q; modulo pp, m′≡mq+(mp−mq)=mpm' \equiv m_q + (m_p - m_q) = m_p. And 0≤m′≤(q−1)+(p−1)q=pq−10 \le m' \le (q - 1) + (p - 1)q = pq - 1. By the Chinese remainder theorem, the only number in [0,n)[0, n) congruent to mm modulo pp and qq is mm, so m′=mm' = m. The test compares it with plain decryption on 20 random messages and on messages divisible by pp or qq; rsa_demo.py uses it for its count.

Exercise 28.7 ★★

Prove that (me)d≡m(modn)(m^e)^d \equiv m \pmod n for every 0≤m<n0 \le m < n, including those with gcd⁡(m,n)≠1\gcd(m, n) \ne 1.

Solution

Solution of Exercise 28.7.

Facts used: Fermat’s little theorem; the Chinese remainder theorem. Write ed=1+k(p−1)(q−1)ed = 1 + k(p - 1)(q - 1). Modulo pp: if p∣mp \mid m, then med≡0≡mm^{ed} \equiv 0 \equiv m; otherwise mp−1≡1m^{p-1} \equiv 1 and med=m⋅(mp−1)k(q−1)≡mm^{ed} = m \cdot (m^{p-1})^{k(q-1)} \equiv m. In the same way med≡m(modq)m^{ed} \equiv m \pmod q. So med−mm^{ed} - m is divisible by the distinct primes pp and qq, hence by nn, for every mm. The proof never divides by mm, 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 2⌈q ⌉2\lceil \sqrt{q}\, \rceil multiplications. If xx is uniform, what is the expected number of giant steps?

Solution

Solution of Exercise 28.8.

Let m=⌈q ⌉m = \lceil \sqrt{q}\, \rceil and 0≤x<q≤m20 \le x < q \le m^2; write x=im+jx = im + j with i=⌊x/m⌋i = \lfloor x/m \rfloor and j=x mod mj = x \bmod m, so 0≤i,j<m0 \le i, j < m. The table holds gj↦jg^j \mapsto j for j<mj < m; these powers are distinct since m≤qm \le q and gg has order qq. At giant step ii, hg−im=gx−im=gjh g^{-im} = g^{x - im} = g^j is in the table, so the method stops at step ii or earlier. If it stops earlier, at i′<ii' < i with hg−i′m=gj′h g^{-i'm} = g^{j'}, then x≡i′m+j′(modq)x \equiv i'm + j' \pmod q with 0≤i′m+j′<im≤x<q0 \le i'm + j' < im \le x < q, so the two are equal, which contradicts i′m+j′<xi'm + j' < x. So the answer is xx. Cost: mm multiplications for the table, one for g−mg^{-m} by fast exponentiation (a few dozen, not counted), and i+1≤mi + 1 \le m table look-ups with at most m−1m - 1 multiplications: at most 2m2m. If xx is uniform, ii is nearly uniform on {0,…,m−1}\{0, \ldots, m - 1\}, so about m/2m/2 giant steps are expected, 1.5q1.5\sqrt{q} 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 10910^9 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: 10910^9 guesses in about 330 seconds, five and a half minutes. One scrypt hash: about 2.85×1072.85 \times 10^7 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 aa, bb, 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 gag^a, gbg^b 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 gabg^{ab} 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 gag^a, gbg^b and the transcript from the recording, plus the long-term private keys, which tell nothing about aa or bb: those were chosen independently and erased. So computing the session key from what it holds is the Diffie–Hellman problem on (ga,gb)(g^a, g^b), 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 (r,s1)(r, s_1) on m1m_1 and (r,s2)(r, s_2) on m2m_2 share the nonce kk. Derive xx from them, say when the formula fails, and prove that it is correct. Does a nonce that is merely predictable, say k2=k1+1k_2 = k_1 + 1, also leak xx?

Solution

Solution of Exercise 28.11.

Facts used: qq is prime, so every non-zero residue has an inverse modulo qq. Let ei=H(r ∥ mi)e_i = H(r \,\|\, m_i). Then s1≡k+e1xs_1 \equiv k + e_1 x and s2≡k+e2x(modq)s_2 \equiv k + e_2 x \pmod q, so s1−s2≡(e1−e2)xs_1 - s_2 \equiv (e_1 - e_2) x, and if e1≢e2e_1 \not\equiv e_2, x=(s1−s2)(e1−e2)−1 mod qx = (s_1 - s_2)(e_1 - e_2)^{-1} \bmod q. The formula fails only when e1≡e2e_1 \equiv e_2, which for different messages requires a collision of the hash modulo qq. A predictable nonce leaks the key too: if k2=k1+1k_2 = k_1 + 1, then s2−s1−1≡(e2−e1)xs_2 - s_1 - 1 \equiv (e_2 - e_1)x, and the same division gives xx; 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 T(i)=HMAC(PRK,T(i−1) ∥ info ∥ i)T(i) = \mathrm{HMAC}(\mathit{PRK}, T(i - 1) \,\|\, \mathit{info} \,\|\, i). Pass test cases 1 to 3 of the RFC.

Solution

Solution of Exercise 28.12.

exercises/ex12_hkdf.py: extract is HMAC(salt,ikm)\mathrm{HMAC}(\mathit{salt}, \mathit{ikm}), with 32 zero bytes when the salt is empty; expand chains T(1),T(2),…T(1), T(2), \ldots, 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 255⋅32255 \cdot 32. 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.

  1. Check that g=2g = 2 has order 23 modulo p=47p = 47.
  2. The town hall picks a=5a = 5 and the library b=9b = 9. What do they send?
  3. Compute the shared value both ways.
  4. Why does the protocol use a subgroup of prime order rather than all the residues modulo 47?
  5. Find aa from AA by trying exponents. How many tries does it take at most?
  6. Which of pp, gg, AA, BB, aa, bb and the shared value are public?

Part II — The man in the middle.

  1. In Output 28.1, why does each side’s key agree with Eve’s and not with the other side’s?
  2. What can Eve do with the records that pass that night?
  3. Would the town hall notice anything in the values it receives?
  4. The library publishes a certificate for a signing key, issued by a CA both trust. What must the library sign during the exchange?
  5. In Output 28.9, which check fails when Eve changes the server’s share, and why can Eve not repair it?
  6. Could Eve instead present a certificate for her own key? What stops her?

Part III — Baby-step giant-step on small groups.

  1. From Output 28.2, how does the mean number of steps grow when qq grows 16 times?
  2. Check that no run exceeded 2q2\sqrt{q}, and say why none can.
  3. Explain why the mean is close to 1.5q1.5\sqrt{q}.
  4. How much memory does the table take for q≈236q \approx 2^{36}, and for q≈264q \approx 2^{64}?
  5. The 64-bit subgroup of Output 28.1: how many steps would baby-step giant-step take?
  6. Why can an eavesdropper who records the exchange tonight attack it at leisure later?

Part IV — How large q must be.

  1. For bb bits of security against baby-step giant-step, how many bits must qq have?
  2. What does that give for 128-bit security?
  3. What size of pp does NIST’s table pair with that qq, and why must pp be longer than qq?
  4. What elliptic-curve group gives the same security, and what is gained?
  5. Why is 112-bit strength not enough for records that must stay secret until 2035?
  6. Sum up: how does baby-step giant-step scale, and what qq does 128-bit security need?
Solution

Solution of Problem 28.1.

1. 23 is prime, so the order of 2 is 1 or 23; 2≠12 \ne 1, and 223≡1(mod47)2^{23} \equiv 1 \pmod{47}, which a test checks, so the order is 23.

2. A=25=32A = 2^5 = 32 and B=29=512≡42(mod47)B = 2^9 = 512 \equiv 42 \pmod{47}.

3. Ba=425≡24B^a = 42^5 \equiv 24 and Ab=329=245≡24(mod47)A^b = 32^9 = 2^{45} \equiv 24 \pmod{47}.

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 aa 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. pp, gg, AA and BB are public; aa, bb and the shared value 24 are secret.

7. The town hall computed with E2E_2, believing it came from the library, so its key is gae2g^{a e_2}, which Eve can compute from AA and e2e_2; likewise the library’s key is gbe1g^{b e_1}. Neither key involves both aa and bb.

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: E2E_2 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 gbg^b, 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 2q2\sqrt{q} in each row. The program counts m+im + i with i<mi < m, so at most 2m−12m - 1 with m=⌈q ⌉m = \lceil \sqrt{q}\, \rceil, which is 2q2\sqrt{q} up to rounding.

15. Every run makes the mm baby steps; the giant step that succeeds has an index ii nearly uniform between 0 and m−1m - 1, so about m/2m/2 on average: 1.5m≈1.5q1.5m \approx 1.5\sqrt{q}.

16. 2182^{18} entries for q≈236q \approx 2^{36}, tens of megabytes as Python objects. For q≈264q \approx 2^{64}, 2322^{32} 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. q≈1.2×1019q \approx 1.2 \times 10^{19}, so about 1.5q≈5.2×1091.5\sqrt{q} \approx 5.2 \times 10^9 steps on average and 7×1097 \times 10^9 at most: hours of computation, with a table of a few billion entries.

18. The values AA and BB 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 q=2b\sqrt{q} = 2^{b} operations, so qq needs 2b2b bits.

20. A 256-bit qq.

21. NIST’s table pairs qq of 256 bits with pp of 3072 bits. Baby-step giant-step only uses the group operation, so it depends on qq; but the integers modulo pp also allow methods that use their arithmetic, beyond this chapter, whose cost depends on the size of pp.

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 2202^{20} to 2362^{36} in at most about 2q2\sqrt{q} steps, 1.5q1.5\sqrt{q} on average, so a group gives only half its size in bits of security. 128-bit security needs q≈2256q \approx 2^{256}, with a 3072-bit pp, or a 256-bit elliptic-curve group; and whatever the size, the exchange must be authenticated, or Eve simply sits in the middle.

इस अध्याय में परिभाषित शब्द

शब्दावली के सभी 1050 शब्द देखें