I'm trying to create a custom CharField that would encrypt a field's
contents before saving to the db, and conversely decrypt the field's
values from the db as it loads (using a public key).

I want to make sure that the contents of this field is encrypted in
the database, but decrypted whenever I work with the field in Django -
nice and transparent to all the developers.  I could add a new
property to my model and have it decrypt the field, but this field's
been around for ages and I don't want to mod all the dependencies.

Sub-classing CharField seemed the obvious choice and encrypting on
save is easy - I simply override the Field's get_db_prep_save()
method.

But I can't find a post-load hook for decrypting the value as soon as
the field's value gets loaded from the db.

This is the part that works well - encrypting on save (silly
encryption algorithm permitting:)

class EncryptedCharField(models.CharField):

    def _encrypt(self, value):
        if value is not None:
            value = ''.join([chr(ord(char)+1) for char in str(value)])
        return value

    def _decrypt(self, value):
        if value is not None:
            value = ''.join([chr(ord(char)-1) for char in str(value)])
        return value

    def get_internal_type(self):
        return "CharField"

    def get_db_prep_save(self, value):
        value = self._encrypt(value)
        return super(EncryptedCharField, self).get_db_prep_save(value)


Does anyone have any idea how I could hook into and change the field's
value as soon as the value gets loaded from the db?

Where can I call my _decrypt() method from?  I would like to call it
once - the moment the results from the Model's QuerySet are parsed and
the Model's field values populated.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to