Encoding and Decoding Base64 Strings in Python

In this post, we will learn Base64 encoding and decoding for strings in Python. In Base64 encoding, we convert the given bytes into ASCII characters. Each Base64 character is 6-bit long. The available characters in Base64 encoding are given below:

  • All uppercase letters
  • All lowercase letters
  • 0-9 digits
  • +
  • /

How to convert a string into a Base64 string?

We can easily convert a given string into a Base64 string by following the below steps for every character:

  1. Get the ASCII value of the character.
  2. Get the 8-bit binary equivalent of obtained ASCII value.
  3. Regroup the digits to convert 8-bit character chunk into 6-bit character chunk.
  4. Now, convert the 6-bit character chunks to decimal value.

We can use the below Base64 encoding table to align the values.

IndexBinaryCharIndexBinaryCharIndexBinaryCharIndexBinaryChar
0000000A16010000Q32100000g48110000w
1000001B17010001R33100001h49110001x
2000010C18010010S34100010i50110010y
3000011D19010011T35100011j51110011z
4000100E20010100U36100100k521101000
5000101F21010101V37100101l531101011
6000110G22010110W38100110m541101102
7000111H23010111X39100111n551101113
8001000I24011000Y40101000o561110004
9001001J25011001Z41101001p571110015
10001010K26011010a42101010q581110106
11001011L27011011b43101011r591110117
12001100M28011100c44101100s601111008
13001101N29011101d45101101t611111019
14001110O30011110e46101110u62111110+
15001111P31011111f47101111v63111111/

Next, we will see how we can encode strings to Base64 and decode Base64 strings using Python.

Base64 Encoding and Decoding in Python

Python provides us with a module named ‘base64’ to encode and decode strings.

Have a look at the Python program given below.

import base64

string = "Codespeedy is fun."
string_bytes = string.encode('ascii')

b64_bytes = base64.b64encode(string_bytes)
b64_string = b64_bytes.decode('ascii')

print("Base64 Encoded String: ", b64_string)

Output:

Base64 Encoded String:  Q29kZXNwZWVkeSBpcyBmdW4u

In the above program, we have first converted the given string into byte-like objects. Next, we have encoded it into base64 encoding using the base64 module which gives us a byte-like object. We use the decode() method to get the encoded string from this byte-like object.

We can also decode a base64 string using the base64 module. See the below Python program.

import base64

b64_string = "Q29kZXNwZWVkeSBpcyBmdW4u"
b64_bytes = b64_string.encode('ascii')

string_bytes = base64.b64decode(b64_bytes)
string = string_bytes.decode('ascii')

print(string)

Output:

Codespeedy is fun.

Thank you.

Also read: How to encode a string in MD5 using Python

Leave a Reply

Your email address will not be published. Required fields are marked *