5

I was looking for an answer but could not find it here. Please excuse me if this question was already asked.

I have a simple code encrypting and decrypting a string, strings look the same, but when comparing them using == they do not appear to be the same, so hashes are different as well..

Here is my code:

$oppa = "rompish";
$opp_enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, "key", $oppa, MCRYPT_MODE_ECB);
$opp_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, "key", $opp_enc, MCRYPT_MODE_ECB);

echo $oppa."<br />".$opp_dec."<br />";

if ($oppa == $opp_dec) echo "YAY"; else echo "NOPE";

On the page:

rompish rompish NOPE

Please tell me what I am doing wrong.

Thank you!

2
  • 2
    AES always encrypts things in blocks of 16 bytes. Apparently mcrypt_encrypt pads the string out with zero bytes until it is a multiple of 16. mcrypt_decrypt dutifully decrypts this but lacks the information to remove the padding. And you are fooling yourself because the displayed values look the same even though oppa_dec actually ends with 9 zero bytes. Use a sensible padding scheme instead. Commented Mar 10, 2013 at 2:23
  • That's an answer, not a comment, GregS (make it so or I'll post it including your name at the end :P) Commented Mar 10, 2013 at 23:06

1 Answer 1

2

AES always encrypts things in blocks of 16 bytes. Apparently mcrypt_encrypt pads the string out with zero bytes until it is a multiple of 16. mcrypt_decrypt dutifully decrypts this but lacks the information to remove the padding. And you are fooling yourself because the displayed values look the same even though oppa_dec actually ends with 9 zero bytes. Use a sensible padding scheme instead. – GregS

To remove these null characters, you can use the rtrim function. After running the decrypted output through that it should be equal.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.