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.
Code
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: TrueWhat 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
Base64 Encoder & DecoderEncode text to Base64 and decode Base64 back to text with UTF-8 support. Handles Unicode characters correctly using TextEncoder and TextDecoder APIs.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.