JasonHarper Posted May 12, 2010 Share Posted May 12, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/201453-mcrypt-encodedecode-issue/ Share on other sites More sharing options...
PFMaBiSmAd Posted May 12, 2010 Share Posted May 12, 2010 Encryption/decryption operates on discrete blocks of data and it pads any supplied data to make it a full block in length. The characters are nulls and you can remove them by using the trim() function. Quote Link to comment https://forums.phpfreaks.com/topic/201453-mcrypt-encodedecode-issue/#findComment-1056905 Share on other sites More sharing options...
JasonHarper Posted May 12, 2010 Author Share Posted May 12, 2010 That did the trick! Thanks a million!! Quote Link to comment https://forums.phpfreaks.com/topic/201453-mcrypt-encodedecode-issue/#findComment-1056906 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.