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 when exactly one of them is , and Python’s ^ applies it bit by bit (chapter 3). Fast exponentiation computes modulo in about 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 . 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(" "), "...")
$ 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 ...
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())
$ python xor_reuse.py
c1 xor c2 == m1 xor m2: True
guessing the start of m1 reveals: Bring the ma
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 bits with a key of , or bits. With 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.
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 and a public number . Alice picks a secret and sends ; Bob picks a secret and sends . Alice computes and Bob computes . Both equal (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
$ 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
To find the shared number, the listener needs or : an exponent such that . This is the discrete logarithm. No fast method is known for well-chosen large primes; the obvious one tries 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
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")
$ 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
The function generator picks a whose powers take every value from to , so that the secret can be any of them. Alice’s work, one fast power, grows like the number of bits of ; the listener’s grows like . 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 , where is the product of two secret primes, and the private key is , where is chosen so that for every . Encrypting is , decrypting . Finding needs , so it needs the factors of . The program below makes the textbook pair from , and .
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))
$ 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
Here is factored at a glance, so this key protects nothing. Real keys use an 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]))
$ 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
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.
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"))
$ 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
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))
$ python toy_certificate.py
site certificate: library.example|(9036011, 65537)|issued by Toy Intermediate signature 536127
chain accepted: True
forged certificate accepted: False
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())
$ 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
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 , bit by bit, then in hexadecimal.
Solution
Solution of Exercise 33.1.
: a wherever the two bits differ. In hexadecimal, b2 xor 67 gives d5, that is .
Exercise 33.2 ★
How many hexadecimal digits has the SHA-256 digest of the empty message? Of a file of one gigabyte?
Exercise 33.3 ★
Compute by hand, squaring as fast exponentiation does.
Solution
Solution of Exercise 33.3.
in binary. , which is modulo ; ; . So , in three multiplications.
Exercise 33.4 ★
With the miniature key pair of the chapter, decrypt . Which message gives it?
Solution
Solution of Exercise 33.4.
: the message , whose encryption is indeed . 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 ?
Solution
Solution of Exercise 33.7.
def dh_shared(p, a, B): return pow(B, a, p). The number is already inside ; 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 and : on average about tries, and the output shows means from to . One more bit doubles , 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 , not into the message number: the comparison fails, and every genuine signature is refused. (By chance it would succeed about once in 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 ; the server’s exponent 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: and , the shares and , 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 symbols, and letter frequencies break it as in Book 1. Worse, anyone can encrypt all 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: .
Solution
Solution of Exercise 33.12.
Computing modulo is compatible with products: . Applied times, . With : . In the same way Bob’s number is , and .
Exercise 33.13 ★★★
With , , and , show that for every that is a multiple of neither nor , using Fermat’s little theorem: for a prime that does not divide .
Solution
Solution of Exercise 33.13.
, and . Take not a multiple of . Fermat gives , so leaves the remainder of modulo . In the same way, with , and have the same remainder modulo . So is a multiple of and of , two different primes, hence of : for . (It holds for the multiples too, but they need another line; the tests check all values.)
Exercise 33.14 ★★★
Write store_password and check_password with hashlib.pbkdf2_hmac, a salt of 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 and sends Bob her own ; she does the same with Bob’s . Alice computes , which Mallory knows as ; Bob computes . 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 and , 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 bits to the primes in use, with the outputs 33.3 and 33.4.
Part I — A small prime.
- List the powers modulo , each from the one before. Which values appear?
- Why is it important that every value from to appears?
- Would do as well? List its powers modulo .
- How many multiplications does Alice need for by fast exponentiation?
Part II — The exchange.
- Check and with the list of question 1.
- Check that .
- Using the list, find from as the listener would. How many tries?
- For the -bit prime of the output, how many multiplications does Alice need for , at most?
Part III — The listener’s work.
- In the brute-force output, why is the mean number of steps near ?
- Why does it vary from one prime to another, between and ?
- From to bits, by what factor did the mean grow? By what factor did grow?
- State how the listener’s work grows with the number of bits of the prime.
- Write
expected_steps(k)for a -bit prime, and compare it with the output.
Part IV — Real sizes.
- Assume a machine that tries exponents per second. How long for the -bit prime?
- How long for the -bit prime of the output, on average?
- How long for a prime of bits? Give a power of ten of years.
- How long does Alice’s computation take for a prime of bits, in multiplications?
- Cleverer methods than brute force exist for the discrete logarithm. What does that change in the choice of the prime’s size?
- Why is Diffie–Hellman alone not enough for a browser? Which section answers that?
- State the result: how the listener’s work grows with the size of the prime, and what it means for a -bit prime.
Solution
Solution of Problem 33.1.
1. : every number from to , once each.
2. Then can be any of the values, and the listener has candidates for . With fewer values, there are fewer secrets to try.
3. No: , so the powers of repeat after values, and only different shares are possible.
4. in binary: , , then : three multiplications.
5. is the fifth value of the list, ; the twelfth, .
6. and , as the program printed.
7. is the fifth power: , found at the fifth try.
8. The exponent has at most bits: at most about multiplications.
9. The secret is drawn evenly from to , and the search stops when it reaches it, so the number of steps is spread evenly too, with a mean near .
10. Each line is the mean of only secrets; with so few, the mean wanders around .
11. From to steps, about times more; grew times. The two factors agree within the wandering of question 10.
12. About steps for a -bit prime: it doubles with each bit.
13. def expected_steps(k): return 2 ** (k - 1). For bits, against counted.
14. : under a hundredth of a second.
15. seconds, about years.
16. seconds is about years.
17. At most about multiplications of -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 tries, so the listener’s work doubles with each bit of the prime: counted from to bits, it grew from to million steps, always between and . At tries per second, a prime of bits would take about years, while Alice needs about multiplications.