Skip to content

Commit d82cf52

Browse files
QuartzAlcclauss
andauthored
split into usable functions and added docstrings for base32 cipher (#5466)
* split into usable functions and added docstrings * Simplified code Co-authored-by: Christian Clauss <[email protected]> * Simplified code Co-authored-by: Christian Clauss <[email protected]> Co-authored-by: Christian Clauss <[email protected]>
1 parent 0616148 commit d82cf52

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

ciphers/base32.py

+36-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,42 @@
11
import base64
22

33

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")
1034

1135

1236
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

Comments
 (0)