1

我正在使用 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 在这两种情况下具有相同的值。怎么了?

4

2 回答 2

1

我必须修剪解密的字符串以删除其末尾的 \0 字符。现在它起作用了。

于 2013-07-22T08:41:12.510 回答
0

您不反转 rawurlencode 步骤:

$cipherTextURLEncoded = rawurlencode($ciphertextBase64);

尝试添加这个:

$stringToDecrypt = rawurldecode($stringToDecrypt);
于 2013-07-18T08:18:49.853 回答