Encryption-Decryption in Python Django

Sometimes we need to encrypt critical information in out Django App. For example client might ask you to store the user information in encrypted format for extra security. Or you might be required to pass some data in URL in encrypted format.

Here we will see how can we encrypt and decrypt the information in Django.

Once you are done with initial setup of project and added the first app, create a new directory or add a new python package with the name utility  in your app.

Create _init__.py  file in the utility directory.

Add a new file, name it encryption_util.py  in utility directory.

Encryption:

Add a new function to encrypt the provided content. Use below code. Each line is explained by the accompanying comment.

Please note that:
– ENCRYPT_KEY should be kept safe. Keep it in settings_production.py  file and do not commit it to git.
– We are also converting the encoded string to urlsafe base64 format because we might required to pass the encoded data to URL.
– If there is any error, log it and return null.

Decryption:

To decrypt any encrypted text, we will just reverse the process.

Dependencies:

You need to install below python module.

– cryptography

Key:

You need to generate the ENCRYPT_KEY using below process.

– Open terminal in your virtual environment where cryptography python module is installed.
– Import Fernet.

– Generate key.

– Keep the key in settings file.

 

encryption decryption in django

Usage:

In the utility package we created in first step, we created the __init__.py  file. Add the below statement in this file.

Now use the encryption and decryption methods in your views.

Complete code:

Complete code for encryption_util.py  is below.

 

Host your Django App for Free.