Base64 Encoding and Decoding



Base64 encoding converts the binary data into text format, which is passed through communication channel where a user can handle text safely. Base64 is also called as Privacy enhanced Electronic mail (PEM) and is primarily used in email encryption process.

Python includes a module called BASE64 which includes two primary functions as given below −

  • base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object.

  • Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object.

Example - Base64 Encoding

You can use the following piece of code to perform base64 encoding −

main.py

import base64

text = "Encode this text"
text_bytes = text.encode('utf-8') 

encoded_data = base64.b64encode(text_bytes)

print("Encoded text with base 64 is")
print(encoded_data.decode("utf-8"))

Output

The code for base64 encoding gives you the following output −

Encoded text with base 64 is
RW5jb2RlIHRoaXMgdGV4dA==

Example - Base64 Decoding

You can use the following piece of code to perform base64 decoding −

main.py

import base64
decoded_bytes = base64.b64decode("RW5jb2RlIHRoaXMgdGV4dA==")

text = decoded_bytes.decode("utf-8")

print("decoded text is ")
print(text)

Output

The code for base64 decoding gives you the following output −

decoded text is 
Encode this text

Difference between ASCII and base64

You can observe the following differences when you work on ASCII and base64 for encoding data −

  • When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.

  • When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.

Drawback

Base64 algorithm is usually used to store passwords in database. The major drawback is that each decoded word can be encoded easily through any online tool and intruders can easily get the information.

Advertisements