2023-09-24 06:09:32 +00:00
|
|
|
"""
|
|
|
|
Base32 encoding and decoding
|
2018-11-03 20:08:13 +00:00
|
|
|
|
2023-09-24 06:09:32 +00:00
|
|
|
https://en.wikipedia.org/wiki/Base32
|
|
|
|
"""
|
2024-03-13 06:52:41 +00:00
|
|
|
|
2023-09-24 06:09:32 +00:00
|
|
|
B32_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2023-09-24 06:09:32 +00:00
|
|
|
|
|
|
|
def base32_encode(data: bytes) -> bytes:
|
2021-10-22 11:14:35 +00:00
|
|
|
"""
|
2023-09-24 06:09:32 +00:00
|
|
|
>>> base32_encode(b"Hello World!")
|
2021-10-22 11:14:35 +00:00
|
|
|
b'JBSWY3DPEBLW64TMMQQQ===='
|
2023-09-24 06:09:32 +00:00
|
|
|
>>> base32_encode(b"123456")
|
2021-10-22 11:14:35 +00:00
|
|
|
b'GEZDGNBVGY======'
|
2023-09-24 06:09:32 +00:00
|
|
|
>>> base32_encode(b"some long complex string")
|
2021-10-22 11:14:35 +00:00
|
|
|
b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY='
|
|
|
|
"""
|
2023-09-24 06:09:32 +00:00
|
|
|
binary_data = "".join(bin(ord(d))[2:].zfill(8) for d in data.decode("utf-8"))
|
|
|
|
binary_data = binary_data.ljust(5 * ((len(binary_data) // 5) + 1), "0")
|
|
|
|
b32_chunks = map("".join, zip(*[iter(binary_data)] * 5))
|
|
|
|
b32_result = "".join(B32_CHARSET[int(chunk, 2)] for chunk in b32_chunks)
|
|
|
|
return bytes(b32_result.ljust(8 * ((len(b32_result) // 8) + 1), "="), "utf-8")
|
2021-10-22 11:14:35 +00:00
|
|
|
|
|
|
|
|
2023-09-24 06:09:32 +00:00
|
|
|
def base32_decode(data: bytes) -> bytes:
|
2021-10-22 11:14:35 +00:00
|
|
|
"""
|
|
|
|
>>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====')
|
2023-09-24 06:09:32 +00:00
|
|
|
b'Hello World!'
|
2021-10-22 11:14:35 +00:00
|
|
|
>>> base32_decode(b'GEZDGNBVGY======')
|
2023-09-24 06:09:32 +00:00
|
|
|
b'123456'
|
2021-10-22 11:14:35 +00:00
|
|
|
>>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=')
|
2023-09-24 06:09:32 +00:00
|
|
|
b'some long complex string'
|
2021-10-22 11:14:35 +00:00
|
|
|
"""
|
2023-09-24 06:09:32 +00:00
|
|
|
binary_chunks = "".join(
|
|
|
|
bin(B32_CHARSET.index(_d))[2:].zfill(5)
|
|
|
|
for _d in data.decode("utf-8").strip("=")
|
|
|
|
)
|
|
|
|
binary_data = list(map("".join, zip(*[iter(binary_chunks)] * 8)))
|
|
|
|
return bytes("".join([chr(int(_d, 2)) for _d in binary_data]), "utf-8")
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2018-11-03 20:08:13 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2023-09-24 06:09:32 +00:00
|
|
|
import doctest
|
2021-10-22 11:14:35 +00:00
|
|
|
|
2023-09-24 06:09:32 +00:00
|
|
|
doctest.testmod()
|