How to base64 encode and decode in Python

Base64 encoding and decoding is used when there needs to transfer or store data. Base64 converts text data into binary data.

Every programming language has own functions to encode and decode in Base64 format. Python language uses base64 module to easily methods to encode and decode in base64 format.

First create base64_encode.py file and paste the below code.

import base64

text_data = "This is text message"
ascii_data = text_data.encode('ascii')
base64_byte_data = base64.b64encode(ascii_data)

encoded_data = base64_byte_data.decode('ascii')

print(encoded_data)

Now run the command in Terminal to see output of encoded data.

python3 base64_encode.py
VGhpcyBpcyB0ZXh0IG1lc3NhZ2U=

To decode base64, same way create base64_decode.py file and put the below code.

import base64

encoded_data = "VGhpcyBpcyB0ZXh0IG1lc3NhZ2U="
base64_byte_data = encoded_data.encode('ascii')
ascii_data = base64.b64decode(base64_byte_data)

text_data = ascii_data.decode('ascii')

print(text_data)

And run the command in Terminal to see decoded data.

python3 base64_decode.py
This is text message

 

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment