TExcelTAD

Applied Cryptography Exercises

Eighteen exercises across the whole course, most of them of the kind you meet in code reviews, audits and incident tickets. Try each before opening the answer. A program at the end checks the numerical answers; edit and run it.

# Exercise Practises
1 Name the goal Vocabulary
2 Which ciphertext is ECB? Block Modes
3 Two messages, one pad One-Time Pad, Nonce Reuse
4 Review an encrypted cookie Padding Oracle, AEAD
5 A nonce scheme for a fleet AEAD, Nonce Reuse
6 Birthday arithmetic Hash Properties, DES and 3DES
7 Pick the hash SHA-2, SHA-3, BLAKE2, MD5 and SHA-1
8 Fix a webhook signature Length Extension, HMAC
9 RSA by hand RSA
10 Review RSA usage OAEP and PSS
11 Two signatures, one r ECDSA, Ed25519
12 Where is the man in the middle? Diffie–Hellman, X25519
13 Read an OpenSSL error X.509, Chains, Revocation
14 A CT alert CT and ACME
15 TLS review TLS 1.3 Handshake, Key Schedule, TLS Limits
16 Tokens and passwords Randomness, Password Entropy, Password Storage
17 Keys in the wrong place KDFs and Peppers, Key Management
18 Post-quantum priorities Common Mistakes, Post-Quantum

Exercise 1: Name the goal

For each mechanism, name the security goal(s) it provides: (a) AES-CTR alone; (b) HMAC-SHA-256 with a shared key; (c) an Ed25519 signature; (d) ephemeral X25519 in TLS 1.3; (e) SHA-256 of a download published on the same web page as the download.

Answer

(a) Confidentiality only (malleable, no integrity). (b) Integrity and authenticity between the key holders, no non-repudiation. (c) Integrity, authenticity and non-repudiation. (d) Confidentiality of the session key with forward secrecy (authentication comes from the certificate signature). (e) Only protection against accidental corruption: an attacker who can change the download can change the hash on the same page.

Exercise 2: Which ciphertext is ECB?

A lab service encrypts the same 80-byte record three ways and you receive three ciphertexts A, B and C. How do you tell which one is ECB without any key?

Answer

Split each into 16-byte blocks and count repeats. The record contains the same 16-byte line four times, so the ECB ciphertext has repeated blocks while CBC and CTR have none. The program at the end finds sample B with 3 repeated blocks (four equal blocks = one original + three repeats).

Exercise 3: Two messages, one pad

