0

我试图在我的模型的 beforeSave 方法中加密一些数据。但它没有被保存。

       $currentBalance = $this->find("all", array(
            "fields" => array(
                "SUM(base_amount) as 'CurrentBalance'"
            ),
            "conditions" => array(
                "Payment.user_id" => $this->data["Payment"]["user_id"]
            )
        ));

        $this->log($this->data["Payment"]);
        $this->log(Configure::read("Security.salt"));        
        $this->log(Security::cipher(implode("|", $this->data["Payment"]), Configure::read("Security.cipherSeed")));

        $this->set("balance", $currentBalance[0][0]["CurrentBalance"] + $this->data["Payment"]["base_amount"]);
        $this->set("balance_checksum", Security::cipher(implode("|", $this->data["Payment"]), Configure::read("Security.salt")));

如果我查看日志文件,我会得到某种加密数据,但都是胡言乱语。

虽然在数据库中,但我一无所获。

如果我用一个简单的字符串替换密码函数说“123”......那将被正确保存。

我已确保数据库连接是 utf8 编码的,并且数据库中的字段具有 utf8 排序规则。

对此的任何指示都会很棒

谢谢

4

1 回答 1

4

我已经解决了一个类似的问题。问题是加密数据创建了一些无效的 utf8 字符。比如汉字之类的。我所做的是将加密字符串转换为十六进制然后保存。当取回数据时,您可以从十六进制解码为字符,然后对其进行解密。

(在 AppModel.php 中)

<?php
/**
 * Encrypts a sensible string for the bd
 * @param string $toEncrypt
 * @return string  encrypted hexadecimal 
 */
function encryptCipher($toEncrypt) {
    $CipherKey = Configure::read('Security.cipherSeed');
    return bin2hex(Security::cipher($toEncrypt, $CipherKey));
}
?>

(在 AppController.php 中)解密方法,其中 $this->CipherKey 以与模型完全相同的方式加载到 __construct

<?php function __construct(){
$this->CipherKey = Configure::read('Security.cipherSeed');
}

/**
 * The main decrypting function
 * 
 * @param string $strToDecrypt the string to be decrypted
 * @return string the decrypted string 
 */
public function decryptCipher($strToDecrypt) {
    return Security::cipher(pack("H*", $strToDecrypt), $this->CipherKey);
}
?>
于 2012-08-07T18:10:14.097 回答