Django: searching on an EncryptedCharField (django-extensions), is this possible?
is this possible?
For a model with EncryptedCharField named "first_name" i noti开发者_JAVA技巧ce that the field does not decrypt when I search on it. In all other uses it is fine. This does not work:
if form.is_valid():
cd = form.cleaned_data
search_results = MyTable.objects.filter(first_name__icontains=cd['search_term'])
is this by design or am i doing something wrong? thanks for you help...
Encrypting the search term first, even if the exact decrypted value, would not work as the cipher is not going to be the same as the one stored in the db. So this would not work:
crypter = Crypter.Read(settings.ENCRYPTED_FIELD_KEYS_DIR)
if form.is_valid():
cd = form.cleaned_data
cipher = crypter.Encrypt(cd['search_term'])
search_results = MyTable.objects.filter(first_name__icontains=cipher)
When something is encrypted (or at least, when it is done properly), it is impossible to gain the value that has been encrypted, without knowing the value. This means that while you can check the value of say a password very quickly, as the user has given you the value of the password, it is very hard to find out the value of the password from the encrypted string. This is part of the P=NP topic.
When you search say via MyTable.objects.filter(first_name=cipher)
, you are just comparing encrypted strings, which is fine. However, when you try MyTable.objects.filter(first_name_icontains=cipher)
, you are asking django to unencrypt all of the values, compare them, then return what matches. However, django cannot do that, as no one knows what the value of the decrypted first_name field is. This is by design, as it means that even if the database is compromised, the data is safe (It is also why you should beware any website or organisation that will show you your password, as it means they have not encrypted the value in their database). Overall, not being able to see a users password is a good thing, and even if you do not agree, it is a small price to pay for good security.
You could simply store the HMAC hash of the value in another field, then search for that.
精彩评论