How to encrypt and decrypt password in Django

In this Python Django Tutorial, we will learn to encrypt and decrypt password in Django. And we’ll also see examples related to this. These are the following topics that we are going to discuss in this tutorial

  • How to encrypt and decrypt password in Django
  • Encrypt and Decrypt password in Django using built-in library
  • Encrypt and Decrypt password in Django without using built-in library

How to encrypt and decrypt password in Django

We will first understand what encryption and decryption are before learning how to encrypt and decrypt passwords in Django.

Encryption:

  • The method that converts original versions of data into an encoded form known as ciphertext is termed encryption.
  • Only the recipient can decipher the ciphertext back into its original form once this is done.
  • It’s the process of converting data into a format that can’t be easily deciphered by an unauthorized individual, and it’s crucial for keeping a system secure.
  • It is a technique for security and fraud prevention that automatically breaks apart and reorders information before it is transferred over the Internet.

Decryption:

  • Decryption is the process of restoring encrypted data to its original state.  
  • It’s a reversal of the encryption process.
  • It allows you to decipher encrypted data so that an authorized user with the correct secret key can access it.

Cryptography:

  • Encryption and decryption are both covered under the term cryptography.
  • It is the process of encrypting data and decrypting it so that only the intended recipient may read it.
  • Example: Consider a user who wishes to save their password in a database from the frontend of a web application. While the data is stored in the database, it is a danger of being accessed by an unintended user. As a result, it is encrypted and then decoded as needed.
how to encrypt and decrypt password using django
Cryptography

In Django, there are two methods for encrypting and decrypting passwords.

  • Using the Library
  • Without Using the Library

Using the Library

All you have to do is import Django’s built-in django_cryptography library to encrypt and decrypt your password.

Without Using the Library

All you have to create encryption and decryption functions to encrypt and decrypt your password.

Read: How to setup Django project

Encrypt and Decrypt password in Django using built-in library

In this section, we’ll learn to encrypt and decrypt password using a built-in cryptography library.

Let’s see an example:

Create Project: First, we need to build a Django Project. To do so, open a terminal and type the following command.

django-admin startproject PythonGuides
  • Here PythonGuides is the name of the Project.
encrypt and decypt password with built in django library
Create Project

Create App: Then, we need to build a Django App. To do so, open a terminal and type the following command.

python manage.py startapp CryptoApp
password encrypt and decrypt using built in django library
Create App

Create Templates: After this, in the project root directory, a Templates Folder is created. And we make HTML files in the folder.

Using django built in library encrypt and decrypt password
Templates

Add Templates: We also need to add the Templates directory in the settings.py file.

'DIRS' = ['Templates']
built in library to encrypt and decrypt password in django
Add Templates

Install App: The above-created app must be included in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'CryptoApp',
]
  • Here, we add the CryptoApp to the Installed_Apps list.
READ:  Python Tkinter Checkbutton - How to use

Create Models: Add the following code inside the models.py file.

from django.db import models

class Login(models.Model):
    email = models.EmailField()
    password = models.CharField(max_length=10)
    class Meta:
        db_table="Login"
  • We create the Login model with two fields.
  • The respective fields are email and password.

Register Model: Add the following code in the admin.py file.

from django.contrib import admin
from .models import Login

admin.site.register(Login)
  • We register the Login model on the admin site.

Encrypt Password: To encrypt a password in Django, we use the built-in function make_password. This method turns a plain text password into a hash that can be stored in a database.

Syntax:

# Import

from django.contrib.auth.hashers import make_password

# make_password function

make_password(password)
        # OR
make_password(password, None, hasher)
        # OR
make_password(password, 'qwertyuiop', hasher)

Hasher: A cryptographic hash function is a hashing algorithm. It’s a mathematical process that converts data of any size into a fixed-size hash. The algorithm names are as follows.

  • sha1
  • md5
  • unsalted_sha1
  • unsalted_md5
  • crypt
  • pbkdf2_sha256
  • pbkdf2_sha1
  • argon2

By default, PBKDF2 hasher is used to encrypt passwords.

Add Settings: Add the following Password Hashers in the settings.py file.

PASSWORD_HASHERS = [
  'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  'django.contrib.auth.hashers.Argon2PasswordHasher',
  'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  'django.contrib.auth.hashers.BCryptPasswordHasher',
  'django.contrib.auth.hashers.SHA1PasswordHasher',
  'django.contrib.auth.hashers.MD5PasswordHasher',
  'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
  'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
  'django.contrib.auth.hashers.CryptPasswordHasher',
]

