php mcrypt cookie - mysql query
Edited to clarify:
I'm using the following code to encrypt and decrypt a string. It all seems to work fine until I try and compare the decrypted string with the encrypted string: <?php // encrypt $secret="a string I don't want people to see"; $key="A secret key for my cipher"; echo("<BR>secret = $secret"); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); $cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $secret, MCRYPT_MODE_ECB, $iv); echo("<BR>cipher = $cipher"); //decrypt $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); $checkSecret=mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cipher, MCRYPT_MODE_ECB, $iv); echo("<BR>checkSecret = $checkSecret"); if ($checkSecret==$secret) { echo ("<br>The decrypt has worked"); } else { echo ("<br>It failed"); } ?> Results: secret = a string I don't want people to see cipher = ¶%‡¿(Œ`O@ƒ¨%–„ü‹ï%ñG'MÇÈ¢¬vƒ¿{¢—›MºÔd??Lp)ô ÂõæSÙ„@ñF‡mœ checkSecret = a string I don't want people to see It failed Try it yourself and see what I mean. The strings are displayed on screen exactly as expected, but the comparison doesn't work. |
I've run into this myself. Sometimes when decrypting, there are some non-blank binary characters added to the end of the string. This *may* represent itself as a box or some other odd character when the de-crypted text is displayed. I overcome this by doing a trim() on the de-crypted text, which ususally does the trick (although occasionally I've had to do something like a preg_replace('/[^a-zA-Z0-9 <whatever other valid characters> ]/', '', $decrypted_string)).
Try changing Code:
$checkSecret=mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cipher, MCRYPT_MODE_ECB, $iv); Code:
$checkSecret=trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cipher, MCRYPT_MODE_ECB, $iv)); |
TruckStuff, thanks for the advice, trim() seems to work.
However, I'm a bit concerend about your comments "(although occasionally I've had to do something like a preg_replace('/[^a-zA-Z0-9 <whatever other valid characters> ]/', '', $decrypted_string))". Do you use the preg_replace in any specific circumstances, I'm thinking that although trim seems to work okay for the now, it might break at a later time? |
Its more a matter of data filtering/programmer preference. If trim() does the job, use it. If you want to filter the de-crypted data a little more, use preg_replace(). Neither is better than the other for this purpose, although I suppose one could make the argument that one requires a bit more horsepower than the other in a given scenario.
Btw, I think the extra data has something to do with the encryption algorythm being block-level vs. byte-level, but I'm not familiar enough with encryption to know for sure. |
All times are GMT -5. The time now is 07:07 PM. |