Encryption-Decryption in Python Django

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.

Originally published  at pythoncircle.com

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.

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

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 below process.

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

- Import Fernet.

from cryptography.fernet import Fernet

- Generate key.

Fernet.generate_key()

- Keep the key in settings file.

ENCRYPT_KEY = b'iDJpljxUBBsacCZ50GpSBff6Xem0R-giqXXnBFGJ2Rs='

Usage:

In the utility package we created in 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:

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


Originally published  at pythoncircle.com

===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python and Django Full Stack Web Developer Bootcamp

☞ Python for Time Series Data Analysis

☞ Python Programming For Beginners From Scratch

☞ Python Network Programming | Network Apps & Hacking Tools

☞ Intro To SQLite Databases for Python Programming

☞ Ethical Hacking With Python, JavaScript and Kali Linux

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming

☞ Django 2.1 & Python | The Ultimate Web Development Bootcamp

☞ Python eCommerce | Build a Django eCommerce Web Application

☞ Python Django Dev To Deployment