Question

I have a beforeSave and afterFind function in my Model. The function encrypt and decrypt the string successfully:

    public function beforeSave($options = array()) {
   foreach($this->encryptedFields as $fieldName){
    if(!empty($this->data[$this->alias][$fieldName])){
        $this->data[$this->alias][$fieldName] = Security::rijndael($this->data[$this->alias][$fieldName], Configure::read('Security.key'), 'encrypt');
    }
}
return true;

}

But. If I do this

    $mobileno = 1234
    $mobile = Security::rijndael($mobileNo, Configure::read('Security.key'), 'encrypt');

and then I run query for example like:

   select * from table where mobileno = $mobileno;

I cant get the result. Because now the mobileno which is I encrypt above is different from the encrypt mobile number which is in db.

Was it helpful?

Solution

That is because Security::rijndael() uses a random initialization vector on every call.

In order to workaround this you would have to use a fixed IV, however this would degrade security, so that might not be a good idea!

For such situations I usually additionally encrypt the value using deterministic encryption, and store an HMAC hash (not a regular hash! Also should use a different secret/key than the one used for encryption!) of that value in an additional column, that way the select can be easily done with the hash of the deterministically encrypted value, and you're note completely loosing the improved security of non-deterministic encryption.

If you aren't able to use such a technique (ie utilizing a different value for identifying the record), then you might not get around selecting all datasets, decrypting them, and searching for the record in question manually.

If your DBMS supports AES encryption/decryption, you could try utilizing that functionality, it will most likely perform better than decrypting and selecting with PHP. But make sure that you assess possible security related pitfalls that might be introduced by exposing the encryption key to the DBMS!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top