I'm writing a basic base64 encoder just to learn.
import base64
prompt = (input("Type your message -> ")
bp = int(input("Base 16, 32, or 64? (Type a number) -> "))
if bp == 16:
encoded = base64.b16encode(b'prompt')
elif bp == 32:
encoded = base64.b32encode(b'prompt')
elif bp == 64:
encoded = base64.b64encode(prompt)
print(encoded)
When I run the program, it just prints out "prompt" in base 64. How can I get it to print out whatever message I type instead?
CodePudding user response:
You need to use encode() to turn the string into a bytes-like object.
import base64
prompt = input("Type your message -> ")
bp = int(input("Base 16, 32, or 64? (Type a number) -> "))
if bp == 16:
encoded = base64.b16encode(prompt.encode())
elif bp == 32:
encoded = base64.b32encode(prompt.encode())
elif bp == 64:
encoded = base64.b64encode(prompt.encode())
print(encoded)
CodePudding user response:
The base64.bXXencode will raise a TypeError if you pass it a str, you need bytes version of your text, ie an encoded one
Use str.encode("utf-8") and call like b16encode(prompt)
prompt = input("Type your message -> ").encode("utf-8")
bp = int(input("Base 16, 32, or 64? (Type a number) -> "))
if bp == 16:
encoded = base64.b16encode(prompt)
elif bp == 32:
encoded = base64.b32encode(prompt)
elif bp == 64:
encoded = base64.b64encode(prompt)
else:
raise Exception(f"The value {bp} isn't supported")
print(encoded)
