Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
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.

2 comments on 'Encryption-Decryption In Python Django'
Login to comment

A Rana July 5, 2018, 5:39 p.m.
nice article sir. easy and precise.
Seymour Oct. 24, 2020, 3:31 p.m.
Thanks for the great article! I hope you can help me with a follow-up question.What if I'm required to store the encrypted user data but I am not allowed to have their key? I would like to be able to use the user password to encrypt and decrypt the user data, so that even if I have server access, I cannot see the user data without knowing their password.

Related Articles:
Creating a bar chart in Django Application
Minimal example of how to create a bar chart or pie chart in Django application using Charts.js. Drawing Analytics charts in Django application. Using charts and graphs to make your Django application visually appealing. Creating Dashboards using Charts.js in Django to convey the information more visually....
Django application to automate the WhatsApp messaging
Django application with REST API endpoints to automate the WhatsApp messaging. Automating WhatsApp web using selenium to send messages. Using selenium to automate whatsapp messaging. Sending bulk messages via whatsapp using automation. Source code Django application Whatsapp Automation...
Python Snippets - A mini project  built using Django - Github Repository made public
mini project, python snippet sharing website, Django project free, Final year project free, Python Django project free,...
Django vs Node.js: Which One Is Better for Web Development?
Benefits of using Django and Node.js, Django vs Node.js: Which One Is Better for Web Development?, Basic features of Django and Node.js, Drawbacks of using Django and Node.js...
DigitalOcean Referral Badge

© 2024-2025 Python Circle   Contact   Sponsor   Archive   Sitemap