I want one of my django model field to be encrypted. I found some extensions such as django-encrypted-fields
and django_extensions
, but both of them are using keyzcar
which is for python 2.7 and I do my project with python 3.5.
Can you guys suggest easy way to do django field encryption under 3.5 version of python?
Asked
Active
Viewed 6,435 times
9

Михаил Павлов
- 805
- 1
- 9
- 21
2 Answers
5
Solved the problem with django-fernet-fields
extension. Works well, it uses SECRET_KEY from django settings. Also you can specify custom encryption key.
Here is a web page.

Михаил Павлов
- 805
- 1
- 9
- 21
4
I tried @Михаил Павлов solution by installing django-fernet-fields
but it doesn't work on Django 3+ versions. My workaraound was to create a custom model that extends default CharField
and uses Fernet native lib for encryption under the hood:
import base64
from django.db.models import CharField
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from core import settings
class SecureString(CharField):
"""Custom Encrypted Field"""
salt = bytes(settings.SECURE_STRING_SALT, encoding="raw_unicode_escape")
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend())
key = base64.urlsafe_b64encode(kdf.derive(settings.SECRET_KEY.encode('utf-8')))
f = Fernet(key)
def from_db_value(self, value, expression, connection):
return str(self.f.decrypt(value), encoding="raw_unicode_escape")
def get_prep_value(self, value):
return self.f.encrypt(bytes(value, encoding="raw_unicode_escape"))

mondaini
- 117
- 8

Kenny Aires
- 1,338
- 12
- 16
-
2I had to parse to bytes before saving and parse back to string when reading. I'm using Django v3.2.3 / Cryptography v3.4.7 – mondaini May 13 '21 at 18:38
-
1No module named core? – prosper1 Aug 04 '21 at 12:13
-
1tried to make https://pypi.org/project/django-fernet-encrypted-fields/ – naohide_a Sep 30 '21 at 22:54