B32encode Prints Transcription-Safe Codes

base64.b32encode emits only A-Z and 2-7 so backup codes survive handwriting and reading aloud; decoding restores the stripped padding with a modulo trick.

PythonData Integrity

Code

pythonsnippet
16 lines
import base64

def encode_code(raw: bytes) -> str:
    # RFC 4648 Base32 uses only A-Z and 2-7: unambiguous to read aloud or type
    return base64.b32encode(raw).decode("ascii").rstrip("=")

def decode_code(code: str) -> bytes:
    # Decoding requires padding to a multiple of 8: restore the stripped '=' signs
    padded = code.upper() + "=" * (-len(code) % 8)
    return base64.b32decode(padded)

secret = b"backup-code-01"
encoded = encode_code(secret)
print("encoded:", encoded)
print("charset ok:", all(ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" for ch in encoded))
print("roundtrip:", decode_code(encoded) == secret)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

encoded: MJQWG23VOAWWG33EMUWTAMI
charset ok: True
roundtrip: True

What the demo encodes

encode_code runs base64.b32encode on the raw bytes and strips the trailing = padding, producing a code over the 26 letters plus digits 2-7. The printed charset ok line verifies every output character belongs to that alphabet, with no 0/O or 1/l pairs to confuse.

decode_code reverses it: code.upper() normalizes case, and the modulo trick “=” * (-len(code) % 8) restores exactly the padding that was stripped, so the roundtrip comparison prints True.

Points to remember

  • Base32 is case-insensitive on decode, so hand transcription survives.
  • Padding length is determined by the input length modulo 8.

Interactive Tools for This Topic

FAQ

Why is Base32 safer for backup codes than Base64?
Its alphabet is A-Z and 2-7 only, with no lookalike digits or punctuation, so codes can be read aloud and retyped reliably; the charset check in the demo asserts exactly that.