Two 19-byte messages were XORed with the same keystream. You know the first one is {"action":"refund",. What can you learn about the second, and how much?

Answer

c1 XOR c2 XOR p1 = p2, so all 19 bytes of the second message (as far as the known plaintext reaches). The keystream for those 19 positions is also recovered (c1 XOR p1), so any other message under the same key and nonce is exposed at those positions. For GCM, assume forgeries are possible as well and rotate the key.

Exercise 4: Review an encrypted cookie

A web framework stores the session as AES-CBC(key, IV, json) in a cookie with a random IV and no MAC. Decryption errors return HTTP 500; JSON errors return 400. List two problems and the fix.

Answer

(1) No integrity: CBC is malleable, so a user can flip bits of the IV to change bytes of the first JSON block (for example turning "role":"user" into another four-letter role). (2) Distinct errors for padding (500) and content (400) form a padding oracle, letting anyone decrypt cookies. Fix: AES-GCM (or the framework's signed-and-encrypted session, e.g. Fernet) with one generic error; rotate the key.

Exercise 5: A nonce scheme for a fleet

200 IoT sensors share one AES-GCM key and each sends 10,000 messages a day. Propose a nonce scheme and check it against the per-key limit.

Answer

Better: give each sensor its own key derived with HKDF from a master key and the sensor id, and use a persistent 96-bit counter as nonce. With a shared key, use sensor id (4 bytes) || persistent counter (8 bytes): unique as long as counters survive reboots. Random nonces would also work: 200×10,000×365≈7.3×108200 \times 10{,}000 \times 365 \approx 7.3 \times 10^8 messages a year, below the 232≈4.3×1092^{32} \approx 4.3 \times 10^9 guideline, so rotate the key at least every five years (better yearly).

Exercise 6: Birthday arithmetic

(a) About how many hashes until a collision of SHA-256 truncated to 64 bits? (b) A VPN uses a 64-bit block cipher; after roughly how much traffic per key do block collisions become likely?

Answer

(a) π/2⋅264≈5.4×109\sqrt{\pi/2 \cdot 2^{64}} \approx 5.4 \times 10^9: a few seconds to minutes on a GPU, so 64-bit tags must not be used where collisions matter. (b) About 2322^{32} blocks of 8 bytes = 32 GiB (Sweet32); rekey far below that or use AES.

Exercise 7: Pick the hash

Choose an algorithm for: (a) Git-style content ids for files uploaded by users; (b) a MAC for API requests; (c) storing customer passwords; (d) checking that a backup copied to tape is not corrupted.

Answer

(a) SHA-256 (or BLAKE2b/BLAKE3), never MD5 or SHA-1, because users control the content. (b) HMAC-SHA-256 (or keyed BLAKE2). (c) Argon2id with OWASP parameters (or scrypt, bcrypt). (d) Any good hash; SHA-256 is the simple choice (CRC32 would catch accidents but not deliberate changes).

Exercise 8: Fix a webhook signature

A provider signs webhooks with sig = sha256(secret + body).hexdigest() and receivers check if sig == header. Give the attack, the detection and the fix.

Answer

Attack: length extension; an attacker with one valid (body, sig) can append data and compute a valid signature; plus a timing leak in ==. Detection: code review for sha256(secret + …) and non-constant-time comparisons; a test with a length-extension tool against your own receiver. Fix: hmac.new(secret, timestamp + b"." + body, "sha256"), hmac.compare_digest, a freshness window, and rotate the secret.

Exercise 9: RSA by hand

With p=11p = 11, q=17q = 17, e=7e = 7: compute nn, φ(n)\varphi(n), dd, then encrypt m=9m = 9 and decrypt it.

Answer

n=187n = 187, φ(n)=10⋅16=160\varphi(n) = 10 \cdot 16 = 160, d=23d = 23 because 7⋅23=161=160+17 \cdot 23 = 161 = 160 + 1. c=97 mod 187=70c = 9^7 \bmod 187 = 70, and 7023 mod 187=970^{23} \bmod 187 = 9.

Exercise 10: Review RSA usage

You find cipher = PKCS1_v1_5.new(key) used to decrypt client-supplied tokens, and key.sign(h, padding.PKCS1v15(), …) for release signatures. What do you report?

Answer

The decryption of client-supplied ciphertexts with PKCS#1 v1.5 is a Bleichenbacher risk if any error or timing difference is observable: high severity; move to OAEP or, better, replace RSA encryption with an AEAD token or HPKE. The v1.5 signatures are not broken when verified strictly; recommend PSS or Ed25519 for new keys, low severity.

Exercise 11: Two signatures, one r

Your firmware-signing log shows two ECDSA signatures by the production key with the same rr. What happened, what can an attacker do, and what are the next steps?

Answer

The same nonce kk was used twice; from the two signatures and message hashes, kk and then the private key follow by modular arithmetic, so anyone can sign firmware. Next: revoke the key, distribute a new verification key through a trusted update path, re-sign current images, find the nonce bug and switch to RFC 6979 or Ed25519.

Exercise 12: Where is the man in the middle?

Which of these is open to an active man in the middle? (a) TLS 1.3 with verify=False; (b) SSH where users accept new host keys without checking; (c) WireGuard with pinned peer public keys; (d) unauthenticated X25519 between two microservices on a "trusted" network.

Answer

(a), (b) on first contact or after a change, and (d). WireGuard (c) authenticates the exchange with the pinned static keys.

Exercise 13: Read an OpenSSL error

Explain each and give the fix: (a) error 20 at 0 depth lookup: unable to get local issuer certificate; (b) error 10 … certificate has expired; (c) error 23 … certificate revoked; (d) verify error:num=62:hostname mismatch; (e) error 25 … path length constraint exceeded.

Answer

(a) The chain doesn't reach a trusted root, usually a missing intermediate on the server (serve the full chain) or an untrusted private CA (add it to the client's store). (b) Renew, and automate renewal. (c) The CA revoked it; deploy a new certificate and find out why. (d) The certificate's SAN doesn't include the requested name; reissue with the right names. (e) A CA in the path exceeds its issuer's pathlen; the hierarchy is misconfigured (or someone issued a CA they shouldn't have).

Exercise 14: A CT alert

Your CT monitor reports a certificate for *.lab.test from a CA that your organisation has never used, issued yesterday. Write the first five steps.

Answer
  1. Check internal teams and providers (CDN, SaaS) for a legitimate request. 2. If none: contact the CA with the CT log entry and request revocation. 3. Investigate how validation was passed: DNS changes, DNS provider account access, dangling records, BGP announcements. 4. Add or tighten CAA records and lock down DNS accounts (MFA). 5. Watch for traffic to unexpected servers and for phishing using the names; document as an incident.

Exercise 15: TLS review

A load balancer offers TLS 1.2 with TLS_RSA_WITH_AES_256_CBC_SHA, TLS 1.3, and accepts 0-RTT for all requests; the backend is plain HTTP; SSLKEYLOGFILE is set in its container. List the findings by priority.

Answer

High: the key log file exposes every session's secrets; plain HTTP behind the load balancer exposes everything on that hop; 0-RTT accepted for non-idempotent requests allows replays. Medium: the RSA-key-exchange CBC suite (no forward secrecy, MAC-then-encrypt). Fixes: remove the variable and file, TLS or mTLS to the backend, 0-RTT only for safe GETs or off, TLS 1.2 limited to ECDHE + AEAD.

