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?
Add a comment
|
2 Answers
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.
Comments
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"))
3 Comments
mondaini
I 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
prosper1
No module named core?
naohide_a
tried to make pypi.org/project/django-fernet-encrypted-fields