Base64 Encoding in Python

Our first program will demonstrate base64 encoding and decoding. Here’s the full source code:

import base64

def main():
    # Here's the string we'll encode/decode.
    data = "abc123!?$*&()'-=@~"

    # Python provides built-in support for base64 encoding/decoding.
    # Here's how to encode using the standard encoder.
    s_enc = base64.b64encode(data.encode()).decode()
    print(s_enc)

    # Decoding may raise an exception, which you can catch
    # if you don't already know the input to be well-formed.
    try:
        s_dec = base64.b64decode(s_enc).decode()
        print(s_dec)
    except:
        print("Decoding failed")

    print()

    # This encodes/decodes using a URL-safe base64 format.
    u_enc = base64.urlsafe_b64encode(data.encode()).decode()
    print(u_enc)
    try:
        u_dec = base64.urlsafe_b64decode(u_enc).decode()
        print(u_dec)
    except:
        print("Decoding failed")

if __name__ == "__main__":
    main()

To run the program, save the code in a file named base64_encoding.py and use the Python interpreter:

$ python base64_encoding.py
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

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

The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing + vs -) but they both decode to the original string as desired.

In Python, the base64 module provides the necessary functions for base64 encoding and decoding. The b64encode and b64decode functions are used for standard base64, while urlsafe_b64encode and urlsafe_b64decode are used for URL-safe base64.

Note that in Python, we need to encode the string to bytes before encoding to base64, and decode the result back to a string. This is because base64 operations work on byte-like objects.

The try-except blocks are used to handle potential decoding errors, although in this case, we know our input is well-formed.