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