Reputation: 53873
I've got a Laravel codebase which records are encrypted before they are inserted in the Mysql database. The encryption is done using the Crypto methods of the php-encryption library. If I want to find a record based on one of the encrypted values, looping over all the records works:
$records = TheModel::all();
foreach ($records as $record){
if ($record->thefield == $value) { // thefield is decrypted in the Eloquent model definition
print $record->id;
}
}
Unfortunately this isn't very scalable. The DB is still quite small, but growing quick so I need to change this code to actually do a query.
So I tried the following code:
$encryptedValue = \App\Crypt::encryptData($value);
$records = TheModel::where('thefield', $encryptedValue)->get();
foreach ($records as $record){
print $record->id;
}
But this doesn't return anything. So I then found this SO question it is suggested to add '0x'
, wrap it in BIN2HEX()
or HEX()
or add an x
before it (like x'abcd'
).
I tried adding '0x'
(which doesn't work), but I'm not sure how I could incorporate the other ideas in my code.
Does anybody know how I could try out these ideas with my code?
Upvotes: 2
Views: 3869
Reputation: 34103
You can't solve the problem with the tools you're using.
Laravel's encryption is randomized (this is a good thing for security, but it makes it impractical for search operations).
Check out CipherSweet, which implements searchable encryption in a way that can be used with any database driver. There isn't currently an Eloquent ORM integration written anywhere, but it should be straightforward to implement.
Upvotes: 4