Decrypted JSON data not being decoded properly

Summary: The decrypted string was was null-padded. These null bytes are not handled by the jsondecode function. It is easily solved by running $string = rtrim($string, “\x00”); before decoding. Problem: In a PHP application, I’m JSON-encoding data, and then encrypting it to be stored in a cookie. The decrypting function, however, would fail when running jsondecode on the decrypted string. When I printed the string out prior to decoding, it looked fine. I could even copy the output and paste it into json_decode, and the string would be decoded. I was flummoxed.

Solution: I didn’t remember that it was encrypted with a block cipher (AES256), which, of course, adds padding to the string to make it a multiple of the block size. When I printed out bin2hex($string), the problem was verified. The solution is simple:

$string = rtrim($string, "\x00");

This strips off the null-padding. Now, calling json_decode($string) results in the expected behaviour.

Discussion: I obviously don’t work with encryption very often.

Leave your thoughts
  • You can use some HTML in your comment.
  • Your comment may not display immediately due to spam filtering. Please wait for moderation.