Jump to content

Mcrypt Encode/Decode Issue


JasonHarper

Recommended Posts

Hello!

 

I'm using mcrypt to encrypt/decrypt a string.  In order to store the encrypted string in MySQL, I was using base64 to encode before storage, and base64 to decode after retrieving from storage and before decryption.  I have something slightly wrong because my output of the decrypted string does contain the original string, but it also contains several ASCII characters behind it.  Here is a code snippet (I eliminated all of the DB insert/select code to try and isolate the issue):

	//VARIABLE
	$string = 'password';

	//ALGORITHM
	$alg = MCRYPT_RIJNDAEL_256;

	//INITIALIZATION VECTOR
	$iv = mcrypt_create_iv(mcrypt_get_iv_size($alg, MCRYPT_MODE_ECB), MCRYPT_RAND);

	$key = 'Gjsj176502j1g71u72h171';

	$encryptedString = mcrypt_encrypt($alg, $key, $string, MCRYPT_MODE_CBC, $iv);
	$encodedString = base64_encode($encryptedString);
	$decodedString = base64_decode($encodedString);
	$decryptedString = mcrypt_decrypt($alg, $key, $decodedString, MCRYPT_MODE_CBC, $iv);

	echo 'String: '.$string.'<p>';
	echo 'Key: '.$key.'<p>';
	echo 'Encrypted String: '.$encryptedString.'<p>';
	echo 'Encoded String: '.$encodedString.'<p>';
	echo 'Decoded String: '.$decodedString.'<p>';
	echo 'Decrypted String: '.$decryptedString.'<p>';

 

Here is what I'm getting as a result of this code:

 

String: password

 

Key: Gjsj176502j1g71u72h171

 

Encrypted String: B��`P�fÚa�;U-ҳ�+KM�&��Κ�+

 

Encoded String: QpaxYFDis2bDmmHYOw9VLdKzlytLTeQmiAi5GM6a9Ss=

 

Decoded String: B��`P�fÚa�;U-ҳ�+KM�&��Κ�+

 

Decrypted String: password������������������������

 

It looks like everything is fine until we get to the decrypted string - it contains the correct value but also all the ASCII.  Any ideas what I'm doing wrong?  Thank you!!

 

Jason

 

 

Link to comment
https://forums.phpfreaks.com/topic/201453-mcrypt-encodedecode-issue/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.