9

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?

2 Answers2

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.

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