2

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?

kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

4

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.

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
  • Thanks for the tip. I'm not actually using the Laravel encryption though, but the encryption of the php-encryption library (added to question). Any idea whether selecting using that encryption could work? – kramer65 Oct 30 '18 at 10:33
  • 1
    After some research and doing a simple test of encrypting the same thing multiple times, I indeed found out I cannot encrypt a value and search for that encrypted value. So I either need to loop over the values, or use Ciphersweet. I'll see which way I'll go. – kramer65 Oct 30 '18 at 13:45