django-cryptography-django5

2.2 · active · verified Thu Apr 16

A fork of the original `django-cryptography` library, `django-cryptography-django5` provides primitives for easily encrypting data in Django models, wrapping the Python `cryptography` library. It offers field-level encryption for sensitive data, ensuring it's stored securely and decrypted automatically when accessed through Django. The library is actively maintained for Django 5 compatibility and is currently at version 2.2, with releases driven by Django version updates and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

Define a model with `encrypt` wrapped around the desired field. Ensure `SECRET_KEY` (and optionally `ENCRYPTION_KEY`) is configured in your Django settings.

import os
from django.db import models
from django_cryptography.fields import encrypt

# Ensure your Django settings.py has a strong SECRET_KEY and optionally ENCRYPTION_KEY
# For example, in settings.py:
# SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'your-very-long-and-random-secret-key-here')
# ENCRYPTION_KEY = os.environ.get('DJANGO_ENCRYPTION_KEY', SECRET_KEY) # Falls back to SECRET_KEY if not set

class SecureData(models.Model):
    name = models.CharField(max_length=100)
    # Encrypt the sensitive_info field
    sensitive_info = encrypt(models.TextField())

    def __str__(self):
        return self.name

# Example usage (after running migrations):
# from myapp.models import SecureData
# data_entry = SecureData.objects.create(name='User A', sensitive_info='This is very secret data.')
# print(data_entry.sensitive_info) # Automatically decrypted when accessed via Django ORM

view raw JSON →