Question

I'm trying to encrypt and decrypt a token with the AES 128 bit CBC encryption in PHP. If I try to encrypt and decrypt a token, the result is not the original token. Here is my code:

$decrKey = "123456789abcdefg";
$decrIV = "xyz123456789abcd";

function encryptAES($data,$key,$iv)
{
$decr= mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, base64_encode($data), MCRYPT_MODE_CBC, $iv);    
return $decr;   
}    

function decryptAES($data,$key,$iv)
{
$decr= mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($data), MCRYPT_MODE_CBC, $iv);    
return $decr;   
}      

$token = "abcdefghijk";
echo $token;

$tokenEncrypt = encryptAES($token,$decrKey,$decrIV);
echo "encrypt: ".$tokenEncrypt ;

$tokenDecrypt = decryptAES($tokenEncrypt,$decrKey,$decrIV);
echo "decrypt: ".$tokenDecrypt ;

What do i miss?

Was it helpful?

Solution

You should base 64 encode the result of the encryption method (called the ciphertext), and decode it again before decryption. You are currently base 64 encoding the plain text in the encryption function instead of the ciphertext. Encoding the plain text is not necessary. It would be however a good idea to use a well defined for the plain text.

$encr = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv));
return $encr
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top