首頁 > php教程 > PHP源码 > 主體

AES CBC

PHP中文网
發布: 2016-05-23 16:36:44
原創
988 人瀏覽過

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);
	}
	
}
登入後複製
相關標籤:
aes
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!