Python Basics: Encoding Bytes with base64
Some text-based formats need binary data represented as printable characters. Python’s base64 module converts bytes to an ASCII representation and back.
Use Python 3.12 or newer on Linux. Each example runs independently with the standard library and only prints sample data.
Encode a message and read it back
Save as demo_base64_1.py:
import base64
message = "café"
encoded_message = base64.b64encode(message.encode("utf-8"))
print(encoded_message.decode("ascii"))
decoded_message = base64.b64decode(encoded_message)
print(decoded_message.decode("utf-8"))Run it:
python3 demo_base64_1.pyOutput:
Y2Fmw6k=
caféb64encode() accepts bytes and returns bytes. Encode text as UTF-8 first. The Base64 result contains ASCII characters; after decoding Base64, use the original text encoding to recover the message.
Reject unexpected characters
Save as demo_base64_2.py:
import base64
import binascii
encoded_message = "aGk=!"
print(base64.b64decode(encoded_message).decode("utf-8"))
try:
base64.b64decode(encoded_message, validate=True)
except binascii.Error:
print("Rejected invalid Base64")Run it:
python3 demo_base64_2.pyOutput:
hi
Rejected invalid Base64The default decoder discards characters outside the Base64 alphabet before checking padding. Use validate=True when unexpected characters should cause an error. Successful decoding only checks the representation; it does not establish who supplied the data.
Use the URL-safe alphabet
Save as demo_base64_3.py:
import base64
binary_data = b"\xfb\xff"
standard_text = base64.b64encode(binary_data).decode("ascii")
url_safe_text = base64.urlsafe_b64encode(binary_data).decode("ascii")
print(standard_text)
print(url_safe_text)
print(base64.urlsafe_b64decode(url_safe_text) == binary_data)Run it:
python3 demo_base64_3.pyOutput:
+/8=
-_8=
TrueThe URL-safe alphabet replaces + and / with - and _. Padding characters (=) can still appear. Keep them unless the format you are implementing explicitly specifies otherwise.
Base64 is an encoding, not encryption. Anyone with the encoded value can decode it, so it does not protect passwords or other secrets.
References
Acknowledgements
This post was created with assistance from AI.