Base64 Encoding and Decoding

Base64 Encoding and Decoding#

Base64 encoding is a method used to convert binary data into an ASCII string format by translating it into a radix-64 representation. This is particularly useful for encoding data that needs to be stored and transferred over media that are designed to deal with textual data. Base64 ensures that the data remains intact without modification during transport.

When using Base64, you need to define the characters used in the encoding process. This can be done with:

const string BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

Encoding with Base64#

Encoding data with Base64 involves converting the input data into a sequence of characters from the Base64 character set. This process ensures that the data can be safely transmitted over text-based protocols such as HTTP or email. The following code shows how you can implement Base64 encoding to convert a message into a Base64-encoded string.

Handy Tip

The Base64-encoded message is padded with = characters to ensure that the length is a multiple of 4.

def base64_encode(input_string):
    BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    encoded_string = ""
    value = 0
    bits = -6
    base64_mask = 0x3F

    for character in input_string.encode():
        value = (value << 8) + character
        bits += 8

        while bits >= 0:
            encoded_string += BASE64_CHARS[(value >> bits) & base64_mask]
            bits -= 6
    
    if bits > -6:
        encoded_string += BASE64_CHARS[((value << 8) >> (bits + 8)) & base64_mask]
    
    while len(encoded_string) % 4:
        encoded_string += "="
    
    return encoded_string
message = "Hello, World!"
encoded_message = base64_encode(message)
print(f"Original: {message}")
print(f"Encoded: {encoded_message}")
Original: Hello, World!
Encoded: SGVsbG8sIFdvcmxkIQ==

Decoding with Base64#

Decoding Base64 data involves converting the encoded string back into its original binary form. This process is essential for retrieving the original data after it has been encoded using Base64. The following code shows how you can implement Base64 decoding to convert a Base64-encoded string back into its original form.

def base64_decode(input_string):
    BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    decoded_string = bytearray()
    value = 0
    bits = -8

    for character in input_string:
        if character not in BASE64_CHARS:
            if character == "=":
                break
            continue
        
        value = (value << 6) + BASE64_CHARS.index(character)
        bits += 6

        if bits >= 0:
            decoded_string.append((value >> bits) & 0xFF)
            bits -= 8
    
    return decoded_string.decode()
encoded_message = "SGVsbG8sIFdvcmxkIQ=="
decoded_message = base64_decode(encoded_message)
print(f"Encoded: {encoded_message}")
print(f"Decoded: {decoded_message}")
Encoded: SGVsbG8sIFdvcmxkIQ==
Decoded: Hello, World!