Login

Django EncryptedField

Author:
zarglex
Posted:
October 26, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

Inspired by Base64Field: base64 encoding field for storing binary data in Django TextFields but in a generic way.

from django.db import models
import base64


class Base64Encryptor(object):
    def encrypt(self, value):
        return base64.encodestring(value)

    def decrypt(self, msg):
        return base64.decodestring(msg)


class MyModel(models.Model):
    ...
    b64_data = EncryptedField(encryptor=Base64Encryptor)
    ...


# Usage
my_obj = MyModel()
my_obj.b64_data = "hello"
print(my_obj.b64_data)  # will output 'hello'
print(my_obj.b64_data_enc)  # will output 'aGVsbG8=\n'
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from south.modelsinspector import add_introspection_rules
from django.db import models


class BaseEnc(object):
    def encrypt(self, value):
        return value

    def decrypt(self, value):
        return value


class EncryptedField(models.TextField):

    description = "A encrypted field"

    def __init__(self, encryptor=BaseEnc, *args, **kwargs):
        self.encryptor = encryptor()
        super(EncryptedField, self).__init__(*args, **kwargs)

    def contribute_to_class(self, cls, name):
        if self.db_column is None:
            self.db_column = name
        self.field_name = name + '_enc'
        super(EncryptedField, self).contribute_to_class(cls, self.field_name)
        setattr(cls, name, property(self.get_data, self.set_data))

    def get_data(self, obj):
        if getattr(obj, self.field_name):
            return self.encryptor.decrypt(getattr(obj, self.field_name))
        return None

    def set_data(self, obj, data):
        if data:
            setattr(obj, self.field_name, self.encryptor.encrypt(data))
        else:
            setattr(obj, self.field_name, None)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

cristianmoreno2017 (on February 16, 2018):

hello, do you have another example of how to encode and decode base64 with django?

#

Please login first before commenting.