Decrypt Password: Django doesn’t provide any built-in library or function to decrypt the encrypted password. As decrypting a password is never a good idea.

Instead of decrypting the hash password, we compare the hash password with the plaintext password and check whether they are equivalent to the hash password or not. The function used to check it is check_password.

Syntax:

from django.contrib.auth.hashers import check_password

check_password(password, hash password)

An example to encrypt and decrypt a password is as below:

Create Views: Add the following code in the views.py file.

from django.shortcuts import render, HttpResponse
from .models import Login
from django.contrib.auth.hashers import make_password, check_password

def login(request):
    if request.method == 'POST':
        email = request.POST['email']
        encryptedpassword=make_password(request.POST['password'])
        print(encryptedpassword)
        checkpassword=check_password(request.POST['password'], encryptedpassword)
        print(decryptedpassword)
        data=Login(email=email, password=encryptedpassword)

        data.save()
        return HttpResponse('Done')
    else:
        return render(request, 'index.html')
  • Here, we import the Django built-in make_password and check_password functions of django.contrib.auth.hashers.
  • Then, we encrypt the password by using the make_password function and also print it on the terminal.
  • After this, we check whether the encrypted password and original password are the same or not by using check_password.

Create HTML Template:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enter Employee</title>
</head>
<style>
    table {
        border: 8px outset;
        border-radius: 10px;
        border-spacing: 10px;
        padding: 20px;
        margin-left: auto;
        margin-right: auto;
    }

    th,
    td {
        padding: 5px;
    }
</style>

<body>
    <h2 style="text-align:center"> Login Employee </h2>
    <form method="POST">
        {% csrf_token %}
        <table style="width:50%" align="center">
            <tr>
                <td>Email</td>
                <td><input type="email" placeholder="Enter Employee Email" name="email" </td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" placeholder="Enter Employee Password" name="password" </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" class="btn btn-success"> </td>
            </tr>
        </table>
    </form>
</body>

</html>
  • Here, we create an HTML login form.
READ:  Django get all data from POST request

Commands: Run the following command on the terminal to make migrations.

# Make Migrations

python manage.py makemigrations

# Migrate

python manage.py migrate

Run Server: Type the following command in the terminal.

python manage.py runserver

Run the development server bypassing http://127.0.0.1:8000/login in the browser address bar.

  • Enter your Email and Password.
django encrypt and decrypt password using built in library
Login Form

When we click on Submit button, HttpResponse prints.

encrypt and decrypt password example using built in library
HTTP Response

See how password saves at the admin’s site.

encrypt and decrypt password in django using built in function
Admin Site

The hash key and result of check_function are printed on the terminal.

Using django encrypt and decrypt password with built in function
Terminal

Read: Python Django vs Flask – Key Differences

Encrypt and Decrypt passwords in Django without using built-in library

In this section, we’ll learn to encrypt and decrypt password without using a built-in cryptography library.

Let’s see an example:

Create Project: First, we need to build a Django Project. Open a terminal and type the following command.

djnago-admin startproject PythonGuides

Here, PythonGuides is the project name.

Create App: After this, we need to build a Django App. Open a terminal and type the following command.

python manage.py startapp home

Here, home is the app name.

CreateTemplates: After this, Templates Folder is created. And we add HTML files in the folder.

Add Templates: Then, add the above created Templates directory in the settings.py file.

'DIRS' = ['Templates']

Install APP: The above-created app ‘home’ must be included in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
]

Project URL: In the project’s urls.py file, add the following code to include the path of home.urls 

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('home.urls')),
]

App URL: To begin, we must create a file called urls.py in the app directory to define the paths to the various views.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.register, name='register'),
]

Install Dependencies: Install the Python cryptography module by using the following command.

pip install cryptography

Encrypt Key: The ENCRYPT KEY must be generated, for this open the terminal and type the following command.

from cryptography.fernet import Fernet
Fernet.generate_key()
  • First, we import Fernet.
  • Then, generate the key using the generate_key() function.
django encrypt and decrypt password without using built in library
Encryption Key

Add Key: Add the above-generated key in the settings.py file.

