|
1 | 1 | import base64
|
2 | 2 |
|
3 | 3 |
|
4 |
| -def main() -> None: |
5 |
| - inp = input("->") |
6 |
| - encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) |
7 |
| - b32encoded = base64.b32encode(encoded) # b32encoded the encoded string |
8 |
| - print(b32encoded) |
9 |
| - print(base64.b32decode(b32encoded).decode("utf-8")) # decoded it |
| 4 | +def base32_encode(string: str) -> bytes: |
| 5 | + """ |
| 6 | + Encodes a given string to base32, returning a bytes-like object |
| 7 | + >>> base32_encode("Hello World!") |
| 8 | + b'JBSWY3DPEBLW64TMMQQQ====' |
| 9 | + >>> base32_encode("123456") |
| 10 | + b'GEZDGNBVGY======' |
| 11 | + >>> base32_encode("some long complex string") |
| 12 | + b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=' |
| 13 | + """ |
| 14 | + |
| 15 | + # encoded the input (we need a bytes like object) |
| 16 | + # then, b32encoded the bytes-like object |
| 17 | + return base64.b32encode(string.encode("utf-8")) |
| 18 | + |
| 19 | + |
| 20 | +def base32_decode(encoded_bytes: bytes) -> str: |
| 21 | + """ |
| 22 | + Decodes a given bytes-like object to a string, returning a string |
| 23 | + >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') |
| 24 | + 'Hello World!' |
| 25 | + >>> base32_decode(b'GEZDGNBVGY======') |
| 26 | + '123456' |
| 27 | + >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=') |
| 28 | + 'some long complex string' |
| 29 | + """ |
| 30 | + |
| 31 | + # decode the bytes from base32 |
| 32 | + # then, decode the bytes-like object to return as a string |
| 33 | + return base64.b32decode(encoded_bytes).decode("utf-8") |
10 | 34 |
|
11 | 35 |
|
12 | 36 | if __name__ == "__main__":
|
13 |
| - main() |
| 37 | + test = "Hello World!" |
| 38 | + encoded = base32_encode(test) |
| 39 | + print(encoded) |
| 40 | + |
| 41 | + decoded = base32_decode(encoded) |
| 42 | + print(decoded) |
0 commit comments