Decrypt and Encrypt using CallBack Methods in cake

2019-02-26 21:55发布

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:

  1. 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;
    }
    
  2. 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:

View

And Database with the values encrypted:

DB

1条回答
时光不老,我们不散
2楼-- · 2019-02-26 22:21

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:

查看更多
登录 后发表回答