Rumah  >  Artikel  >  php教程  >  AES CBC

AES CBC

PHP中文网
PHP中文网asal
2016-05-23 16:36:44990semak imbas

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);
	}
	
}
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn