I have a code that goes something like:
$cipher_alg = MCRYPT_RIJNDAEL_128;
$decrypted_string = mcrypt_decrypt($cipher_alg, $key,
$encrypted_string , MCRYPT_MODE_CBC, trim(hex2bin(trim($hexiv))));
I worry that in the process of decoding the mcrypt_decrypt will introduce a gratuitous whitespace or null characters at the back or front of the $decrypted_string.
So should I trim it?
Note: I could have run the code and find this out. But since I can never run enough samples to prove ( or disprove) my point, I want some concrete and theoretical answers, probably based on the inner working of the mcrypt_decrypt algorithm. Another reason I ask is that I believe this is going to help others.
Note 2: Notwithstanding with the answer below ( now deleted and only 10K users can see it), it seems that the examples here do use trimming to get the correct decrypted string.
Actually both
mcrypt_encrypt()andmcrypt_decrypt()as well as the other en-/decryption functons (likemcrypt_generic()ormdecrypt_generic()) do pad the$dataparameter to a length ofn * <<blocksize>>. The padding character is theNULcharacter (\x0or\0) whereas the<<blocksize>>depends on the cipher and the block cipher modes used. You should have a look at Block cipher modes of operation and Padding (cryptography).The following is the output of
mcrypt_get_block_size()for each of the available ciphers and modes on my machine. Obviously the function does not take into account that modes such as CFB, OFB and CTR do not require any special measures to handle messages whose lengths are not multiples of the block size, since they all work by XORing the plaintext with the output of the block cipher (quote from Wikipedia). CBC which is used in your example always requires that the final block is padded before encryption.Therefore you have to
rtrim()the output of the decryption functions to get the original string if your cipher operates on fixed length blocks: