---
title: "Cryptography and Secure Communication"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 33
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/33-cryptography-and-secure-communication
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 33 — Cryptography 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](#def-g12-secure-communication-hash) 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](https://one-course.com/books/computer-science/2/en/chapter/8-the-web-clients-servers-and-http#def-g10-http-clients-servers-http) carries requests and answers between a browser and a server (chapter [8](https://one-course.com/books/computer-science/2/en/chapter/8-the-web-clients-servers-and-http#ch-g10-http-clients-servers)). The exclusive or of two bits is $1$ when exactly one of them is $1$, and Python’s `^` applies it bit by bit (chapter [3](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#ch-g10-machine-integers)). [Fast exponentiation](https://one-course.com/books/computer-science/2/en/chapter/27-divide-and-conquer#met-g12-divide-and-conquer-fast-power) computes $x^n$ modulo $m$ in about $2 \log_2 n$ multiplications (chapter [27](https://one-course.com/books/computer-science/2/en/chapter/27-divide-and-conquer#ch-g12-divide-and-conquer)); 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 \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.

```python
"""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.

```python
"""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 $128$ bits with a key of $128$, $192$ or $256$ bits. With $2^{128}$ possible keys, trying them all is out of reach of any computer.

**History — A machine broken by mathematicians.**

![](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-secure-communication/img-82955a5702b8.jpg)

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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-secure-communication/fig-af1ed8f31c8c.svg)

*Who holds which key. With [symmetric encryption](#def-g12-secure-communication-symmetric) 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](#def-g12-secure-communication-symmetric) 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 $p$ and a public number $g$. Alice picks a secret $a$ and sends $A = g^a \bmod p$; Bob picks a secret $b$ and sends $B = g^b \bmod p$. Alice computes $B^a \bmod p$ and Bob computes $A^b \bmod p$. Both equal $g^{ab} \bmod p$ (exercise [33.12](#exo-g12-secure-communication-12)).

```python
"""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 $61$ 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 $p$, $g$, $A$ and $B$; the secrets $a$ and $b$, 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-secure-communication/fig-2e35a7bd046a.svg)

*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.*

To find the shared number, the listener needs $a$ or $b$: an exponent $a$ such that $g^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, \dots$ in turn.

```python
"""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*

```python
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 $10$ to $24$ 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 $p$ itself: about half of it on average, so four times more for every two bits.*

