Ilmu Komputer · Buku 2 · Kelas 10–12

High School Computer Science

Buku ini belum tersedia dalam Bahasa Indonesia. Edisi: English.

High School Computer Science · Kelas 10–12

33Cryptography and Secure Communication

A browser opens a connection to a bank it has never contacted before. Every message between them crosses networks run by strangers, and any of them could copy it. Yet within a fraction of a second the two agree on a secret key that none of the listeners knows, and the browser is sure it is talking to the bank and not to an impostor.

This chapter builds that result from four tools: a cipher that needs a shared key, a way to agree on a key in public, a key pair that lets anyone check a signature, and a hash function that reduces a message to a short fingerprint. Every tool is shown on small numbers, small enough to follow by hand and to attack by brute force, and the chapter ends with the steps a browser takes before it shows its padlock.

You already know

A cipher turns a message into an unreadable one with a key, and the shift and substitution ciphers can be broken by trying keys or by counting letter frequencies (Book 1, grade 9). HTTP carries requests and answers between a browser and a server (chapter 8). The exclusive or of two bits is 11 when exactly one of them is 11, and Python’s ^ applies it bit by bit (chapter 3). Fast exponentiation computes xnx^n modulo mm in about 2log⁡2n2 \log_2 n multiplications (chapter 27); Python’s pow(x, n, m) does exactly that. Computing modulo a number, and the miniature RSA, belong to the mathematics book.

33.1 One key for both sides

Definition 33.1 (Symmetric encryption)

Symmetric encryption uses the same key to encrypt and to decrypt. Whoever holds the key can do both; whoever does not should learn nothing from the encrypted message, apart from its length.

The simplest modern-looking cipher combines the message, byte by byte, with a stream of bytes computed from the key, by an exclusive or. Doing it twice gives the message back, since (m⊕k)⊕k=m(m \oplus k) \oplus k = m. Below, the stream comes from Python’s random generator seeded with the key: the same key gives the same stream on both sides.

"""A toy stream cipher: xor with bytes from a seeded generator. Not secure."""
import random


def key_stream(key, n):
    """n bytes that depend only on the key: the same key gives the same bytes."""
    rng = random.Random(key)
    return bytes(rng.randrange(256) for _ in range(n))


def xor_bytes(a, b):
    return bytes(x ^ y for x, y in zip(a, b))


if __name__ == "__main__":
    message = b"Meet at the bridge at noon"
    key = 314159                                  # the shared secret
    cipher = xor_bytes(message, key_stream(key, len(message)))
    print("message:", message.hex(" "))
    print("cipher: ", cipher.hex(" "))
    back = xor_bytes(cipher, key_stream(key, len(cipher)))
    print("decrypted with the key:  ", back.decode())
    wrong = xor_bytes(cipher, key_stream(271828, len(cipher)))
    print("decrypted with another:  ", wrong[:12].hex(" "), "...")
Listing 33.1. A toy stream cipher. code/grade-12/12-secure-communication/listings/xor_stream.py
$ python xor_stream.py
message: 4d 65 65 74 20 61 74 20 74 68 65 20 62 72 69 64 67 65 20 61 74 20 6e 6f 6f 6e
cipher:  2f e9 f7 46 1c fd ea 7e 22 79 0c 6f 3d d1 68 21 e2 ce b8 92 dd 8e 07 42 50 ff
decrypted with the key:   Meet at the bridge at noon
decrypted with another:   61 db 30 50 5c 87 e9 23 24 14 98 ac ...
Output 33.1. With the key the message comes back; with another key, only noise.

This cipher is a toy. The random module is designed for simulations, not for secrets: its output is completely determined by its state, and that state can be rebuilt from enough of its output. The module secrets exists for keys and passwords.

A stream cipher has a second weakness, which no generator cures: the stream must never be used twice.

"""The same key stream used twice: the two messages leak through their xor."""
from xor_stream import key_stream, xor_bytes

key = 314159
m1 = b"Meet at the bridge at noon"
m2 = b"Bring the map and a torch."
c1 = xor_bytes(m1, key_stream(key, len(m1)))
c2 = xor_bytes(m2, key_stream(key, len(m2)))

leak = xor_bytes(c1, c2)                         # the listener computes this
print("c1 xor c2 == m1 xor m2:", leak == xor_bytes(m1, m2))
guess = b"Meet at the "                  # a likely start for a message
print("guessing the start of m1 reveals:", xor_bytes(leak, guess).decode())
Listing 33.2. Two messages, one key stream. code/grade-12/12-secure-communication/listings/xor_reuse.py
$ python xor_reuse.py
c1 xor c2 == m1 xor m2: True
guessing the start of m1 reveals: Bring the ma
Output 33.2. The key stream cancels out; guessing a few words of one message reveals the other.

In practice — Real symmetric ciphers

The cipher used on the web today is AES, chosen by a public competition in 2000 and standardised in 2001. It encrypts blocks of 128128 bits with a key of 128128, 192192 or 256256 bits. With 21282^{128} possible keys, trying them all is out of reach of any computer.

