I want to use the Callbacks methods to encrypt a value before it gets stored in my database and decrypt it before showing it back in the application.
I used one of the examples provided in the documentation.
In my core.php
I put the following :
Configure::write('Security.cipherCriptKey','su0HKssPmdbwgK6LdQLqzp0YmyaTI7zO');
In my Model, I used two methods:
beforeSave()
public function beforeSave($options = array()) { $value=$this->data['Internship']['encryptedindb']; $encrypted = Security::encrypt($value, Configure::read('Security.cipherCriptKey')); $this->data['Internship']['encryptedindb'] = $encrypted; return true; }
afterFind()
public function afterFind($results, $primary = false) { foreach ($results as $key => $val) { if(isset($val['Internship']['encryptedindb'])){ $results['Internship']['encryptedindb'] = Security::decrypt($val['Internship']['encryptedindb'], Configure::read('Security.cipherCriptKey')); } return $results; } }
The beforeSave()
seems to be working fine, since I can see in my Database the value encrypted. However, in my view, and when I would like to see the content of the field decrypted, it displays it as an empty field. As if the afterFind()
method is unable to decrypt it back (it returns always false).
Below is a screenshot of my application's view:
And Database with the values encrypted:
The function Security::encrypt($text)
uses the AES-256 algorithm to encrypt $text
. It returns binary data, and as such, it should be stored in a binary data type, instead of a text type.
Any of the following should work:
- BINARY
- VARBINARY
- BLOB (TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB).
Setting it to VARBINARY(255)
should probably be enough.
For further reference, see:
来源:https://stackoverflow.com/questions/34818969/decrypt-and-encrypt-using-callback-methods-in-cakephp