Django Fernet Encrypted Fields

0.4.0 · active · verified Thu Apr 16

django-fernet-encrypted-fields provides symmetrically encrypted model fields for Django, leveraging Fernet encryption from the `cryptography` library. It ensures that data is encrypted before being stored in the database and automatically decrypted when accessed in the application. This library is actively maintained as part of the Jazzband project, with recent updates and a focus on security for sensitive data at rest.

Common errors

Warnings

Install

Imports

Quickstart

To get started, install the library and configure your `settings.py` with a `SALT_KEY` (or rely on `SECRET_KEY` as a fallback, which is less secure for specific field encryption). Define your model with an `EncryptedTextField` or other provided encrypted field types. Data will be automatically encrypted and decrypted during save and retrieve operations. Remember to run `makemigrations` and `migrate`.

import os
from django.db import models
from encrypted_fields.fields import EncryptedTextField

# In your Django settings.py file, define SALT_KEY
# For production, load from environment variables and ensure it's a strong, random string.
# Example for settings.py (not for production directly):
# import os
# os.environ.setdefault('DJANGO_SALT_KEY', '0123456789abcdefghijklmnopqrstuvwxyz')
SALT_KEY = os.environ.get('DJANGO_SALT_KEY', 'a_default_32_char_salt_key_for_dev')
# For Django >= 4.1, you can also use SECRET_KEY_FALLBACKS for SECRET_KEY rotation.
# SECRET_KEY_FALLBACKS = [os.environ.get('OLD_DJANGO_SECRET_KEY', '')]

class MyEncryptedModel(models.Model):
    sensitive_data = EncryptedTextField()
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

# Example usage (assuming Django setup and migrations are run):
# from myapp.models import MyEncryptedModel
# instance = MyEncryptedModel.objects.create(name='Test User', sensitive_data='This is a secret message.')
# print(instance.sensitive_data) # Automatically decrypted: 'This is a secret message.'
# print(instance.pk)

view raw JSON →