Historically it's been common for militaries to use purpose built mechanical cipher machines like the well known Enigma Machine, or the more mundanely named M-209. Ever since I learned about these devices they fascinated me. This project is a small toy cipher device inspired by them albeit made with a microcontroller instead of mechanical parts and pieces.
I showed this project on Show & Tell, the video is embedded below.
Generate Keys
By default device expects to find a set of keys in the file fizzbuzz.keys in the root of the CIRCUITPY drive. It should be a text file with 4 lines in it. The key file can be generated with the following script included in the project repo.
Run this script and save then copy the resulting fizzbuzz.keys file to your CIRCUITPY drive.
Here is an example of what the key file should look like:
[!;VZjqy,kPgfD.>0eFXK=C7A|~tE)xn+*:SWuNa5b#9UH`3c? r4Y1&d"]-Q\Mm$i8^2o6%'JzhlsT@_}(<p{vLGI/wROB
q5v@:6SA'Lwch%-#p<CYt8.)3 ]yT^meGk;VR0HB$K9}I=WF(Of/nugs\iJar{XxZNodP?_>,*+7[DM|E~&!Uz124`"ljbQ
06*^H8N1:&/\hypP m`f'bn3DG,XJ{_jM=o-c>TuYr;IC[Q]S#$%<ZsFwaxzW+vEt9i@|e(2kKBAq!4LU~}.dg7)5?lV"RO
\lE<Pj5|MQK?.nma!-,yNU*:TG" JoW6F(%92^~8$xvO0e>#krH]h+='&A[7V@u1_LX3ct){zZYp`BIgR/4sd}b;qCSfwiD
fizzbuzz_cipher_keygen.py
import os
import secrets
import random
random.seed(secrets.randbelow(999999999))
alphabet_start_idx = ord(' ')
alphabet_end_idx = ord('~')
alphabet_len = alphabet_end_idx - alphabet_start_idx
indexes = list(range(alphabet_start_idx, alphabet_end_idx + 1))
print(len(indexes))
print(indexes)
fizz_key_list = []
buzz_key_list = []
fizzbuzz_key_list = []
none_key_list = []
for i in range(alphabet_len + 1):
cur_char_index = random.choice(indexes)
fizz_key_list.append(chr(cur_char_index))
indexes.remove(cur_char_index)
indexes = list(range(alphabet_start_idx, alphabet_end_idx + 1))
for i in range(alphabet_len + 1):
cur_char_index = random.choice(indexes)
buzz_key_list.append(chr(cur_char_index))
indexes.remove(cur_char_index)
print(f"len: {len(indexes)}")
indexes = list(range(alphabet_start_idx, alphabet_end_idx + 1))
for i in range(alphabet_len + 1):
cur_char_index = random.choice(indexes)
fizzbuzz_key_list.append(chr(cur_char_index))
indexes.remove(cur_char_index)
indexes = list(range(alphabet_start_idx, alphabet_end_idx + 1))
for i in range(alphabet_len + 1):
cur_char_index = random.choice(indexes)
none_key_list.append(chr(cur_char_index))
indexes.remove(cur_char_index)
if not os.path.exists("fizzbuzz.keys"):
with open("fizzbuzz.keys", "w") as f:
f.write("".join(fizz_key_list) + "\n")
f.write("".join(buzz_key_list) + "\n")
f.write("".join(fizzbuzz_key_list) + "\n")
f.write("".join(none_key_list) + "\n")
else:
print("fizzbuzz.keys already exists, not overwriting.")
print("New keys are:")
print("".join(fizz_key_list))
print("".join(buzz_key_list))
print("".join(fizzbuzz_key_list))
print("".join(none_key_list))
Operation
The device has two modes encrypting, and decrypting, each has their own behavior outlined here. To change modes the user can press the boot button on the Feather.
Encrypting
In encrypting mode input is read from USB Host. The user connects a standard USB HID keyboard to the USB A Host port on the Feather. The user types the cleartext message that they want to encrypt into the keyboard. As they type the feather sends the ciphertext out over the standard USB connection via HID to be typed into the computer or other device that the Feather is plugged in to.
Decrypting
In decrypting mode input is still read from the connected keyboard over USB Host. However for decrypting the user will type in the cipher text value to the keyboard. The cleartext output will appear on the 14 segment displays connected to the feather. Cleartext is not sent to the computer, it is shown only on the 14 segment display module.
Code
The code.py for this project is embedded below. To get the code bundled together with required libraries click the Download Project Bundle button.
import time
import board
import keypad
import supervisor
import sys
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
import adafruit_ht16k33.segments
from fizzbuzz_cipher import FizzBuzzCipher
starttime = time.monotonic()
use_usb_hid = False
# wait a bit for USB to be connected
while time.monotonic() < starttime + 5:
if supervisor.runtime.usb_connected:
use_usb_hid = True
break
# initialize the cipher object
cipher = FizzBuzzCipher("fizzbuzz.keys")
# initialize the display
i2c = board.I2C()
display = adafruit_ht16k33.segments.Seg14x4(i2c)
display.brightness = 0.3
# setup input for mode button
mode_btn = keypad.Keys((board.BUTTON,), value_when_pressed=False, pull=True)
# if USB was connected initialize the HID output stuff
if use_usb_hid:
keyboard = Keyboard(usb_hid.devices)
layout = KeyboardLayoutUS(keyboard)
# state machine variables
MODE_ENCRYPT = 0
MODE_DECRYPT = 1
mode = MODE_ENCRYPT
# buffer for currently shown on the display
displaybuffer = ""
def show_text(segment_display, text):
"""
Show some text on the display
"""
try:
for i in range(4):
segment_display[i] = text[i]
except IndexError:
pass
while True:
# check for incoming data from USB Host keyboard
available = supervisor.runtime.serial_bytes_available
if available: # if a key was pressed
# read which key it was
c = sys.stdin.read(available)
if mode == MODE_ENCRYPT:
# encrypt it
cipherchr = cipher.encrypt(c)
if use_usb_hid:
# output ciphertext out from HID to the computer
layout.write(cipherchr)
else:
# No HID connection, so output ciphertext to the display instead
displaybuffer += cipherchr
displaybuffer = displaybuffer[-4:]
show_text(display, displaybuffer)
elif mode == MODE_DECRYPT:
# decrypt it
clearchr = cipher.decrypt(c)
# show the cleartext on the display
displaybuffer += clearchr
displaybuffer = displaybuffer[-4:]
show_text(display, displaybuffer)
# check for mode button press
event = mode_btn.events.get()
# event will be None if nothing has happened.
if event and event.released:
if mode == MODE_ENCRYPT:
show_text(display, "Dec ")
mode = MODE_DECRYPT
displaybuffer = ""
cipher.reset_keys()
time.sleep(1)
display.fill(0)
elif mode == MODE_DECRYPT:
show_text(display, "Enc ")
mode = MODE_ENCRYPT
cipher.reset_keys()
time.sleep(1)
display.fill(0)
FizzBuzz Cipher Algorithm
The encryption algorithm that the device uses is a custom cipher that I created while tinkering, I call it the FizzBuzz Cipher. It is similar to the Enigma cipher in that it is a polyalphabetic substitution cipher. Like enigma it sends the input text through a series of substitutions, and after each input letter a manipulation is made to the mechanism that determines the substitution for the next letter. With enigma that manipulation is the rotor(s) turning after each key press. In the FizzBizz cipher the substitutions work similarly to the enigma rotors, though the "rotor" is laid out in a straight line inside the key file. To find the ciphertext for a cleartext character the following steps are used:
- Find the cleartext character in the first line of of the key file.
- Find character at the same index in the next line down of the key file. This will be the input character for the next step
- Find the character from the previous step in the 3rd line of the key file
- Find the character at the same index in the 4th and final line of the key file. This is the final ciphertext output character.
So the cleartext input goes through two substitutions that are ultimately based the relative indexes of the characters within the 4 lines of the key file.
The lines in the key file are referred to as fizz key, buzz key, fizzbuzz key, and none key from top to bottom. If you are familiar with a certain basic programming exercise you might be familiar with these terms and one of the core bits of logic used by the algorithm.
Next is the manipulation that makes the cipher polyalphabetic. This part is much different than the enigma algorithms rotors turning. After each keypress and enciphering the keys are "shifted" based on the following rules:
- The fizz key (1st line) has every character whose index is evenly divisible by 2 taken out, grouped together and placed after the remaining odd indexed characters that were left behind. To visualize this I like to imagine the reverse of a "perfect shuffle" of a deck of cards. In a perfect riffle shuffle you split the deck in half, then riffle cards alternating from each half one on top of the other until the deck is completely intermingled. We are doing the reverse to our fizz key. We are splitting the full key into two "piles" or halves placing alternating characters from the key into each, and then stacking to two piles one after the other.
- The buzz key (2nd line) has every character whose index is evenly divisble by 3 taken out, grouped and placed at the end.
- The fizzbuzz key (3rd line) has every character whose index is evenly divisible by both 2 and 3 taken out, grouped and placed at the end.
- The none key (4th line) has a different and less complex rule. It simply takes the first character in the key and moves it to the end. In essence "rotating" the key much like the rotors on the enigma.
With these shifts applied the characters within the keys now have a vastly different relative order, so inputting several copies of the same cleartext letter in a row will result in different, garbled looking, ciphertext coming out. Such as "AAAA" encoding to "rhpG".
By default, using keys generated with the script above the cipher supports all upper and lower case letters, the digits 0-9 and several special characters. Speficially it is every character in ASCII from the space (hex 0x20) to the tilde (hex 0x7E). But the cipher algorithm itself can be used with different keys. The main limitation is that every possible cleartext character must appear exactly once within each of the 4 keys.
This page (USB Cipher Machine) was last updated on July 29, 2025.