Exercise 16: Tokens and passwords

(a) How many bits does a passphrase of 4 words picked at random from a 2,048-word list have, compared with 12 random characters from a–z and 0–9? (b) A reset token is random.getrandbits(64). What is wrong? (c) Passwords are stored as bcrypt cost 8. What do you recommend?

Answer

(a) 4log⁡22048=444 \log_2 2048 = 44 bits versus 12log⁡236≈62.012 \log_2 36 \approx 62.0 bits; six words (66 bits) would beat the 12 characters. (b) Mersenne Twister is predictable (624 outputs rebuild the state, or a guessable seed is searched) and 64 bits is short; use secrets.token_urlsafe(32). (c) Raise to cost 12 or move to Argon2id at OWASP parameters, rehashing at login; wrap existing hashes now.

Exercise 17: Keys in the wrong place

A service encrypts customer documents with key = hashlib.sha256(b"CompanyName2026").digest(), hard-coded in the repository. Describe the risk and a target design.

Answer

The key is guessable and in source control: anyone with repository access or a guess decrypts everything, and rotation means a code change. Target: a KEK in a KMS, a random DEK per document wrapped by the KEK (envelope encryption), document ids as AAD, least-privilege unwrap permissions, audit logs, scheduled KEK rotation; re-encrypt existing documents and treat the old key as compromised.

Exercise 18: Post-quantum priorities

Order these for migration and justify: (a) TLS to a patient portal; (b) the code-signing key for a device fleet with a 15-year lifetime; (c) AES-128 backups kept 20 years; (d) an internal dashboard with session data that expires daily.

Answer

(a) first (harvest now, decrypt later on long-lived medical data: hybrid X25519MLKEM768 now); (b) next (the root of trust must stay unforgeable for the devices' lifetime: plan ML-DSA or SLH-DSA, or LMS/XMSS for firmware, and an update path); (c) move to AES-256 when re-encrypting (Grover margin), lower urgency; (d) last.

Checking the numerical answers

python · try it yourself
import math
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

# Exercise 2: three unknown ciphertexts from a lab service. Which one is ECB?
def blocks(ct): return [ct[i:i + 16] for i in range(0, len(ct), 16)]
key = bytes(range(16)); data = (b"user=alice;role=" * 4) + b"status=active..."
mk = lambda m: Cipher(algorithms.AES(key), m).encryptor()
samples = {"A": mk(modes.CTR(bytes(16))).update(data), "B": mk(modes.ECB()).update(data),
           "C": mk(modes.CBC(bytes(16))).update(data)}
for name, ct in samples.items():
    b = blocks(ct)
    print(f"sample {name}: {len(b)} blocks, {len(b) - len(set(b))} repeated")

# Exercise 6: expected hashes until a collision of a 64-bit truncated hash
print(f"64-bit collision after about {math.sqrt(math.pi / 2 * 2**64):.2e} hashes")
# Exercise 9: toy RSA with p = 11, q = 17, e = 7
p, q, e = 11, 17, 7
n, phi = p * q, (p - 1) * (q - 1)
d = pow(e, -1, phi)
print(f"n = {n}, phi = {phi}, d = {d}, enc(9) = {pow(9, e, n)}, dec = {pow(pow(9, e, n), d, n)}")
# Exercise 16: entropy of 4 words drawn from a 2,048-word list and of a 12-character a-z0-9 password
print(f"4 of 2048 words: {4 * math.log2(2048):.0f} bits; 12 chars of 36: {12 * math.log2(36):.1f} bits")
sample A: 5 blocks, 0 repeated
sample B: 5 blocks, 3 repeated
sample C: 5 blocks, 0 repeated
64-bit collision after about 5.38e+09 hashes
n = 187, phi = 160, d = 23, enc(9) = 70, dec = 9
4 of 2048 words: 44 bits; 12 chars of 36: 62.0 bits

Practice problems for this course, with tests in 21 languages: Crack a Caesar Cipher, Decode a Vigenere Cipher, Repeating-Key XOR, Base64 and Base64url Encoding, Merkle Root, Password Entropy Estimate.

Test yourself

A ciphertext's 16-byte blocks contain several exact repeats. What is the most likely mode?

  1. CTR
  2. CBC with a random IV
  3. ECB
  4. GCM

Which single change fixes both the length-extension and the timing problem in Exercise 8?

  1. Use SHA-512
  2. HMAC plus hmac.compare_digest
  3. Base64-encode the signature
  4. Put the secret last

In Exercise 9, what is the private exponent dd?

  1. 7
  2. 23
  3. 160
  4. 187

Two ECDSA signatures by one key share the same rr. What must happen?

  1. Nothing
  2. Treat the private key as compromised: revoke and replace it
  3. Re-sign with the same key
  4. Switch to SHA-1