Question

I am encrypting a string with PHP's mcrypt_encrypt function. This is my code:

$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;

Now I send the encrypted string to a client which later sends it back through an URL. Then I want to decrypt it using:

$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;

This is giving me garbage though and not the original string. The variable $key has the same value in both cases. What is wrong?

Was it helpful?

Solution

I had to trim the decrypted string to remove \0 characters at the end of it. Now it works.

OTHER TIPS

You don't reverese the rawurlencode step:

$cipherTextURLEncoded = rawurlencode($ciphertextBase64);

Try to add this:

$stringToDecrypt = rawurldecode($stringToDecrypt);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top