2 min read

Python Base64 Module

The base64 module provides functions for encoding binary data to printable ASCII characters and decoding such encodings back to binary data. It provides encoding and decoding functions for the data encoding specified in RFC 3548, which defines the Base16, Base32, and Base64 algorithms, and for the de-facto standard Ascii85 and Base85 encodings.

Importing the Module

import base64

Base64 Encoding

base64.b64encode() encodes a bytes-like object using Base64 and returns the encoded bytes.

import base64

data = b"Python is fun"
encoded = base64.b64encode(data)
print(encoded)
# Output: b'UHl0aG9uIGlzIGZ1bg=='

Base64 Decoding

base64.b64decode() decodes the Base64 encoded bytes-like object or ASCII string and returns the decoded bytes.

decoded = base64.b64decode(encoded)
print(decoded)
# Output: b'Python is fun'

URL Safe Encoding

The standard Base64 alphabet uses + and /, which are not URL-safe. The urlsafe_b64encode() function uses - and _ instead.

import base64

data = b"i\xb7\x1d\xfb\xef\xff"
standard_encoded = base64.b64encode(data)
url_safe_encoded = base64.urlsafe_b64encode(data)

print("Standard:", standard_encoded) # Contains + and /
print("URL Safe:", url_safe_encoded) # Contains - and _

Encoding Strings

Since b64encode expects bytes, you often need to encode strings to bytes first, and decode the result back to a string if you want text output.

import base64

message = "Hello World"
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')

print(base64_message)

programming/python/python