impl/python/base32_decode.py
1,807 bytes · the Python implementation · view raw
from typing import List
# Padding that each count of data characters past a multiple of 8 needs;
# -1 marks the counts no byte string produces.
_PAD = [0, -1, 6, -1, 4, 3, -1, 1]
def _quintet(ch: str) -> int:
# Character ranges rather than str.isalpha()/isdigit(), which accept
# letters and digits of every script.
if "A" <= ch <= "Z":
return ord(ch) - 65
if "a" <= ch <= "z":
return ord(ch) - 97
if "2" <= ch <= "7":
return ord(ch) - 24
return -1
def base32_decode(text: str) -> List[int]:
"""RFC 4648 base32 back to bytes. Either case; = padding optional but
exact when present; no spaces or other characters; zero bits after the
last byte. The standard library's b32decode differs on several of these,
which is why this is written out."""
if not isinstance(text, str):
raise TypeError("base32 text must be a string")
values = []
padding = 0
for ch in text:
if ch == "=":
padding += 1
continue
v = _quintet(ch)
if v < 0 or padding > 0:
raise ValueError("base32 text may only contain A-Z and 2-7, with = padding at the end")
values.append(v)
rest = len(values) % 8
if _PAD[rest] < 0:
raise ValueError("base32 text has a length that no byte count produces")
if padding > 0 and padding != _PAD[rest]:
raise ValueError("base32 text has the wrong amount of = padding")
out = []
buffer = 0
bits = 0
for v in values:
buffer = ((buffer << 5) | v) & 0x1FFF
bits += 5
if bits >= 8:
out.append((buffer >> (bits - 8)) & 255)
bits -= 8
if buffer & ((1 << bits) - 1):
raise ValueError("base32 text has non-zero bits after its last byte")
return out