PHP中的加密会留下不需要的字符

I have made an encryption function which encrypts a simple value and stores it in the database. Here is the code to encrypt and decrypt:

public function encrypt($string){
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $value = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key256, $string, MCRYPT_MODE_ECB, $iv);
    $value = base64_encode($value);
    return $value;
}

public function decrypt($string){
    $value = base64_decode($string);
    $value = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key256, $value, MCRYPT_MODE_ECB);
    return $value;
}

When I encrypt a simple value such as 'Michael' and decrypt again, I get the value:

Michael���������

Is there a reason I get all those question marks or a way to get rid of them?

In my experience, those extra character are NULL-bytes used for padding, that has been preserved after decryption.

You should try changing your decrypt() function to:

public function decrypt($string){
    $value = base64_decode($string);
    $value = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key256, $value, MCRYPT_MODE_ECB);
    return trim($value, "\0");
}

use bin2hex() instead of bas64_encode() and you can use the hex2bin() before decryption instead of base64_decode()

protected function hex2bin($hexdata) 
{
 $bindata = '';
 for ($i = 0; $i < strlen($hexdata); $i += 2) {
 $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
     }

  return $bindata;
}

Ofcourse you can use hex2bin() in PHP., this custom code is for compatibility with Java like platforms. I do it this way. May be you can give a try.

Thanks