Django Cryptography

1.1 · active · verified Thu Apr 16

django-cryptography simplifies encrypting data within Django models and applications. It provides encrypted model fields and utilities based on the `cryptography` library. The current version is 1.1, with releases occurring periodically to maintain compatibility with Django and the underlying `cryptography` library.

Common errors

Warnings

Install

Imports

Quickstart

To get started, install the package, add `django_cryptography` to your `INSTALLED_APPS`, and configure the `DJANGO_CRYPTOGRAPHY_KEY` in your Django settings. This key must be a base64-encoded Fernet key, typically loaded from an environment variable for security. You can then use `EncryptedCharField` or `EncryptedTextField` in your models to automatically encrypt and decrypt data.

import os

# settings.py
INSTALLED_APPS = [
    # ...
    'django_cryptography',
]

# Generate a key once with: `from cryptography.fernet import Fernet; Fernet.generate_key().decode()`
# Set this as an environment variable, e.g., export DJANGO_CRYPTOGRAPHY_KEY='YOUR_GENERATED_KEY'
DJANGO_CRYPTOGRAPHY_KEY = os.environ.get('DJANGO_CRYPTOGRAPHY_KEY', '')


# myapp/models.py
from django.db import models
from django_cryptography.fields import EncryptedCharField

class SecretNote(models.Model):
    title = models.CharField(max_length=100)
    content = EncryptedCharField(max_length=500)

    def __str__(self):
        return self.title

# Example usage in a Django shell or view:
# from myapp.models import SecretNote
# note = SecretNote.objects.create(title='Top Secret', content='This is highly confidential information.')
# print(note.content) # decrypted value
# stored_value = SecretNote.objects.values_list('content', flat=True).get(pk=note.pk) # will be encrypted bytes
# print(f"Stored (encrypted): {stored_value}")

view raw JSON →