php代码
class aes_cbc_nopadding
{
private $iv;
private $key;
private $blocksize;
public function __construct($key, $iv)
{
$this->blocksize = mcrypt_get_iv_size(mcrypt_rijndael_128, mcrypt_mode_cbc);
$this->key = substr(md5($key), 0, $this->blocksize);
$this->iv = substr(md5($iv), 0, $this->blocksize);
}
public function encrypt($text)
{
$pad = $this->blocksize - strlen($text)%$this->blocksize;
$text = str_pad($text, strlen($text) + $pad, "\0");
return base64_encode(mcrypt_encrypt(mcrypt_rijndael_128, $this->key, $text, mcrypt_mode_cbc, $this->iv));
}
public function decrypt($text)
{
$text = mcrypt_decrypt(mcrypt_rijndael_128, $this->key, base64_decode($text), mcrypt_mode_cbc, $this->iv);
$len = strlen($text);
for($len--; $len >= 0; $len--)
{
if($text[$len] !== "\0")
{
$len++;
break;
}
}
return substr($text, 0, $len);
}
}
class aes_cbc_pkcs7padding
{
private $iv;
private $key;
private $blocksize;
public function __construct($key, $iv)
{
$this->blocksize = mcrypt_get_iv_size(mcrypt_rijndael_128, mcrypt_mode_cbc);
$this->key = substr(md5($key), 0, $this->blocksize);
$this->iv = substr(md5($iv), 0, $this->blocksize);
}
public function encrypt($text)
{
$pad = $this->blocksize - strlen($text)%$this->blocksize;
$text = str_pad($text, strlen($text) + $pad, chr($pad));
return base64_encode(mcrypt_encrypt(mcrypt_rijndael_128, $this->key, $text, mcrypt_mode_cbc, $this->iv));
}
public function decrypt($text)
{
$text = mcrypt_decrypt(mcrypt_rijndael_128, $this->key, base64_decode($text), mcrypt_mode_cbc, $this->iv);
$pad = ord(substr($text, -1));
if($pad < 1 || $pad > 32) {
$pad = 0;
}
return substr($text, 0, strlen($text) - $pad);
}
}