0

我正在使用两个简单的函数来加密和解密密码。但是解密功能无法正常工作。这是我的输出:

加密:�\� ���#�%\��>�3,�o�Sd��c�
解密:test123

这是我的代码:

$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);   

function encrypt($data)
{
    $key = 'test';
    $encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_ENCRYPT, $iv);
    return $encrypted_data;
}

function decrypt($encryptedData)
{       
    $key = 'test';
    $decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_256, $key, $encryptedData, MCRYPT_DECRYPT, $iv);
    return $decrypt;
}


$password = encrypt($member[0]['PASSWORD']);
print('Encrypted: '.$password.'<br />');
$password = decrypt($password);
print('Decrypted: '.$password);
4

3 回答 3

4

嗯,是的,当您使用随机 IV 进行加密和使用新 IV 进行解密时,就会发生这种情况。您应该只在加密期间生成 IV 并将其作为密文的前缀。

于 2013-02-05T19:14:02.207 回答
2

问题在于$iv一代。您在加密期间生成它,然后在解密期间再次生成它。

$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);

function encrypt($data, $iv)
{
    $key = 'test';
    $encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_ENCRYPT, $iv);
    return $encrypted_data;
}

function decrypt($encryptedData, $iv)
{
    $key = 'test';
    $decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_256, $key, $encryptedData, MCRYPT_DECRYPT, $iv);
    return $decrypt;
}

$password = encrypt("testing", $iv);
echo $password.'<br>';
echo decrypt($password, $iv);
于 2013-02-05T19:21:10.973 回答
-1

好的,我使用以下代码进行了加密:

$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);   

function encrypt($data)
{
    $key = 'test';
    $encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_ENCRYPT, $iv);
    return base64_encode($encrypted_data);
}

function decrypt($encryptedData)
{       
    $key = 'test';
    $encryptedData = base64_decode($encryptedData);
    $decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_256, $key, $encryptedData, MCRYPT_DECRYPT, $iv);
    return trim($decrypt);
}
于 2013-02-05T21:08:24.920 回答