ENCRYPT_KEY = b'tmzHcYuvLUhxjcxZ4k_iqfCx-HUq6PCvdbXr4vOC5B4='

Create Models: Add the following code inside the models.py file.

from django.db import models

class EmpLogin(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()
    password = models.CharField(max_length=8)
    class Meta:
        db_table="EmpLogin"
  • We create the EmpLogin model with five fields.
  • The respective fields are nameemail, and password.

Register Model: Add the following code in the admin.py file.

from django.contrib import admin
from .models import EmpLogin

admin.site.register(EmpLogin)
  • To register the EmpLogin model on the admin site, we use the admin.site.register() function with model name.

Create Encryption and Decryption Function: Create an encrypt_util.py file in the home app.

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

def encrypt(pas):
    try:        
        pas = str(pas)
        cipher_pass = Fernet(settings.ENCRYPT_KEY)
        encrypt_pass = cipher_pass.encrypt(pas.encode('ascii'))
        encrypt_pass = base64.urlsafe_b64encode(encrypt_pass).decode("ascii") 
        return encrypt_pass
    except Exception as e:
        logging.getLogger("error_logger").error(traceback.format_exc())
        return None


def decrypt(pas):
    try:
        pas = base64.urlsafe_b64decode(pas)
        cipher_pass = Fernet(settings.ENCRYPT_KEY)
        decod_pass = cipher_pass.decrypt(pas).decode("ascii")     
        return decod_pass
    except Exception as e:
        logging.getLogger("error_logger").error(traceback.format_exc())
        return None
  • We create a encrypt and decrypt function to encrypt and decrypt the password.
  • We use the urlsafe, base64 to convert the encrypted data.
  • If an error occurs while encryption and decryption, log it and return null.
READ:  Python Turtle Speed With Examples

Create Views: Add the following code in the views.py file.

from django.shortcuts import render
from django.http import HttpResponse
from. models import EmpLogin
from home.encrypt_util import *

def register(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        password = request.POST['password']
        print('Original Password:', request.POST['password'])
        encryptpass= encrypt(request.POST['password'])
        print('Encrypt Password:',encryptpass)
        decryptpass= decrypt(encryptpass)
        print('Decrypt Password:',decryptpass)
        data=EmpLogin(name=name, email=email, password=password)
        data.save()
        return HttpResponse('Done')
    else:
        return render(request, 'index.html')
  • Here, we create a register view.
  • The view receives the name, email, and password entered by the user.
  • Then, we print the original password, encrypted password, and decrypted password.
  • It also shows HttpResponse Done on successful entry of data.

Create HTML File: Add the following code to the index.html file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enter Employee</title>
</head>
<style>
    table {
        border: 8px outset;
        border-radius: 10px;
        border-spacing: 10px;
        padding: 20px;
        margin-left: auto;
        margin-right: auto;
    }

    th,
    td {
        padding: 5px;
    }
</style>

<body>
    <h2 style="text-align:center"> Enter Details of Employee </h2>
    <form method="POST">
        {% csrf_token %}
        <table style="width:50%" align="center">
            <tr>
                <td>Employee Name</td>
                <td><input type="text" placeholder="Enter Employee Name" name="name" </td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="email" placeholder="Enter Employee Email" name="email" </td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" placeholder="Enter Employee Password" name="password" </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" class="btn btn-success"> </td>
            </tr>
        </table>
    </form>
</body>

</html>
  • Here, we create a form to take input from the user.

Basic Commands: Run the following basic command on the terminal.

# Make Migrations

python manage.py makemigrations

# Migrate

python manage.py migrate

# Run Server

python manage.py runserver

Output: Run the development server bypassing http://127.0.0.1:8000/ in the browser address bar.

encrypt and decrypt password without built in function in django
Enter Details
uisng django encrypt and decrypt password without built in library
Details

After, entering the details click on Submit Button.

password encrypt and decrypt without built in library using django
HTTP Response

Now, open the terminal and see the original password, encrypted and decrypted password.

example encrypt and decrypt password without built in library
Password Encryption and Decryption

You may also like to read the following Python Django Tutorials.

In this tutorial, we have discussed “How to Encrypt and Decrypt password in Django” and we have also discussed the following topics in this tutorial.

  • How to encrypt and decrypt password in Django
  • Encrypt and Decrypt password in Django using built-in library
  • Encrypt and Decrypt password in Django without using built-in library