Lessons and the learning game

Cryptography for builders

Secure the things you build, in Python on a Raspberry Pi, ending in a door lock that only opens for a signed, fresh command.

The course

Cryptography for builders is an advanced Coding course in seven lessons on a Raspberry Pi 4. Lessons 1 to 6 run on the gallery's traffic light circuit and the project on the gallery servo. Each step is checked against what the Pi prints or what the circuit does.

It teaches honestly: the toy ciphers are there to show how encryption works and breaks, and every lesson says to use vetted libraries for anything real.

  1. Hashes: SHA-256, the avalanche effect (127 of 256 bits flip for one letter), a fixed size for any input, a firmware download checked against its published hash, and an anagram that breaks a homemade hash.
  2. HMAC: why sha256(key + message) is not enough, HMAC built from SHA-256 as RFC 2104 describes, checked against RFC 4231 test case 2 and the hmac module, and lamps for genuine and forged commands.
  3. Symmetric ciphers: Caesar broken in 26 tries, the one-time pad, a toy stream cipher from SHA-256, and the nonce reuse that leaks a door code.
  4. Why not roll your own: a repeating XOR key recovered from one known word, a bit-flipping attack that turns SHUT into OPEN, a timing attack that finds a PIN in 40 tries, and the fix: encrypt, then MAC, and compare in constant time.
  5. Keys and secrets: a seeded key found by replaying seeds, keys from secrets, PBKDF2 with a salt (checked against its test vector), what 1,000 rounds cost an attacker, and keys kept in their own file.
  6. Signed messages: a command|counter|tag format, tamper and replay attacks, a counter that stops replay, and how HMAC tags differ from public-key signatures.
  7. Project: a signed door command.

The project

A servo on GPIO18 is the bolt. It starts by opening for anything typed in the Serial Monitor, then only for commands signed by a simulated phone, then only for fresh ones, and finally with its counter saved to a file so a restart cannot bring old recordings back to life. The last step is a short, honest threat model.

What the Pi's engine does differently

The Pi runs MicroPython 1.29, not CPython:

  • hashlib has SHA-256 built in, and hmac, secrets and hashlib.pbkdf2_hmac are included, so the hand-built versions are checked against the library on the same Pi.
  • secrets here draws on the page's own generator, so it is fine for learning and is not a source of real keys. On a real Pi it reads the operating system's random source.
  • There is no cryptography package or libsodium, so AES-GCM, ChaCha20 and Ed25519 are explained but not run.
  • time.monotonic_ns() follows the simulated clock, which charges every turn of a Python loop the same cost. That is why the timing attack's signal is so clean; on real hardware it is noisy, and still works.

The catalog line also names an ESP32-C3. The course runs on the Pi only.