Base64 Encoding in Python

Python’s Base64 module provides functions to encode binary data to Base64 encoded format and decode such encodings back to binary data.

It implements Base64 encoding and decoding as specified in RFC 3548.

This article contains examples that demonstrate how to perform Base64 encoding in Python.

Python Base64 Encoding Example

You can use the b64encode() function provided by the base64 module to perform Base64 encoding. It accepts a bytes-like object and returns the Base64 encoded bytes -

import base64

data = "abc123!?$*&()'-=@~"

# Standard Base64 Encoding
encodedBytes = base64.b64encode(data.encode("utf-8"))
encodedStr = str(encodedBytes, "utf-8")

print(encodedStr)
# Output
YWJjMTIzIT8kKiYoKSctPUB+

Python Base64 URL and Filename safe Encoding

The default b64encode() functions uses the standard Base64 alphabet that contains characters A-Z, a-z, 0-9, +, and /. Since + and / characters are not URL and filename safe, The RFC 3548 defines another variant of Base64 encoding whose output is URL and Filename safe. This variant replaces + with minus (-) and / with underscore (_) -

import base64

data = "abc123!?$*&()'-=@~"

# URL and Filename Safe Base64 Encoding
urlSafeEncodedBytes = base64.urlsafe_b64encode(data.encode("utf-8"))
urlSafeEncodedStr = str(urlSafeEncodedBytes, "utf-8")

print(urlSafeEncodedStr)
# Output
YWJjMTIzIT8kKiYoKSctPUB-

Also Read: Python Base64 Decode Example

References