首页 >php教程 >PHP源码 >PHP完整的AES加解密算法使用及例子(256位)

PHP完整的AES加解密算法使用及例子(256位)

PHP中文网
PHP中文网原创
2016-05-25 17:09:231071浏览

php代码

<?php
class aes {

    // CRYPTO_CIPHER_BLOCK_SIZE 32
	
	private $_secret_key = &#39;default_secret_key&#39;;
	
	public function setKey($key) {
		$this->_secret_key = $key;
	}
	
	public function encode($data) {
		$td = mcrypt_module_open(MCRYPT_RIJNDAEL_256,&#39;&#39;,MCRYPT_MODE_CBC,&#39;&#39;);
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td),MCRYPT_RAND);
		mcrypt_generic_init($td,$this->_secret_key,$iv);
		$encrypted = mcrypt_generic($td,$data);
		mcrypt_generic_deinit($td);
		
		return $iv . $encrypted;
	}
	
	public function decode($data) {
		$td = mcrypt_module_open(MCRYPT_RIJNDAEL_256,&#39;&#39;,MCRYPT_MODE_CBC,&#39;&#39;);
		$iv = mb_substr($data,0,32,&#39;latin1&#39;);
		mcrypt_generic_init($td,$this->_secret_key,$iv);
		$data = mb_substr($data,32,mb_strlen($data,&#39;latin1&#39;),&#39;latin1&#39;);
		$data = mdecrypt_generic($td,$data);
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		
		return trim($data);
	}
}

$aes = new aes();
$aes->setKey(&#39;key&#39;);

// 加密
$string = $aes->encode(&#39;string&#39;);
// 解密
$aes->decode($string);
?>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn