Skip to content
background-image background-image

Base64 Encoding and Decoding Example

This example demonstrates how to encode and decode Base64 strings in Python.

Introduction

Base64 encoding is a widely used method to represent binary data as ASCII text. It is commonly employed for tasks such as encoding binary files into text format or securely transmitting binary data as text over text-based protocols.

In this example, we will explore two processes:

  1. Encode: We will take an input string, "Hello," and encode it into its Base64 representation.
  2. Decode: We will take a Base64 encoded string, "SGVsbG8=", and decode it back into the original "Hello" string.

Encode

INPUT_DATA = [{ "data": "Hello" }]

from base64 import b64encode  # Import the b64encode function from the base64 module

# Encode the input string to bytes
bytes_ = INPUT_DATA[0]["data"].encode("utf-8")

# Encode the bytes to Base64 bytes
encoded_bytes = b64encode(bytes_)

# Decode the Base64 bytes to a string
encoded_string = encoded_bytes.decode("utf-8")

return [{ "data": encoded_string }]  # Return the encoded string, which is "SGVsbG8="

Decode

INPUT_DATA = [{ "data": "SGVsbG8=" }]

from base64 import b64decode  # Import the b64decode function from the base64 module

# Encode the input string to bytes
bytes_ = INPUT_DATA[0]["data"].encode("utf-8")

# Decode the Base64 bytes to bytes
decoded_bytes = b64decode(bytes_)

# Decode the bytes to a string
decoded_string = decoded_bytes.decode("utf-8")

return [{ "data": decoded_string }]  # Return the decoded string, which is "Hello"

Conclusion

This Base64 encoding and decoding example demonstrates how to convert data between binary and text formats using Python. Whether you need to encode binary data for safe transmission or decode Base64-encoded data back into its original form, Python's base64 module provides the necessary tools for these operations.