# 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 | 
#+----+------------+-----------+----------------------------------+