mcrypt_decrypt在解密文本末尾添加null

I used Rijndael algorithm to encrypt and decrypt my database password. I kept encoded password in another file. Here I reduced the code to get relevant :

$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, PASSWORD_SALT, 'mypassword', MCRYPT_MODE_ECB);    
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, PASSWORD_SALT, $encrypted, MCRYPT_MODE_ECB);
// !! The value of $decrypted is "mypassword      " i.e. "mypasswordNULLNULLNULLNULLNULL"

'mypassword' is converted to 'mypassword' + 6xNULL. The decrypted code is containing null.

I wrote this code 1 year ago and everything was working fine. But now, when version of all technologies have changed, I am having problem.

It was always so.

According to documentation:

The data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

So either you trim your data with \0, or you have to store the original length anywhere and then cut the padded 0 off.

Using the Rijndael-128 algorithm mcrypt_encrypt() will always return multiples of 16 bytes. If your plain text ist not an exact multiple of 16 bytes the data will be padded with zero bytes so it will be a multiple of 16.

Those zero Bytes will appear in the decrypted text as well. You have to remove those by using:

$decrypted = rtrim($decrypted, "\0");

Note 1: Rijndael is a block encryption algorithm which operates on block of a fixed size. This is why padding may be necessary.

Note 2: Encryption is only suitable for encoded input that never ends with value 00h (because of default zero padding). Taken from example code at http://php.net/manual/en/function.mcrypt-encrypt.php