Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt django model field using python 3.5

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?

like image 904
Михаил Павлов Avatar asked May 15 '16 02:05

Михаил Павлов


People also ask

How do I encrypt using Django?

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.

How does Django encrypt password?

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.


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.

like image 137
Михаил Павлов Avatar answered Sep 21 '22 01:09

Михаил Павлов


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"))
like image 44
Kenny Aires Avatar answered Sep 21 '22 01:09

Kenny Aires