The function `generator` picks a $g$ whose powers take every value from $1$ to $p - 1$, so that the secret can be any of them. Alice’s work, one fast power, grows like the number of bits of $p$; the listener’s grows like $p$. 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](#def-g12-secure-communication-key-pair) is a pair $(n, e)$, where $n = pq$ is the product of two secret primes, and the [private key](#def-g12-secure-communication-key-pair) is $(n, d)$, where $d$ is chosen so that $x^{ed} \bmod n = x$ for every $x < n$. Encrypting is $x \mapsto x^e \bmod n$, decrypting $y \mapsto y^d \bmod n$. Finding $d$ needs $(p - 1)(q - 1)$, so it needs the factors of $n$. The program below makes the textbook pair from $p = 61$, $q = 53$ and $e = 17$.

**Definition 33.4 (Digital signature).**

A *digital signature* of a message is a number computed from the message with a [private key](#def-g12-secure-communication-key-pair). Anyone holding the matching [public key](#def-g12-secure-communication-key-pair) can check that the signature fits the message; nobody without the [private key](#def-g12-secure-communication-key-pair) can make a signature that fits.

With RSA, signing is the private operation applied to a short fingerprint of the message, its [digest](#def-g12-secure-communication-hash) (next section), and checking applies the public operation to the signature and compares with the [digest](#def-g12-secure-communication-hash).

```python
"""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 = 3233$ is factored at a glance, so this key protects nothing. Real keys use an $n$ 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](#def-g12-secure-communication-signature) 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.

```python
"""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](#def-g12-secure-communication-hash) 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 $256$ bits, as a random [digest](#def-g12-secure-communication-hash) would.*

A [digest](#def-g12-secure-communication-hash) guards *integrity*: whoever knows the [digest](#def-g12-secure-communication-hash) of a file can check that a copy has not been changed. A signature signs the [digest](#def-g12-secure-communication-hash) 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-secure-communication/fig-3898bbf73bb5.svg)

*Signing and checking. The signer applies its [private key](#def-g12-secure-communication-key-pair) to the [digest](#def-g12-secure-communication-hash); the checker recomputes the [digest](#def-g12-secure-communication-hash) of the message it received, applies the [public key](#def-g12-secure-communication-key-pair) 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](#def-g12-secure-communication-hash) either: two users with the same password would have the same [digest](#def-g12-secure-communication-hash), and an attacker who steals the table could look up the [digests](#def-g12-secure-communication-hash) 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](#def-g12-secure-communication-hash) and hashed with the password. Each user gets a different salt, so equal passwords give different [digests](#def-g12-secure-communication-hash), and a table of [digests](#def-g12-secure-communication-hash) computed in advance is useless.

```python
"""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](#def-g12-secure-communication-hash), 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](#def-g12-secure-communication-hash).*

**Safe use.**

A real password store goes further than this listing. Its [salt](#def-g12-secure-communication-salt) comes from `secrets`, not `random`, and its [hash function](#def-g12-secure-communication-hash) 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](#exo-g12-secure-communication-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](#def-g12-secure-communication-key-pair). It does not tell you *who* that holder is. When a browser receives a [public key](#def-g12-secure-communication-key-pair) 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](#def-g12-secure-communication-key-pair), 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](#def-g12-secure-communication-key-pair) of a list of such *root* authorities.

A root rarely signs sites itself. It signs an intermediate authority’s [certificate](#def-g12-secure-communication-certificate), which signs the site’s. The browser checks each signature with the key in the [certificate](#def-g12-secure-communication-certificate) above, up to a root it already trusts.

```python
"""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](#def-g12-secure-communication-certificate), 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-secure-communication/fig-022c51ebdac4.svg)

*A [certificate](#def-g12-secure-communication-certificate) chain. The browser trusts the root’s key because it came installed; that key checks the intermediate’s [certificate](#def-g12-secure-communication-certificate), whose key checks the site’s.*

[HTTPS](https://one-course.com/books/computer-science/2/en/chapter/8-the-web-clients-servers-and-http#def-g10-http-clients-servers-https) sends [HTTP](https://one-course.com/books/computer-science/2/en/chapter/8-the-web-clients-servers-and-http#def-g10-http-clients-servers-http) over an encrypted connection (chapter [8](https://one-course.com/books/computer-science/2/en/chapter/8-the-web-clients-servers-and-http#ch-g10-http-clients-servers)); 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.

```python
"""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](#def-g12-secure-communication-certificate), 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-secure-communication/fig-a5c5981ea611.svg)

*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](#def-g12-secure-communication-key-exchange) gives a key that listeners cannot compute. The [certificate](#def-g12-secure-communication-certificate) chain tells the browser that the key in the [certificate](#def-g12-secure-communication-certificate) belongs to the name in the address bar. The signature over the exchange shows that the server holds the [private key](#def-g12-secure-communication-key-pair) of that [certificate](#def-g12-secure-communication-certificate), so an impostor who copied the [certificate](#def-g12-secure-communication-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 \oplus 01100111$, bit by bit, then in hexadecimal.

**Solution of Exercise 33.1.**

$10110010 \oplus 01100111 = 11010101$: a $1$ wherever the two bits differ. In hexadecimal, `b2` xor `67` gives `d5`, that is $213$.

**Exercise 33.2 ★.**

How many hexadecimal digits has the SHA-256 [digest](#def-g12-secure-communication-hash) of the empty message? Of a file of one gigabyte?

**Solution of Exercise 33.2.**

$64$ in both cases: a [digest](#def-g12-secure-communication-hash) has $256$ bits, four per hexadecimal digit, whatever the length of the message. The [digest](#def-g12-secure-communication-hash) of the empty message starts `e3b0c44298fc1c14`.

**Exercise 33.3 ★.**

Compute $5^6 \bmod 23$ by hand, squaring as [fast exponentiation](https://one-course.com/books/computer-science/2/en/chapter/27-divide-and-conquer#met-g12-divide-and-conquer-fast-power) does.

**Solution of Exercise 33.3.**

$6 = 110$ in binary. $5^2 = 25$, which is $2$ modulo $23$; $5^4 = 2^2 = 4$; $5^6 = 5^4 \times 5^2 = 4 \times 2 = 8$. So $5^6 \bmod 23 = 8$, in three multiplications.

**Exercise 33.4 ★.**

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

**Solution of Exercise 33.4.**

$855^{2753} \bmod 3233 = 123$: the message $123$, whose encryption $123^{17} \bmod 3233$ is indeed $855$. The tests compute both.

**Exercise 33.5 ★.**

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

**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 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 $g$?

**Solution of Exercise 33.7.**

`def dh_shared(p, a, B): return pow(B, a, p)`. The number $g$ is already inside $B = 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 of Exercise 33.8.**

The listener tries exponents until it meets the secret, which may be anywhere between $2$ and $p - 2$: on average about $p/2$ tries, and the output shows means from $0.30\,p$ to $0.51\,p$. One more bit doubles $p$, 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](#def-g12-secure-communication-key-pair) 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 of Exercise 33.9.**

The signature was made on the [digest](#def-g12-secure-communication-hash), so the [public key](#def-g12-secure-communication-key-pair) turns it back into the [digest](#def-g12-secure-communication-hash) modulo $n$, not into the message number: the comparison fails, and every genuine signature is refused. (By chance it would succeed about once in $3233$ 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 of Exercise 33.10.**

Secret: the browser’s exponent $a$; the server’s exponent $b$ and the site’s [private key](#def-g12-secure-communication-key-pair); the [private keys](#def-g12-secure-communication-key-pair) of the authorities, held by them; the shared number and the session key, on both sides. Public: $p$ and $g$, the shares $A$ and $B$, the [certificates](#def-g12-secure-communication-certificate) and every [public key](#def-g12-secure-communication-key-pair) 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](#def-g12-secure-communication-key-pair). Encrypt `"noon"`, and explain why this use of RSA is no better than a substitution cipher.

**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 $256$ symbols, and letter frequencies break it as in Book 1. Worse, anyone can encrypt all $256$ bytes with the [public key](#def-g12-secure-communication-key-pair) and read the table directly. [Public-key encryption](#def-g12-secure-communication-key-pair) 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: $(g^b \bmod p)^a \bmod p = (g^a \bmod p)^b \bmod p$.

**Solution of Exercise 33.12.**

Computing modulo $p$ is compatible with products: $(xy) \bmod p = ((x \bmod p)(y \bmod p)) \bmod p$. Applied $a$ times, $(x \bmod p)^a \bmod p = x^a \bmod p$. With $x = g^b$: $(g^b \bmod p)^a \bmod p = g^{ba} \bmod p$. In the same way Bob’s number is $g^{ab} \bmod p$, and $ab = ba$.

**Exercise 33.13 ★★★.**

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

**Solution of Exercise 33.13.**

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

**Exercise 33.14 ★★★.**

Write `store_password` and `check_password` with `hashlib.pbkdf2_hmac`, a [salt](#def-g12-secure-communication-salt) of $16$ bytes from `os.urandom`, and a number of rounds kept with the [digest](#def-g12-secure-communication-hash). Why keep the number of rounds?

**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](#def-g12-secure-communication-hash) 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](#def-g12-secure-communication-certificate), she can run one exchange with each and read everything. Which step of the handshake stops her?

**Solution of Exercise 33.15.**

Mallory keeps Alice’s $A$ and sends Bob her own $M = g^m \bmod p$; she does the same with Bob’s $B$. Alice computes $M^a$, which Mallory knows as $A^m$; Bob computes $M^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 $p$ and $g$, which are public. The [certificate](#def-g12-secure-communication-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 $5$ bits to the primes in use, with the outputs [33.3](#out-g12-secure-communication-dh) and [33.4](#out-g12-secure-communication-brute).

**Part I — A small prime.**

1. List the powers $5^1, 5^2, \dots, 5^{22}$ modulo $23$ , each from the one before. Which values appear?
2. Why is it important that every value from $1$ to $22$ appears?
3. Would $g = 2$ do as well? List its powers modulo $23$ .
4. How many multiplications does Alice need for $5^5 \bmod 23$ by [fast exponentiation](https://one-course.com/books/computer-science/2/en/chapter/27-divide-and-conquer#met-g12-divide-and-conquer-fast-power) ?

**Part II — The exchange.**

5. Check $A = 20$ and $B = 18$ with the list of question 1.
6. Check that $18^5 \bmod 23 = 20^{12} \bmod 23 = 3$ .
7. Using the list, find $a$ from $A = 20$ as the listener would. How many tries?
8. For the $61$ -bit prime of the output, how many multiplications does Alice need for $A$ , at most?

**Part III — The listener’s work.**

9. In the brute-force output, why is the mean number of steps near $p/2$ ?
10. Why does it vary from one prime to another, between $0.30\,p$ and $0.51\,p$ ?
11. From $10$ to $24$ bits, by what factor did the mean grow? By what factor did $p$ grow?
12. State how the listener’s work grows with the number of bits $k$ of the prime.
13. Write `expected_steps(k)` for a $k$ -bit prime, and compare it with the output.

**Part IV — Real sizes.**

14. Assume a machine that tries $10^9$ exponents per second. How long for the $24$ -bit prime?
15. How long for the $61$ -bit prime of the output, on average?
16. How long for a prime of $2048$ bits? Give a power of ten of years.
17. How long does Alice’s computation take for a prime of $2048$ bits, in multiplications?
18. Cleverer methods than brute force exist for the discrete logarithm. What does that change in the choice of the prime’s size?
19. Why is Diffie–Hellman alone not enough for a browser? Which section answers that?
20. State the result: how the listener’s work grows with the size of the prime, and what it means for a $2048$ -bit prime.

**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, 1$: every number from $1$ to $22$, once each.

**2.** Then $A$ can be any of the $22$ values, and the listener has $22$ candidates for $a$. With fewer values, there are fewer secrets to try.

**3.** No: $2^{11} \bmod 23 = 1$, so the powers of $2$ repeat after $11$ values, and only $11$ different shares are possible.

**4.** $5 = 101$ in binary: $5^2$, $5^4$, then $5^4 \times 5$: three multiplications.

**5.** $5^5$ is the fifth value of the list, $20$; $5^{12}$ the twelfth, $18$.

**6.** $18^5 \bmod 23 = 3$ and $20^{12} \bmod 23 = 3$, as the program printed.

**7.** $20$ is the fifth power: $a = 5$, found at the fifth try.

**8.** The exponent has at most $61$ bits: at most about $2 \times 61 = 122$ multiplications.

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

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

**11.** From $426$ to $8\,238\,342$ steps, about $19\,000$ times more; $p$ grew $16\,432$ times. The two factors agree within the wandering of question 10.

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

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

**14.** $8.4 \times 10^6 / 10^9$: under a hundredth of a second.

**15.** $2^{60} / 10^9 \approx 1.15 \times 10^9$ seconds, about $36.5$ years.

**16.** $2^{2047} / 10^9$ seconds is about $5.1 \times 10^{599}$ years.

**17.** At most about $2 \times 2048 = 4096$ multiplications of $2048$-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](#exo-g12-secure-communication-15)). [Certificates](#def-g12-secure-communication-certificate), in the last section, answer that.

**20.** **Brute force needs about $p/2$ tries, so the listener’s work doubles with each bit of the prime: counted from $10$ to $24$ bits, it grew from $426$ to $8.2$ million steps, always between $0.30\,p$ and $0.51\,p$. At $10^9$ tries per second, a prime of $2048$ bits would take about $5 \times 10^{599}$ years, while Alice needs about $4096$ multiplications.**
