Weekly letter pythonprogramming.email
Hi,
To get the curated list of awesome python articles from all over the Internet, please subscribe with pythonprogramming.email. This is specifically suitable for beginners.
Advertise with us
Encryption-Decryption in Python Django

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

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

Once you are done with the initial setup of the 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 the below code. Each line is explained by the accompanying comment.

def encrypt(txt):
    try:
        # convert integer etc to string first
        txt = str(txt)
        # get the key from settings
        cipher_suite = Fernet(settings.ENCRYPT_KEY) # key should be byte
        # #input should be byte, so convert the text to byte
        encrypted_text = cipher_suite.encrypt(txt.encode('ascii'))
        # encode to urlsafe base64 format
        encrypted_text = base64.urlsafe_b64encode(encrypted_text).decode("ascii") 
        return encrypted_text
    except Exception as e:
        # log the error if any
        logging.getLogger("error_logger").error(traceback.format_exc())
        return None


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 the URL-safe base64 format because we might be required to pass the encoded data to the URL.

- If there is an error, log it and return null.


Decryption:

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

def decrypt(string):
    try:
        # base64 decode
        txt = base64.urlsafe_b64decode(txt)
        cipher_suite = Fernet(settings.ENCRYPT_KEY)
        decoded_text = cipher_suite.decrypt(txt).decode("ascii")     
        return decoded_text
    except Exception as e:
        # log the error
        logging.getLogger("error_logger").error(traceback.format_exc())
        return None

Dependencies:

You need to install below python module.

- cryptography


Key:


You need to generate the ENCRYPT_KEY using the below process.

- Open terminal in your virtual environment where the cryptography python module is installed.

- Import Fernet.

from cryptography.fernet import Fernet
- Generate key.

Fernet.generate_key()
- Keep the key in the settings file.

ENCRYPT_KEY = b'iDJpljxUBBsacCZ50GpSBff6Xem0R-giqXXnBFGJ2Rs='


encryption decryption in django 


Usage:

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

from .encryption_util import *
Now use the encryption and decryption methods in your views.

encryption_util.encrypt(username)

Complete code:

The complete code for encryption_util.py  is below.

from cryptography.fernet import Fernet
import base64
import logging
import traceback
from django.conf import settings

#this is your "password/ENCRYPT_KEY". keep it in settings.py file
#key = Fernet.generate_key() 

def encrypt(txt):
    try:
        # convert integer etc to string first
        txt = str(txt)
        # get the key from settings
        cipher_suite = Fernet(settings.ENCRYPT_KEY) # key should be byte
        # #input should be byte, so convert the text to byte
        encrypted_text = cipher_suite.encrypt(txt.encode('ascii'))
        # encode to urlsafe base64 format
        encrypted_text = base64.urlsafe_b64encode(encrypted_text).decode("ascii") 
        return encrypted_text
    except Exception as e:
        # log the error if any
        logging.getLogger("error_logger").error(traceback.format_exc())
        return None


def decrypt(txt):
    try:
        # base64 decode
        txt = base64.urlsafe_b64decode(txt)
        cipher_suite = Fernet(settings.ENCRYPT_KEY)
        decoded_text = cipher_suite.decrypt(txt).decode("ascii")     
        return decoded_text
    except Exception as e:
        # log the error
        logging.getLogger("error_logger").error(traceback.format_exc())
        return None
 

Host your Django App for Free.


Related Articles:
How to reset Django superuser password
This article explains 3 methods to reset the user password in Django, What command should be used to reset the superuser password from the terminal in Django application, Changing the user password in Django...
How to upload an Image file in Django
This article explains the simple steps of uploading and storing an image in Django application, After storing the image, how to use it in Django template or emails, Uploading a file in Django, Storing image in Django model, Uploading and storing the image in Django model, HTML for multipart file upload...
Getting query params from request in Django
In this article, we will see how to access the query parameters from a request in the Django view, Accessing GET attribute of request, get() vs getlist() method of request in Django, query parameters Django,...
Hello Word in Django 2: How to start with Django 2
In this article, we will see how to start working with Django 2.2, Step by step guide to install Django inside a virtual environment and starting the application on localhost, Django 2.2 installation, first Django project, hello world in Django 2.2, First Django application...

1 thought on 'Encryption-Decryption In Python Django'
A Rana :
nice article sir. easy and precise.

Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.

SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.

© 2017-2020 Python Circle   Contact   Sponsor   Archive   Sitemap