Simple Data Encoding and 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 those QR code worked on Django, My friend told me that 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 endoding the data ‘see the source’ and deoding 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’
b’c2VlIHRoZSBzb3VyY2U=’     #this is the data in the encoded form
>>>decoded_data = base64.b64decode(b’c2VlIHRoZSBzb3VyY2U=’)  # here we decode the data back to readable form
b’see the source’

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

  1. base64.decode(input, output) – 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.
  2. base64.encode(input, output) -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.