Introduction

Base64 is the most common encoding method for 8Bit byte on the internet. It is used to convert bytes into ASCII characters. It can also be used for simple encryption for an extra slim layer of protection (just by a little). Python can import Base64 as well and here is how to use Base64 in Python.

How does Base64 work:

Everytime when we use Base64 the following list is generated:

['A', 'B', 'C', ... 'a', 'b', 'c', ... '0', '1', ... '+', '/']

As the Base64 index table, it used "A-Z、a-z、0-9、+、/" 64 printable chars in total as the standard Base64 protocol. Each char represents 6 bits of data.

Steps to encode:

  1. Get the ASCII value of each character in the string
  2. Compute the 8-bit binary equivalent of the ASCII values
  3. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits
  4. Convert the 6-bit binary groups to their respective decimal values
  5. Use the Base64 encoding table to align the respective Base64 values for each decimal value

The Base64 encoding table:

The Functions

Adding the functions and import:

# Adding the import
import base64

# Encoder and decoder functions of base64 providing a string
def encoding(info: str) -> str:
    info_bytes = info.encode("ascii")
    base64_bytes = base64.b64encode(info_bytes)
    encrypted = base64_bytes.decode("ascii")
    return encrypted

def decoding(info: str) -> str:
    base64_bytes = info.encode("ascii")
    info_bytes = base64.b64decode(base64_bytes)
    decrypted = info_bytes.decode("ascii")
    return decrypted

Usage

  • Pass the string to encrypt to encoding function, store the returned encoded string.
  • Pass the string to decrypt to decoding function, store the returned decoded string.

Example

  • The following will translate based on base64 functions:
    # Base64 encoded with encoding function
    UmljaGFyZCBMdQ==
    NDM3eHh4eHh4eA==
    QCE=
    Tm8gYmlydGhkYXkgYWRkZWQ=
    # Base64 decoded with decoding function
    Richard Lu
    437xxxxxxx
    @!
    No birthday added

Reference:
GeeksforGeeks