Search code examples
phpc++mcryptcrypto++

Why is PHP Mcrypt returning post message garbage?


Using the same (basic) code from here but switching to MCRYPT_RIJNDAEL_128, I'm now getting the correct data out of php mcrypt_decrypt, except in certain circumstances, it's padding out the end of my message a newline with seemingly random binary characters.

The following, for example, came back from a request to decrypt:

{"messageData":{"identity":"test","msg_id":0,"token":"fakeToken58586"},"messageName":"fetchSavedData_request"}\n\b\b\b\b\b\b\b\b

I would think this is a padding issue, but even if I pad out my string to the correct length, I occasionally get garbage, and strings that would normally need to be padded, do occasionally come back correct.

What's going on here?


Solution

  • As @Jack pointed out in the comments, this is apparently a common problem. The code here works to remove control characters at the end of encrypted data.

    Reproduced here for posterity:

    $data = preg_replace( "/\p{Cc}*$/u", "", $data);