Password Encryption and Decryption in Django

Django provides useful tools for password management. However, sometimes you need to go beyond Django’s default hashing mechanisms, especially when you want to encrypt and decrypt passwords or sensitive data for specific use cases.

In this tutorial, I’ll walk you through practical methods to encrypt and decrypt passwords in Django. I’ll share code examples and best practices based on real-world scenarios, so you can implement secure password handling confidently.

Let’s get in!

Methods to Encrypt and Decrypt Passwords in Django

Django’s built-in authentication system hashes passwords using strong algorithms like PBKDF2, which is the recommended way to store passwords securely. Hashing is a one-way operation — you cannot retrieve the original password from the hash, which protects users if your database is compromised.

However, there are cases where you might want reversible encryption, such as:

  • Encrypting API keys or tokens that need to be decrypted later.
  • Handling legacy systems where passwords or secrets must be decrypted.
  • Encrypting user data fields that require confidentiality beyond hashing.

Keep in mind, never store user passwords in reversible encryption unless necessary. For user authentication, always use Django’s hashing system.

Read: Check if Python Dictionary is Empty

Method 1: Use Django’s Built-In Password Hashing

Before we dive into encryption and decryption, let me quickly recap Django’s default method for handling user passwords securely.

Django uses the make_password and check_password functions to hash and verify passwords.

from django.contrib.auth.hashers import make_password, check_password

# Hash a password
raw_password = 'MySecureP@ssw0rdUSA'
hashed_password = make_password(raw_password)
print(f"Hashed Password: {hashed_password}")

# Verify password
is_valid = check_password('MySecureP@ssw0rdUSA', hashed_password)
print(f"Password valid? {is_valid}")

You can refer to the screenshot below to see the output.

django password decryption

This method is highly secure because it uses salted hashes and multiple iterations, making it computationally expensive to crack.

Read Python Filter Not in Django

Method 2: Encrypt and Decrypt Passwords Using Cryptography Library

For reversible encryption, I recommend the cryptography library. It’s a modern and secure Python package for encryption tasks.

Step 1: Install the library

pip install cryptography

Step 2: Writing Encryption and Decryption Functions

Here’s a simple example of how to encrypt and decrypt passwords or any sensitive data using symmetric encryption (Fernet):

from cryptography.fernet import Fernet

# Generate a key (do this once and save the key securely)
key = Fernet.generate_key()
cipher_suite = Fernet(key)

def encrypt_password(password: str) -> bytes:
    """Encrypt the password."""
    return cipher_suite.encrypt(password.encode())

def decrypt_password(encrypted_password: bytes) -> str:
    """Decrypt the password."""
    return cipher_suite.decrypt(encrypted_password).decode()

# Example usage
raw_password = "MySecureP@ssw0rdUSA"
encrypted = encrypt_password(raw_password)
print(f"Encrypted: {encrypted}")

decrypted = decrypt_password(encrypted)
print(f"Decrypted: {decrypted}")

You can refer to the screenshot below to see the output.

how to decrypt the password

Important Notes:

  • Store the key securely, preferably in environment variables or a secrets manager.
  • Never hardcode the key in your source code.
  • This method is suitable for encrypting data you need to decrypt later, not user login passwords.

Read Union Operation on Django Models

Method 3: Use Django’s Field Encryption Packages

If you want to encrypt model fields transparently, you can use third-party packages like django-fernet-fields or django-encrypted-model-fields.

Here’s an example with django-fernet-fields:

Step 1: Install the package

pip install django-fernet-fields

Step 2: Add to your INSTALLED_APPS in settings.py

INSTALLED_APPS = [
    # other apps
    'fernet_fields',
]

Step 3: Use encrypted fields in your models

from django.db import models
from fernet_fields import EncryptedCharField

class UserProfile(models.Model):
    username = models.CharField(max_length=150)
    encrypted_password = EncryptedCharField(max_length=255)

    def __str__(self):
        return self.username

You can refer to the screenshot below to see the output.

how to decrypt the encrypted password

This package handles encryption and decryption automatically when saving and retrieving data.

Check out Create a model in Django

Method 4: Encrypt Passwords with Custom Django User Model

Sometimes, you may want to store encrypted passwords or secrets in a custom user model for specialized applications.

Here’s a minimal example integrating Fernet encryption into a custom Django user model:

from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from cryptography.fernet import Fernet
import os

key = os.environ.get('FERNET_KEY')
cipher_suite = Fernet(key)

class CustomUser(AbstractBaseUser):
    username = models.CharField(max_length=150, unique=True)
    encrypted_password = models.BinaryField()

    def set_password(self, raw_password):
        self.encrypted_password = cipher_suite.encrypt(raw_password.encode())

    def check_password(self, raw_password):
        decrypted = cipher_suite.decrypt(self.encrypted_password).decode()
        return decrypted == raw_password

Remember: This approach is not recommended for typical user authentication. Use Django’s default password hashing unless you have a very specific need.

Read ModuleNotFoundError: No module named Django

Best Practices for Password Security in Django

  • Always prefer Django’s built-in password hashing for user authentication.
  • Use environment variables or secure vaults to store encryption keys.
  • Avoid reversible encryption for user passwords unless necessary.
  • Regularly rotate encryption keys if possible.
  • Use HTTPS to protect data in transit.
  • Keep dependencies like cryptography updated to the latest secure versions.

Handling passwords securely is a critical part of building trustworthy applications. In my experience, Django’s built-in system is robust and sufficient for most use cases. When reversible encryption is needed, the cryptography library provides a secure and straightforward solution.

By combining these approaches thoughtfully, you can protect sensitive data while building applications that meet your project’s requirements.

This tutorial should give you a solid foundation for encrypting and decrypting passwords and sensitive data in Django. Implement these methods carefully, and your users’ data will be much safer.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.