History — A machine broken by mathematicians

The Enigma above is a cipher machine: each key pressed sends a current through wheels of wiring and lights the lamp of another letter, and a wheel turns at every key, so that the same letter is encrypted differently each time. Its key was a setting: the order of the wheels, their rings and starting positions, and the cables of a plugboard, the same at both ends, a symmetric key.

In 1981 the Polish mathematician Marian Rejewski told, in the Annals of the History of Computing, “How Polish Mathematicians Broke the Enigma Cipher”. Photograph: Rama, CC BY-SA 2.0 fr.

Who holds which key. With symmetric encryption both parties hold one secret, which must reach them somehow. With a key pair the public half can be given to anyone, and only its owner holds the private half.
Who holds which key. With symmetric encryption both parties hold one secret, which must reach them somehow. With a key pair the public half can be given to anyone, and only its owner holds the private half.

The real difficulty of symmetric encryption is not the cipher: it is the key. Two parties who have never met have no safe way to send each other one, since every channel they could use is the one they want to protect.

33.2 Agreeing on a key in public

Definition 33.2 (Key exchange)

A key exchange is a protocol by which two parties, sending messages that anyone may read, end with the same secret key, which a listener who saw every message cannot compute in any reasonable time.

The Diffie–Hellman exchange uses a public prime pp and a public number gg. Alice picks a secret aa and sends A=ga mod pA = g^a \bmod p; Bob picks a secret bb and sends B=gb mod pB = g^b \bmod p. Alice computes Ba mod pB^a \bmod p and Bob computes Ab mod pA^b \bmod p. Both equal gab mod pg^{ab} \bmod p (exercise 33.12).

"""Diffie-Hellman: two parties agree on a secret; a listener sees every message."""
import random

rng = random.Random(2026)                        # real code uses the secrets module


def exchange(p, g):
    a = rng.randrange(2, p - 1)                  # Alice's secret, never sent
    b = rng.randrange(2, p - 1)                  # Bob's secret, never sent
    A = pow(g, a, p)                             # Alice sends A
    B = pow(g, b, p)                             # Bob sends B
    alice = pow(B, a, p)                         # Alice computes from B and a
    bob = pow(A, b, p)                           # Bob computes from A and b
    print(f"public: p = {p}, g = {g}")
    print(f"  sent: A = {A}, B = {B}   (the listener sees these)")
    print(f"  kept: a = {a}, b = {b}")
    print(f"  Alice finds {alice}, Bob finds {bob}: same = {alice == bob}")


exchange(23, 5)
exchange(2**61 - 1, 3)                           # a prime of 61 bits
Listing 33.3. The exchange, on a tiny prime and on a prime of 6161 bits. code/grade-12/12-secure-communication/listings/diffie_hellman.py
$ python diffie_hellman.py
public: p = 23, g = 5
  sent: A = 20, B = 18   (the listener sees these)
  kept: a = 5, b = 12
  Alice finds 3, Bob finds 3: same = True
public: p = 2305843009213693951, g = 3
  sent: A = 832448800051935879, B = 155264676293995971   (the listener sees these)
  kept: a = 2193646641555496796, b = 1492337387635134525
  Alice finds 4748317199105114, Bob finds 4748317199105114: same = True
Output 33.3. The listener sees pp, gg, AA and BB; the secrets aa and bb, and the shared number, never travel.
The exchange of the first run. Each side combines its own secret with the other’s message, and both find 3. The listener holds 20 and 18 but neither exponent.
The exchange of the first run. Each side combines its own secret with the other’s message, and both find 33. The listener holds 2020 and 1818 but neither exponent.

To find the shared number, the listener needs aa or bb: an exponent aa such that ga mod p=Ag^a \bmod p = A. This is the discrete logarithm. No fast method is known for well-chosen large primes; the obvious one tries a=1,2,3,…a = 1, 2, 3, \dots in turn.

"""The listener's attack: try a = 1, 2, 3, ... until g**a mod p equals A."""
import random


def is_prime(n):
    return n > 1 and all(n % d for d in range(2, int(n**0.5) + 1))


def prime_factors(n):
    factors, d = set(), 2
    while d * d <= n:
        while n % d == 0:
            factors.add(d)
            n //= d
        d += 1
    return factors | ({n} if n > 1 else set())


