Reputation: 1404
I have the following custom field class:
class Binary(models.Field):
__metaclass__ = models.SubfieldBase
def get_prep_value(self, value):
return encryptAES(key, iv_random, str(value))
def to_python(self, value):
return value
def db_type(self, connection):
return 'VARBINARY(900)'
This is the Model I have:
class Received(models.Model):
user = models.ForeignKey(User, unique=False, editable=False)
address = Binary(blank=True)
aes_key = Binary(blank=True)
iv = Binary(blank=True)
I am trying to encrypt/decrypt data using the custom field class. When a form is submitted by the user the get_prep_value method needs to encrypt the data. In the Django Admin interface I need the to_python method to decrypt the data fields in the change view. I was thinking of making the following additions to the to_python method:
def to_python(self, value):
return decryptAES(aes_key?, iv?, value)
The problem I'm having is that the to_python method loops through each field's value individually, whereas I need the values of the field itself, including the fields aes_key and iv to decrypt the data. I don't know how to get the aes_key and iv fields, hence the question marks.
Hope this clears things up.
Upvotes: 1
Views: 1814
Reputation: 239400
Based on the update to your question, what you're trying to do isn't really feasible. If you want the field to be able to encrypt/decrypt itself automatically, then all the information required to do so must be stored in the corresponding database field (see @DanielRoseman's answer). That essentially negates the usefulness of encryption if your database is ever compromised. Though, I guess an intruder would still have to figure out how to piece it together properly.
There is absolutely no way to store the requisite information across multiple database fields yet have one field that pulls all the info together to decrypt itself. Fields are isolated entities. They, pretty obviously, aren't allowed to have any information about other fields on the model because they can be used in places where those other fields might not exist on the model.
Your best bet is to store the encrypted value and the info needed to decrypt it in standard Django model fields, and have a one model method that decrypts the value and another than encrypts the value.
Upvotes: 1
Reputation: 599788
If key
, iv_random
and name
are all needed for this field to encrypt and decrypt itself on the way into and out of the database, then they shouldn't be separate fields at all - instead, you should define this Binary
class (terrible name, BTW) so that it produces/accepts a sequence of three values.
Upvotes: 0