使用cakephp中的CallBack方法解密和加密 [英] Decrypt and Encrypt using CallBack Methods in cakephp

查看:389
本文介绍了使用cakephp中的CallBack方法解密和加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Callbacks方法加密一个值,然后将其存储在我的数据库中,并在将其显示回应用程序之前对其进行解密。



我使用了

解决方案

函数 Security :: encrypt($ text)使用AES-256算法加密 $ text 。它返回二进制数据,因此,它应该存储为二进制数据类型,而不是文本类型。



以下任何一种都应该可以使用:




  • BINARY BLOB (TINYBLOB,BLOB,MEDIUMBLOB和LONGBLOB)




将其设置为 VARBINARY(255) p>

有关进一步参考,请参阅:




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:

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:

这篇关于使用cakephp中的CallBack方法解密和加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