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?
To encrypt your data using django_cryptography, all you need to do is import encrypt from django_cryptography. fields and use it directly on each field where it is required. In app/models.py put the code given below. Then, add the code given below to app/admin.py to display your models on your admin page.
By default, Django uses the PBKDF2 algorithm with a SHA256 hash, a password stretching mechanism recommended by NIST. This should be sufficient for most users: it's quite secure, requiring massive amounts of computing time to break.
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.
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"))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With