Yii加密和解密密码


Yii encrypt and decrypt password

我正在使用Yii CSecurityManager进行密码加密:

$this->securityManager->encrypt('TEST', '1');

*TEST是要加密的字符串,而1是密钥。

但当我在解密之前进行测试时,我发现值一直在变化。

for ($index = 0; $index < 10; $index++) {
        $EncPassword = $this->securityManager->encrypt('TEST', '1');
        echo $EncPassword;
    }

我在应用程序的另一部分依赖这个值。。。我深入研究了加密密码,发现它实际上是随机的:

public function encrypt($data,$key=null)
{
    $module=$this->openCryptModule();
    $key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
    srand();
    $iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
    mcrypt_generic_init($module,$key,$iv);
    $encrypted=$iv.mcrypt_generic($module,$data);
    mcrypt_generic_deinit($module);
    mcrypt_module_close($module);
    return $encrypted;
}

所以我的问题是,如何根据密钥进行加密,每次都能得到相同的值?

谢谢,Danny

原则上,每次都可以创建相同的密文。只要使用静态IV,你就可以完成。然而,这意味着你会泄露有关密码的信息。对于不同的用户,相同的密码将具有相同的密文。

如果你真的想拥有相同的密文,请将用户名上哈希的前16个字节预先加在密码上,并用零IV进行加密。请注意,这仍然可能及时泄露一些有关密码的信息。

请注意,将密文值用于除明文存储之外的其他方式通常是一个非常糟糕的主意。