Skip to content

split into usable functions and added docstrings for base32 cipher #5466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 36 additions & 7 deletions ciphers/base32.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,42 @@
import base64


def main() -> None:
inp = input("->")
encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object)
b32encoded = base64.b32encode(encoded) # b32encoded the encoded string
print(b32encoded)
print(base64.b32decode(b32encoded).decode("utf-8")) # decoded it
def base32_encode(string: str) -> bytes:
"""
Encodes a given string to base32, returning a bytes-like object
>>> base32_encode("Hello World!")
b'JBSWY3DPEBLW64TMMQQQ===='
>>> base32_encode("123456")
b'GEZDGNBVGY======'
>>> base32_encode("some long complex string")
b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY='
"""

# encoded the input (we need a bytes like object)
# then, b32encoded the bytes-like object
return base64.b32encode(string.encode("utf-8"))


def base32_decode(encoded_bytes: bytes) -> str:
"""
Decodes a given bytes-like object to a string, returning a string
>>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====')
'Hello World!'
>>> base32_decode(b'GEZDGNBVGY======')
'123456'
>>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=')
'some long complex string'
"""

# decode the bytes from base32
# then, decode the bytes-like object to return as a string
return base64.b32decode(encoded_bytes).decode("utf-8")


if __name__ == "__main__":
main()
test = "Hello World!"
encoded = base32_encode(test)
print(encoded)

decoded = base32_decode(encoded)
print(decoded)