from typing import Sequence _ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" def base32_encode(bytes: Sequence[int], padding: bool) -> str: """Bytes as RFC 4648 base32: five bits per character, upper case, padded with = to a multiple of eight characters when ``padding`` is true.""" if isinstance(bytes, (str, dict)) or not hasattr(bytes, "__len__"): raise TypeError("bytes must be a list of integers from 0 to 255") if not isinstance(padding, bool): raise TypeError("padding must be true or false") out = [] buffer = 0 bits = 0 for b in bytes: if type(b) is not int or b < 0 or b > 255: raise ValueError("bytes must be a list of integers from 0 to 255") buffer = ((buffer << 8) | b) & 0xFFF bits += 8 while bits >= 5: out.append(_ALPHABET[(buffer >> (bits - 5)) & 31]) bits -= 5 if bits > 0: out.append(_ALPHABET[(buffer << (5 - bits)) & 31]) if padding: while len(out) % 8 != 0: out.append("=") return "".join(out)