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

我使用了documentation中提供的示例之一。

在我的core.php中,输入以下内容:

Configure::write('Security.cipherCriptKey','su0HKssPmdbwgK6LdQLqzp0YmyaTI7zO');


在我的模型中,我使用了两种方法:


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;
    }
}



beforeSave()似乎运行良好,因为我可以在数据库中看到加密的值。但是,在我看来,并且当我希望看到该字段的内容已解密时,它将显示为空字段。好像afterFind()方法无法将其解密(它始终返回false)。

以下是我的应用程序视图的屏幕截图:

php - 在cakephp中使用回调方法解密和加密-LMLPHP

和具有加密值的数据库:

php - 在cakephp中使用回调方法解密和加密-LMLPHP

最佳答案

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

以下任何一项都可以工作:


二进制
VARBINARY
BLOB(TINYBLOB,BLOB,MEDIUMBLOB和LONGBLOB)。


将其设置为VARBINARY(255)应该足够了。

有关更多参考,请参阅:


功能Security::encrypt()
Encrypt MySQL data using AES techniques

关于php - 在cakephp中使用回调方法解密和加密,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34818969/

10-11 02:48
查看更多