Transparent encryption for model fields

 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
# demo model
from django.db import models
from Crypto.Cipher import Blowfish
from django.conf import settings
import binascii

# Create your models here.
class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    social_security_number = models.CharField(max_length=32)

    def _get_ssn(self):
        enc_obj = Blowfish.new( settings.SECRET_KEY )
        return u"%s" % enc_obj.decrypt( binascii.a2b_hex(self.social_security_number) ).rstrip()

    def _set_ssn(self, ssn_value):
        enc_obj = Blowfish.new( settings.SECRET_KEY )
        repeat = 8 - (len( ssn_value ) % 8)
        ssn_value = ssn_value + " " * repeat
        self.social_security_number = binascii.b2a_hex(enc_obj.encrypt( ssn_value ))

    ssn = property(_get_ssn, _set_ssn)



# testing
>>> Person.objects.all().delete()
>>> p = Person.objects.create(first_name='Billy', last_name='Barou', ssn='123-12-1234')
>>> p.ssn
u'123-12-1234'

#sandbox$ mysql -e "SELECT * FROM django_sandbox.field_encryption_person"
#+----+------------+-----------+----------------------------------+
#| id | first_name | last_name | social_security_number           |
#+----+------------+-----------+----------------------------------+
#|  3 | Billy      | Barou     | 94ec660c832c95b31500618a5ffee60f | 
#+----+------------+-----------+----------------------------------+

More like this

  1. Transparently encrypt ORM fields using OpenSSL (via M2Crypto) by ncoghlan 1 year, 11 months ago
  2. Encryption Fields by zbyte64 4 years, 8 months ago
  3. Saving passwords for other services (semi-)securely in a database by equanimity 4 years, 4 months ago
  4. S/MIME Encrypted E-mail by bthomas 3 years, 10 months ago
  5. Drupal password hasher for migration by dgrtwo 1 year, 2 months ago

Comments

(Forgotten your password?)