Data encoding/decoding in python

I was given a QR CODE  and the contents of it were encrypted or encoded data. It could have been any kind of encryption MD 5 hash, Ceaser brute force or any other type of schemes.But, since the company who distributed that QR code worked on Django, I thought the encoding ought to be done using a technique in python and some research led me to the python’s  RFC 3548 :- base 16,base 32 and base 64 encoding and decoding schemes.

This method of encoding requires the base64 module that has to be imported into the script.

This scheme works similar to the uuencode program. The uuencode is a binary to text encoding scheme used in Unix  systems for transferring binary data  over the UUCP(Unix-To-Unix file system).

SO here is how to use BASE 64  method to encode and decode.

The simple methods we use here are the b64encode(b’text’)  and the  b64decode(b’text’). Here the ‘b ‘ signifies we are working with the binary strings . This is the format while coding in python 3.x. But if you are using python 2.7.x then it works fine even if the ‘b ‘ is not mentioned.

here is a sample code of encoding the data ‘see the source’  and decoding it in python3.x:

import base64
encoded_data = base64.b64encode(b'see the source')
Encoded _data has the encoded form of our text -
#'see the source'
print(encoded_data)
>>>b'c2VlIHRoZSBzb3VyY2U='#this is the data in the encoded form
decoded_data = base64.b64decoding(b'c2VlIHRoZSBzb3VyY2U=')
# here we decode the data back to readable form
print(decoded_data)
>>>b'see the source'

Thus here we can see that we were able to successfully extract the original data. But these are the 2 basic methods. This module, BASE64  provides many more functions like

  • base64.decode(inputoutput) – Where input and output represent file objects.This decodes an encoded file and stores the decoded output in the file pointed by the output file object.
  • base64.encode(inputoutput) -Even this method is similar to the previous one but it encodes a text file and stores the encoded contents of input file int the file pointed by output file object.

There also contains methods that are available for standard base64 alphabet , url safe alphabet and base 16 and 32  strings.

akshay pai

I am a data science engineer and I love working on machine learning problems. I have experience in computer vision, OCR and NLP. I love writing and sharing my knowledge with others. This is why I created Source Dexter. Here I write about Python, Machine Learning, and Raspberry Pi the most. I also write about technology in general, books and topics related to science. I am also a freelance writer with over 3 years of writing high-quality, SEO optimized content for the web. I have written for startups, websites, and universities all across the globe. Get in Touch! We can discuss more.

4 thoughts on “Data encoding/decoding in python

Leave a Reply