def generator(p):
    """The smallest g whose powers give every number from 1 to p - 1."""
    qs = prime_factors(p - 1)
    return next(g for g in range(2, p) if all(pow(g, (p - 1) // q, p) != 1 for q in qs))


def brute_force(p, g, A):
    """Return Alice's secret and the number of multiplications it took."""
    value, a = g, 1
    while value != A:
        value, a = value * g % p, a + 1
    return a, a - 1
Listing 33.4. The listener’s brute force, and a generator for each prime. code/grade-12/12-secure-communication/listings/brute_dlog.py
rng = random.Random(7)
for bits in range(10, 25, 2):
    p = next(n for n in range(2**bits - 1, 0, -1) if is_prime(n))   # largest prime
    g = generator(p)
    steps = []
    for _ in range(12):                          # twelve secrets for each prime
        a = rng.randrange(2, p - 1)
        found, count = brute_force(p, g, pow(g, a, p))
        assert found == a
        steps.append(count)
    mean = sum(steps) / len(steps)
    print(f"{bits} bits: p = {p:>8}, g = {g:>2}, mean steps {mean:>9.0f}"
          f" = {mean / p:.2f} p")
Listing 33.5. The steps counted for primes of 1010 to 2424 bits. code/grade-12/12-secure-communication/listings/brute_dlog.py
$ python brute_dlog.py
10 bits: p =     1021, g = 10, mean steps       426 = 0.42 p
12 bits: p =     4093, g =  2, mean steps      1235 = 0.30 p
14 bits: p =    16381, g =  2, mean steps      8221 = 0.50 p
16 bits: p =    65521, g = 17, mean steps     27907 = 0.43 p
18 bits: p =   262139, g =  2, mean steps    113096 = 0.43 p
20 bits: p =  1048573, g =  2, mean steps    398862 = 0.38 p
22 bits: p =  4194301, g =  7, mean steps   2121149 = 0.51 p
24 bits: p = 16777213, g =  5, mean steps   8238342 = 0.49 p
Output 33.4. The steps grow like pp itself: about half of it on average, so four times more for every two bits.

The function generator picks a gg whose powers take every value from 11 to p−1p - 1, so that the secret can be any of them. Alice’s work, one fast power, grows like the number of bits of pp; the listener’s grows like pp. The problem of the chapter measures this gap.

History — Diffie and Hellman, 1976

Whitfield Diffie and Martin Hellman published the exchange in “New directions in cryptography”, in the IEEE Transactions on Information Theory, in November 1976.

33.3 A pair of keys

Definition 33.3 (Public key, private key, public-key encryption)

A key pair is made of a public key, which its owner gives to anyone, and a private key, which its owner keeps. In public-key encryption, anyone encrypts with the public key, and only the private key decrypts. The private key cannot be computed from the public one in any reasonable time.

In RSA, the public key is a pair (n,e)(n, e), where n=pqn = pq is the product of two secret primes, and the private key is (n,d)(n, d), where dd is chosen so that xed mod n=xx^{ed} \bmod n = x for every x<nx < n. Encrypting is x↦xe mod nx \mapsto x^e \bmod n, decrypting y↦yd mod ny \mapsto y^d \bmod n. Finding dd needs (p−1)(q−1)(p - 1)(q - 1), so it needs the factors of nn. The program below makes the textbook pair from p=61p = 61, q=53q = 53 and e=17e = 17.

Definition 33.4 (Digital signature)

A digital signature of a message is a number computed from the message with a private key. Anyone holding the matching public key can check that the signature fits the message; nobody without the private key can make a signature that fits.

With RSA, signing is the private operation applied to a short fingerprint of the message, its digest (next section), and checking applies the public operation to the signature and compares with the digest.

"""A miniature RSA key pair: encrypt with the public key, sign with the private key."""
import hashlib


def make_keys(p, q, e):
    """From two primes and an exponent: public key (n, e), private key (n, d)."""
    n, phi = p * q, (p - 1) * (q - 1)
    d = pow(e, -1, phi)                          # d * e = 1 modulo phi
    return (n, e), (n, d)


def apply(key, x):
    n, k = key
    return pow(x, k, n)                          # x**k modulo n


def digest_number(message, n):
    """The SHA-256 digest of the message, as a number reduced modulo n."""
    return int.from_bytes(hashlib.sha256(message.encode()).digest(), "big") % n


def sign(private, message):
    return apply(private, digest_number(message, private[0]))


def verify(public, message, signature):
    return apply(public, signature) == digest_number(message, public[0])


if __name__ == "__main__":
    public, private = make_keys(61, 53, 17)
    print("public key (n, e):", public, "  private key (n, d):", private)
    c = apply(public, 65)
    print("65 encrypted:", c, "  decrypted:", apply(private, c))
    s = sign(private, "Pay Bea 20")
    print("signature of 'Pay Bea 20':", s)
    print("checked on 'Pay Bea 20':", verify(public, "Pay Bea 20", s))
    print("checked on 'Pay Bea 90':", verify(public, "Pay Bea 90", s))
Listing 33.6. A miniature key pair: encrypt, decrypt, sign, check. code/grade-12/12-secure-communication/listings/mini_rsa.py
$ python mini_rsa.py
public key (n, e): (3233, 17)   private key (n, d): (3233, 2753)
65 encrypted: 2790   decrypted: 65
signature of 'Pay Bea 20': 2758
checked on 'Pay Bea 20': True
checked on 'Pay Bea 90': False
Output 33.5. The signature fits its message, and not a message with one digit changed.

Here n=3233n = 3233 is factored at a glance, so this key protects nothing. Real keys use an nn of thousands of bits, whose factors nobody can find. The keys are also used differently: public-key operations are slow, so a browser uses them only to agree on a symmetric key and to check who is at the other end, and then encrypts everything with the symmetric key.

History — Rivest, Shamir and Adleman, 1978

Ronald Rivest, Adi Shamir and Leonard Adleman described the method in “A method for obtaining digital signatures and public-key cryptosystems”, in Communications of the ACM, in February 1978; it carries their initials.

33.4 Hash functions

Definition 33.5 (Hash function, digest)

A cryptographic hash function turns a message of any length into a digest of fixed length, so that finding two messages with the same digest, or a message with a given digest, is out of reach. A change to the message, however small, gives a digest unrelated to the first.

SHA-256 is such a function, standardised with others of its family; Python’s hashlib provides it.

"""SHA-256: a fixed-size digest, and a small change that changes everything."""
import hashlib

messages = ["Pay Bea 20", "Pay Bea 21", "Pay Bea 20.", "x" * 10_000]
digests = [hashlib.sha256(m.encode()).hexdigest() for m in messages]
for m, d in zip(messages, digests):
    print(f"{m[:12]:12} ({len(m):5} characters): {d[:32]}...")
print("every digest has", len(digests[0]) * 4, "bits")


def bits_differ(h1, h2):
    return bin(int(h1, 16) ^ int(h2, 16)).count("1")


print("bits that differ between the first two:", bits_differ(digests[0], digests[1]))
print("between the first and the third:", bits_differ(digests[0], digests[2]))
Listing 33.7. Digests of close messages. code/grade-12/12-secure-communication/listings/hashes.py
$ python hashes.py
Pay Bea 20   (   10 characters): 76a9fc2b0b6ddab601d0b2dbe44868d4...
Pay Bea 21   (   10 characters): a46d5ae45cd5136dfae442dc7c63bd58...
Pay Bea 20.  (   11 characters): a5e053cd69e79252255015d48b496b9a...
xxxxxxxxxxxx (10000 characters): e4ee97ec252749d2096447e849628d0d...
every digest has 256 bits
bits that differ between the first two: 131
between the first and the third: 120
Output 33.6. A changed digit or an added full stop changes about half of the 256256 bits, as a random digest would.

A digest guards integrity: whoever knows the digest of a file can check that a copy has not been changed. A signature signs the digest rather than the message, which keeps the slow public-key operation short whatever the length of the message.

Signing and checking. The signer applies its private key to the digest; the checker recomputes the digest of the message it received, applies the public key to the signature, and compares the two numbers.
Signing and checking. The signer applies its private key to the digest; the checker recomputes the digest of the message it received, applies the public key to the signature, and compares the two numbers.

A site that stores its users’ passwords should not store the passwords themselves, but it cannot store plain digests either: two users with the same password would have the same digest, and an attacker who steals the table could look up the digests of a list of common passwords, computed once for all sites.

Definition 33.6 (Salt)

A salt is a random value stored next to a user’s password digest and hashed with the password. Each user gets a different salt, so equal passwords give different digests, and a table of digests computed in advance is useless.

"""Storing passwords: a salted digest, never the password itself."""
import hashlib
import random

rng = random.Random(42)                          # real code uses secrets.token_bytes


def store(password):
    salt = bytes(rng.randrange(256) for _ in range(8))
    return salt, hashlib.sha256(salt + password.encode()).hexdigest()


def check(stored, attempt):
    salt, digest = stored
    return hashlib.sha256(salt + attempt.encode()).hexdigest() == digest


users = {"ada": store("tulip7"), "bea": store("tulip7")}   # the same password
for name, (salt, digest) in users.items():
    print(f"{name}: salt {salt.hex()}  digest {digest[:24]}...")
print("ada logs in with tulip7:", check(users["ada"], "tulip7"))
print("ada logs in with tulip8:", check(users["ada"], "tulip8"))
Listing 33.8. A salted digest, and the check at login. code/grade-12/12-secure-communication/listings/salted.py
$ python salted.py
ada: salt 390c8c7d7247342c  digest 716476ddb1e9365434cf34db...
bea: salt d8100f2f6f770d65  digest 82ac1af8505e2b2fda2476a3...
ada logs in with tulip7: True
ada logs in with tulip8: False
Output 33.7. Two users with the same password have different stored digests.

Safe use

A real password store goes further than this listing. Its salt comes from secrets, not random, and its hash function is deliberately slow, repeating its work many thousands of times, so that an attacker with the stolen table can test only a few guesses per second for each user; hashlib.pbkdf2_hmac is one such function (exercise 33.14). A password store never keeps the password itself, and never sends it back.

33.5 Certificates and the secure web

A signature tells you that a message was signed by the holder of a private key. It does not tell you who that holder is. When a browser receives a public key that claims to be the bank’s, it needs some reason to believe it.

Definition 33.7 (Certificate, certificate authority)

A certificate is a message that binds a name to a public key, signed by someone else. A certificate authority is an organisation whose signatures on certificates are trusted: browsers and operating systems ship with the public keys of a list of such root authorities.

A root rarely signs sites itself. It signs an intermediate authority’s certificate, which signs the site’s. The browser checks each signature with the key in the certificate above, up to a root it already trusts.

"""A chain of toy certificates: each one signed by the key of the one above it."""
from mini_rsa import make_keys, sign, verify

root_pub, root_priv = make_keys(1009, 1013, 65537)        # the authority's keys
mid_pub, mid_priv = make_keys(2003, 2011, 65537)          # an intermediate's
site_pub, site_priv = make_keys(3001, 3011, 65537)        # the web site's


def certificate(name, public, issuer, issuer_private):
    """A name bound to a public key, signed by the issuer."""
    body = f"{name}|{public}|issued by {issuer}"
    return body, sign(issuer_private, body)


mid_cert = certificate("Toy Intermediate", mid_pub, "Toy Root", root_priv)
site_cert = certificate("library.example", site_pub, "Toy Intermediate", mid_priv)


def check_chain(site_cert, mid_cert, trusted_root):
    """The browser knows only the root's public key."""
    ok_mid = verify(trusted_root, *mid_cert)
    mid_key = tuple(int(x) for x in mid_cert[0].split("|")[1].strip("()").split(","))
    ok_site = verify(mid_key, *site_cert)
    return ok_mid and ok_site


if __name__ == "__main__":
    print("site certificate:", site_cert[0], " signature", site_cert[1])
    print("chain accepted:", check_chain(site_cert, mid_cert, root_pub))
    fake_pub, _ = make_keys(4001, 4003, 65537)            # an attacker's key
    forged = (f"library.example|{fake_pub}|issued by Toy Intermediate", site_cert[1])
    print("forged certificate accepted:", check_chain(forged, mid_cert, root_pub))
Listing 33.9. A chain of two certificates, and a forged one. code/grade-12/12-secure-communication/listings/toy_certificate.py
$ python toy_certificate.py
site certificate: library.example|(9036011, 65537)|issued by Toy Intermediate  signature 536127
chain accepted: True
forged certificate accepted: False
Output 33.8. The forgery keeps the site’s name but swaps in another key; the intermediate’s signature no longer fits.
A certificate chain. The browser trusts the root’s key because it came installed; that key checks the intermediate’s certificate, whose key checks the site’s.
A certificate chain. The browser trusts the root’s key because it came installed; that key checks the intermediate’s certificate, whose key checks the site’s.

HTTPS sends HTTP over an encrypted connection (chapter 8); the protocol that encrypts it is TLS. In its current version, published in 2018, a connection starts with a handshake, which the program below plays between two objects of one program, with the toy tools of this chapter.

"""The steps of a secure connection, simplified, between two objects in one program."""
import hashlib
import random

from mini_rsa import sign, verify
from toy_certificate import check_chain, mid_cert, root_pub, site_cert, site_priv
from xor_stream import key_stream, xor_bytes

P, G = 2**61 - 1, 3
rng = random.Random(8446)                        # real code uses the secrets module

# 1. The client says hello and sends its Diffie-Hellman share.
a = rng.randrange(2, P - 1)
hello = ("client hello", pow(G, a, P))
print("client -> server:", hello)

# 2. The server answers with its share, its certificates, and a signature of the talk.
b = rng.randrange(2, P - 1)
answer = ("server hello", pow(G, b, P))
transcript = f"{hello}{answer}"
proof = sign(site_priv, transcript)              # only the site's private key can
print("server -> client:", answer, "+ 2 certificates + signature", proof)

# 3. The client checks the chain up to the root it trusts, then the signature.
site_key = tuple(int(x) for x in site_cert[0].split("|")[1].strip("()").split(","))
print("client: chain valid:", check_chain(site_cert, mid_cert, root_pub),
      "| signature valid:", verify(site_key, transcript, proof))

# 4. Both compute the shared secret, and a session key from it.
client_key = hashlib.sha256(str(pow(answer[1], a, P)).encode()).hexdigest()
server_key = hashlib.sha256(str(pow(hello[1], b, P)).encode()).hexdigest()
print("session keys equal:", client_key == server_key,
      "| key:", client_key[:16] + "...")

# 5. From now on, everything is encrypted with the session key (a toy cipher here).
request = b"GET /catalogue HTTP/1.1"
sent = xor_bytes(request, key_stream(client_key, len(request)))
print("on the wire:", sent.hex(" "))
print("server reads:", xor_bytes(sent, key_stream(server_key, len(sent))).decode())
Listing 33.10. The handshake, simplified: hello, key shares, certificates, signature, session key. code/grade-12/12-secure-communication/listings/handshake_steps.py
$ python handshake_steps.py
client -> server: ('client hello', 1905688035559212229)
server -> client: ('server hello', 1213743860181837420) + 2 certificates + signature 4164372
client: chain valid: True | signature valid: True
session keys equal: True | key: 426eaf36af82f325...
on the wire: 5a 00 91 02 05 32 04 c1 60 5a 27 51 c8 0e 76 d8 9c 30 cc f9 dd 9f 19
server reads: GET /catalogue HTTP/1.1
Output 33.9. After four steps, the request travels encrypted with a key that never travelled.
The handshake, simplified. The real protocol also agrees on which ciphers to use and checks the whole exchange at the end; this book does not study those parts.
The handshake, simplified. The real protocol also agrees on which ciphers to use and checks the whole exchange at the end; this book does not study those parts.

Each step answers one threat. The key exchange gives a key that listeners cannot compute. The certificate chain tells the browser that the key in the certificate belongs to the name in the address bar. The signature over the exchange shows that the server holds the private key of that certificate, so an impostor who copied the certificate cannot use it. The padlock means exactly this: the connection is encrypted, and the other end proved it is the site whose name is shown. It says nothing about whether that site is honest.

33.6 Exercises

Exercise 33.1 ★

Compute 10110010⊕0110011110110010 \oplus 01100111, bit by bit, then in hexadecimal.

Solution

Solution of Exercise 33.1.

10110010⊕01100111=1101010110110010 \oplus 01100111 = 11010101: a 11 wherever the two bits differ. In hexadecimal, b2 xor 67 gives d5, that is 213213.

Exercise 33.2 ★

How many hexadecimal digits has the SHA-256 digest of the empty message? Of a file of one gigabyte?

Solution

Solution of Exercise 33.2.

6464 in both cases: a digest has 256256 bits, four per hexadecimal digit, whatever the length of the message. The digest of the empty message starts e3b0c44298fc1c14.

Exercise 33.3 ★

Compute 56 mod 235^6 \bmod 23 by hand, squaring as fast exponentiation does.

Solution

Solution of Exercise 33.3.

6=1106 = 110 in binary. 52=255^2 = 25, which is 22 modulo 2323; 54=22=45^4 = 2^2 = 4; 56=54×52=4×2=85^6 = 5^4 \times 5^2 = 4 \times 2 = 8. So 56 mod 23=85^6 \bmod 23 = 8, in three multiplications.

Exercise 33.4 ★

With the miniature key pair of the chapter, decrypt 855855. Which message gives it?

Solution

Solution of Exercise 33.4.

8552753 mod 3233=123855^{2753} \bmod 3233 = 123: the message 123123, whose encryption 12317 mod 3233123^{17} \bmod 3233 is indeed 855855. The tests compute both.

Exercise 33.5 ★

Write xor_bytes(a, b), which refuses two byte strings of different lengths.

Solution

Solution of Exercise 33.5.

def xor_bytes(a, b):

if len(a) != len(b):

raise ValueError("the two byte strings must have the same length")

return bytes(x ^ y for x, y in zip(a, b))

Without the check, zip would stop at the shorter one, and the end of a message would be silently lost.

Exercise 33.6 ★★

A messaging program encrypts every message with key_stream(key, n), always from the start of the stream. Show what a listener learns, and change the program so that each message gets its own stream.

Solution

Solution of Exercise 33.6.

Every message is xored with the same bytes, so the xor of any two encrypted messages is the xor of the two plain ones, as in xor_reuse.py: guessing a few words of one reveals the same places of all the others. The fix gives each message a number used once, a nonce, sent in clear with the message, and builds the stream from the key and the nonce together:

key_stream(f"{key}:{nonce}", len(message))

The nonce may be public; what matters is that a key and a nonce are never used together twice.

Exercise 33.7 ★★

Write dh_shared(p, a, B), Alice’s computation of the shared number. Why does it not need gg?

Solution

Solution of Exercise 33.7.

def dh_shared(p, a, B): return pow(B, a, p). The number gg is already inside B=gb mod pB = g^b \bmod p; Alice needs only Bob’s message, her own secret and the modulus.

Exercise 33.8 ★★

Explain from the output of the brute force why each bit added to the prime doubles the listener’s work on average, while Alice’s work grows by one or two multiplications.

Solution

Solution of Exercise 33.8.

The listener tries exponents until it meets the secret, which may be anywhere between 22 and p−2p - 2: on average about p/2p/2 tries, and the output shows means from 0.30 p0.30\,p to 0.51 p0.51\,p. One more bit doubles pp, so it doubles the mean. Alice’s fast power makes at most two multiplications per bit of her exponent, so one more bit adds at most two.

Exercise 33.9 ★★

A checking function applies the public key to the signature and compares the result with the message turned into a number, int.from_bytes(message.encode(), "big") % n. What happens with the signatures of mini_rsa.py?

Solution

Solution of Exercise 33.9.

The signature was made on the digest, so the public key turns it back into the digest modulo nn, not into the message number: the comparison fails, and every genuine signature is refused. (By chance it would succeed about once in 32333233 messages.) Signer and checker must apply the same function to the message. The tests check that the wrong function refuses the signature of "Pay Bea 20", which the right one accepts.

Exercise 33.10 ★★

In the handshake, list the values that must stay secret, and on which side; list those that may be seen by anyone.

Solution

Solution of Exercise 33.10.

Secret: the browser’s exponent aa; the server’s exponent bb and the site’s private key; the private keys of the authorities, held by them; the shared number and the session key, on both sides. Public: pp and gg, the shares AA and BB, the certificates and every public key in them, the signature, and the encrypted bytes.

Exercise 33.11 ★★

Write encrypt_text(public, text), which encrypts each byte of a text with the miniature public key. Encrypt "noon", and explain why this use of RSA is no better than a substitution cipher.

Solution

Solution of Exercise 33.11.

def encrypt_text(public, text):

return [apply(public, byte) for byte in text.encode()]

For "noon" the two o give the same number, and so do the two n. Each byte always gives the same number, so the result is a substitution of 256256 symbols, and letter frequencies break it as in Book 1. Worse, anyone can encrypt all 256256 bytes with the public key and read the table directly. Public-key encryption is applied to one large random number, such as a symmetric key, never to letters one by one.

Exercise 33.12 ★★★

Prove that Alice and Bob find the same number: (gb mod p)a mod p=(ga mod p)b mod p(g^b \bmod p)^a \bmod p = (g^a \bmod p)^b \bmod p.

Solution

Solution of Exercise 33.12.

Computing modulo pp is compatible with products: (xy) mod p=((x mod p)(y mod p)) mod p(xy) \bmod p = ((x \bmod p)(y \bmod p)) \bmod p. Applied aa times, (x mod p)a mod p=xa mod p(x \bmod p)^a \bmod p = x^a \bmod p. With x=gbx = g^b: (gb mod p)a mod p=gba mod p(g^b \bmod p)^a \bmod p = g^{ba} \bmod p. In the same way Bob’s number is gab mod pg^{ab} \bmod p, and ab=baab = ba.

Exercise 33.13 ★★★

With p=61p = 61, q=53q = 53, e=17e = 17 and d=2753d = 2753, show that xed mod 3233=xx^{ed} \bmod 3233 = x for every xx that is a multiple of neither 6161 nor 5353, using Fermat’s little theorem: xr−1 mod r=1x^{r - 1} \bmod r = 1 for a prime rr that does not divide xx.

Solution

Solution of Exercise 33.13.

ed=17×2753=46 801=1+15×3120ed = 17 \times 2753 = 46\,801 = 1 + 15 \times 3120, and 3120=60×523120 = 60 \times 52. Take xx not a multiple of 6161. Fermat gives x60 mod 61=1x^{60} \bmod 61 = 1, so xed=x⋅(x60)15×52x^{ed} = x \cdot (x^{60})^{15 \times 52} leaves the remainder of xx modulo 6161. In the same way, with x52 mod 53=1x^{52} \bmod 53 = 1, xedx^{ed} and xx have the same remainder modulo 5353. So xed−xx^{ed} - x is a multiple of 6161 and of 5353, two different primes, hence of 32333233: xed mod 3233=xx^{ed} \bmod 3233 = x for x<3233x < 3233. (It holds for the multiples too, but they need another line; the tests check all 32333233 values.)

Exercise 33.14 ★★★

Write store_password and check_password with hashlib.pbkdf2_hmac, a salt of 1616 bytes from os.urandom, and a number of rounds kept with the digest. Why keep the number of rounds?

Solution

Solution of Exercise 33.14.

def store_password(password, rounds=600_000):

salt = os.urandom(16)

digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, rounds)

return salt, rounds, digest

def check_password(stored, attempt):

salt, rounds, digest = stored

trial = hashlib.pbkdf2_hmac("sha256", attempt.encode(), salt, rounds)

return hmac.compare_digest(trial, digest)

The number of rounds is kept so that it can be raised later, as machines get faster: old entries are still checked with their own number, and rewritten with the new one at the user’s next login. hmac.compare_digest compares the two digests without stopping at the first difference, so that the time the check takes says nothing about how much of a guess was right.

Exercise 33.15 ★★★

Mallory sits between Alice and Bob and can change their messages. Show that, without certificates, she can run one exchange with each and read everything. Which step of the handshake stops her?

Solution

Solution of Exercise 33.15.

Mallory keeps Alice’s AA and sends Bob her own M=gm mod pM = g^m \bmod p; she does the same with Bob’s BB. Alice computes MaM^a, which Mallory knows as AmA^m; Bob computes Mb=BmM^b = B^m. Mallory now shares one key with each, decrypts each message, reads or changes it, and encrypts it again for the other: neither notices anything. She needs only to sit on the path and to know pp and gg, which are public. The certificate and the signature over the exchange stop her: the server’s share comes signed by a key that a trusted chain ties to the site’s name, and Mallory cannot sign her own share with that key.

33.7 Problem: A Secret Agreed in Public

Problem 33.1

Weekend problem — how long would the listener need?

This problem follows the Diffie–Hellman exchange from a prime of 55 bits to the primes in use, with the outputs 33.3 and 33.4.

Part I — A small prime.

  1. List the powers 51,52,…,5225^1, 5^2, \dots, 5^{22} modulo 2323, each from the one before. Which values appear?
  2. Why is it important that every value from 11 to 2222 appears?
  3. Would g=2g = 2 do as well? List its powers modulo 2323.
  4. How many multiplications does Alice need for 55 mod 235^5 \bmod 23 by fast exponentiation?

Part II — The exchange.

  1. Check A=20A = 20 and B=18B = 18 with the list of question 1.
  2. Check that 185 mod 23=2012 mod 23=318^5 \bmod 23 = 20^{12} \bmod 23 = 3.
  3. Using the list, find aa from A=20A = 20 as the listener would. How many tries?
  4. For the 6161-bit prime of the output, how many multiplications does Alice need for AA, at most?

Part III — The listener’s work.

  1. In the brute-force output, why is the mean number of steps near p/2p/2?
  2. Why does it vary from one prime to another, between 0.30 p0.30\,p and 0.51 p0.51\,p?
  3. From 1010 to 2424 bits, by what factor did the mean grow? By what factor did pp grow?
  4. State how the listener’s work grows with the number of bits kk of the prime.
  5. Write expected_steps(k) for a kk-bit prime, and compare it with the output.

Part IV — Real sizes.

  1. Assume a machine that tries 10910^9 exponents per second. How long for the 2424-bit prime?
  2. How long for the 6161-bit prime of the output, on average?
  3. How long for a prime of 20482048 bits? Give a power of ten of years.
  4. How long does Alice’s computation take for a prime of 20482048 bits, in multiplications?
  5. Cleverer methods than brute force exist for the discrete logarithm. What does that change in the choice of the prime’s size?
  6. Why is Diffie–Hellman alone not enough for a browser? Which section answers that?
  7. State the result: how the listener’s work grows with the size of the prime, and what it means for a 20482048-bit prime.
Solution

Solution of Problem 33.1.

1. 5,2,10,4,20,8,17,16,11,9,22,18,21,13,19,3,15,6,7,12,14,15, 2, 10, 4, 20, 8, 17, 16, 11, 9, 22, 18, 21, 13, 19, 3, 15, 6, 7, 12, 14, 1: every number from 11 to 2222, once each.

2. Then AA can be any of the 2222 values, and the listener has 2222 candidates for aa. With fewer values, there are fewer secrets to try.

3. No: 211 mod 23=12^{11} \bmod 23 = 1, so the powers of 22 repeat after 1111 values, and only 1111 different shares are possible.

4. 5=1015 = 101 in binary: 525^2, 545^4, then 54×55^4 \times 5: three multiplications.

5. 555^5 is the fifth value of the list, 2020; 5125^{12} the twelfth, 1818.

6. 185 mod 23=318^5 \bmod 23 = 3 and 2012 mod 23=320^{12} \bmod 23 = 3, as the program printed.

7. 2020 is the fifth power: a=5a = 5, found at the fifth try.

8. The exponent has at most 6161 bits: at most about 2×61=1222 \times 61 = 122 multiplications.

9. The secret is drawn evenly from 22 to p−2p - 2, and the search stops when it reaches it, so the number of steps is spread evenly too, with a mean near p/2p/2.

10. Each line is the mean of only 1212 secrets; with so few, the mean wanders around p/2p/2.

11. From 426426 to 8 238 3428\,238\,342 steps, about 19 00019\,000 times more; pp grew 16 43216\,432 times. The two factors agree within the wandering of question 10.

12. About 2k−12^{k - 1} steps for a kk-bit prime: it doubles with each bit.

13. def expected_steps(k): return 2 ** (k - 1). For 2424 bits, 8 388 6088\,388\,608 against 8 238 3428\,238\,342 counted.

14. 8.4×106/1098.4 \times 10^6 / 10^9: under a hundredth of a second.

15. 260/109≈1.15×1092^{60} / 10^9 \approx 1.15 \times 10^9 seconds, about 36.536.5 years.

16. 22047/1092^{2047} / 10^9 seconds is about 5.1×105995.1 \times 10^{599} years.

17. At most about 2×2048=40962 \times 2048 = 4096 multiplications of 20482048-bit numbers, a small fraction of a second.

18. The prime is chosen large enough against the best known method, not against brute force. Faster methods are why the prime has thousands of bits, where brute force alone would be stopped by a few hundred.

19. It gives a key, but not the identity of the other end: a man in the middle can run one exchange with each side (exercise 33.15). Certificates, in the last section, answer that.

20. Brute force needs about p/2p/2 tries, so the listener’s work doubles with each bit of the prime: counted from 1010 to 2424 bits, it grew from 426426 to 8.28.2 million steps, always between 0.30 p0.30\,p and 0.51 p0.51\,p. At 10910^9 tries per second, a prime of 20482048 bits would take about 5×105995 \times 10^{599} years, while Alice needs about 40964096 multiplications.

Istilah yang didefinisikan dalam bab ini

Lihat semua 1050 istilah di glosarium