Learn › Part 3 · Cryptography and secure protocols
Diffie–Hellman, RSA and man-in-the-middle
Diffie-Hellman key agreement, brute-forcing a small discrete log, RSA key generation and use, padding, and why unauthenticated keys invite man-in-the-middle attacks.
Diffie–Hellman key agreement
Public parameters: prime p and generator g. Alice picks secret a and sends A = ga mod p; Bob picks b and sends B = gb mod p. Both compute K = Ba = Ab = gab mod p. The key itself never crosses the network; security rests on the discrete logarithm problem.
Worked example: the lab relay attack (corrected)
g = 3, p = 19. Powers of 3 mod 19: 3, 9, 8, 5, 15, 7, 2, 6, 18, 16, 10, 11, …
- Client 1 sends A = 5. The relay loops exp = 1, 2, 3, … and finds 34 mod 19 = 5, so a = 4 (after 4 iterations).
- Client 2 sends B = 11. The relay computes K = 114 mod 19 = 11, the same key both clients derive.
- It forwards ciphertext untouched while decrypting a copy: a passive MitM. An active MitM would also alter and re-encrypt messages.
The original lab text gives a = 6 and K = 18; both are arithmetic slips (36 mod 19 = 7 and 116 mod 19 = 1).
Man-in-the-middle: without authentication, Mallory replaces A and B with her own values and shares one key with Alice and another with Bob, relaying between them. Countermeasures: large groups (≥ 2,048-bit p, or elliptic curves) against brute force, and signed half-keys with certificates (authenticated, ephemeral DH such as ECDHE) against substitution. Logjam (2015) showed how downgrading to 512-bit export groups broke real TLS sessions.
RSA
Choose primes p, q; n = pq; φ(n) = (p − 1)(q − 1). Pick e with gcd(e, φ(n)) = 1; d = e−1 mod φ(n).
Encrypt c = me mod n. Decrypt m = cd mod n. Sign with d, verify with e.
Worked example
p = 11, q = 13: n = 143, φ(n) = 120. e = 7 ⇒ d = 103 (7 × 103 = 721 = 6 × 120 + 1). m = 9 ⇒ c = 97 mod 143 = 48; 48103 mod 143 = 9. e = 9 would be invalid, because gcd(9, 120) = 3.
- Security rests on factoring n; use at least 2,048-bit moduli today.
- Textbook RSA is deterministic: an attacker can encrypt each possible message (“yes”/“no”) and compare. Randomised padding (OAEP) fixes this.
- In the lab, the server sends its public key to each client, which pads and encrypts; programs link OpenSSL (
-lssl -lcrypto). - If the client accepts any key that arrives, an attacker swaps in its own key, decrypts, reads or alters, and re-encrypts with the real server key. Verify certificates.
Common pitfalls
- Compute d modulo φ(n), never modulo n.
- Large parameters stop passive brute force; only authentication stops active MitM.
- Do not reduce the RSA ciphertext modulo φ(n).