使用mcrypt_decrypt进行错误的解密

时间:2013-07-18 07:56:10

标签: php cryptography mcrypt

我正在使用PHP的mcrypt_encrypt函数加密字符串。这是我的代码:

$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$this->iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);

$encryptionKey = pack('H*', $key);

$stringToEncryptUTF8 = utf8_encode($stringToEncrypt);

$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $encryptionKey, $stringToEncryptUTF8, MCRYPT_MODE_CBC, $this->iv);
$ciphertext = $this->iv . $ciphertext;
$ciphertextBase64 = base64_encode($ciphertext);
$cipherTextURLEncoded = rawurlencode($ciphertextBase64);

return $cipherTextURLEncoded;

现在我将加密的字符串发送到客户端,然后通过URL将其发回。然后我想使用以下方法解密它:

$stringToDecrypt = base64_decode($stringToDecrypt);

$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = substr($stringToDecrypt, 0, $ivSize);

$stringToDecrypt = substr($stringToDecrypt, $ivSize);

$encryptionKey = pack('H*', $key);
$decodedText = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $encryptionKey, $stringToDecrypt, MCRYPT_MODE_CBC, $iv);

return $decodedText;

这给了我垃圾而不是原始字符串。在两种情况下,变量$ key都具有相同的值。有什么问题?

2 个答案:

答案 0 :(得分:1)

我必须修剪解密的字符串,以删除它末尾的\ 0字符。现在它有效。

答案 1 :(得分:0)

您不会撤消rawurlencode步骤:

$cipherTextURLEncoded = rawurlencode($ciphertextBase64);

尝试添加:

$stringToDecrypt = rawurldecode($stringToDecrypt);