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'
>>>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
>>>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.


4 thoughts on “Data encoding/decoding in python

  1. Alternatively, we can also achieve the encode/decoding of string in the following way:

    In [1]: “Udhay Prakash”.encode(‘base64’)
    Out[1]: ‘VWRoYXkgUHJha2FzaA==\n’

    In [2]: ‘VWRoYXkgUHJha2FzaA==\n’.decode(‘base64’)
    Out[2]: ‘Udhay Prakash’

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s