Laravel Crypt - Comparison of Values

Given that Laravel Crypt always adds salt, there are therefore no two instances of the same encryption.

This is usually normal, because I can compare the decrypted version of the two. However, what if I want to search for a value encrypted in a database?

Say I have a users table, and I would like to encrypt the email address. Now I want to find someone by email test@email.com .

How do I write a query for this? I can’t just Crypt::encrypt($email) and search, since this iteration of encrypt will be different from the one in the database.

Edit

Currently, ONLY what I can think of is to get everything and filter through them:

 $match = User::all()->filter(function($record) use($email) { $field = $record->email['email']; if(Crypt::decrypt($field) == $email) return $record; }); 

but it is terrible. I do not want to search everything.

+6
source share
1 answer

As described, you cannot. The answer you gave is how you will reach it if you do not need to optimize it.

If you need to optimize it without completely compromising the encrypted value and profile to find the amount of data returned and processed by your filter is the main reason for the delay, you can do the following.

Add a new field to the table in which a subset of the hash will be stored. Depending on the number of unique email addresses, you can configure how large this subset is. Note. The smaller, the better, since you use this information for encryption. For example, if you store a 1-byte hash of the email address, you reduce the encryption entropy by ~ 8 bits.

When prompted, first create a subset of the email hash and place the where clause to return only those lines.

All this suggests that a hash function is cheaper than a decryption step. This approach would require you to recalculate all hash subsets if you want to increase its size, so choosing a size that significantly improves performance does not cause excessive damage to encryption and most likely will not change as it grows.

Note. In this situation, you should not use a direct hash like MD5. Not because of this susceptibility to collisions, but because the key space will be so small. If performance is important and you store a large amount of data, you open your DOS attacks, as a result of which the attacker creates a large number of email addresses that all hashes for the same subset. To deal with this problem, use a private key HMAC .

Remember, if you have no true reasons for performance to add complexity - not

+2
source

Source: https://habr.com/ru/post/972641/


All Articles