Home > php教程 > PHP源码 > body text

AES-256 加密 PHP实现

PHP中文网
Release: 2016-05-23 17:10:19
Original
1087 people have browsed it

php代码

class aes {

	static public $mode = MCRYPT_MODE_NOFB;
	
	static public function generateKey($length=32) {
		if (!in_array($length,array(16,24,32)))
			return False;

		$str = '';
		for ($i=0;$i<$length;$i++) {
			$str .= chr(rand(33,126));
		}

		return $str;
	}

	static public function encrypt($data, $key) {

		if (strlen($key) > 32 || !$key)
			return trigger_error(&#39;key too large or key is empty.&#39;, E_USER_WARNING) && False;

		$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, self::$mode);
		$iv = mcrypt_create_iv($ivSize, (substr(PHP_OS,0,1) == &#39;W&#39; ? MCRYPT_RAND : MCRYPT_DEV_URANDOM ));
		$encryptedData = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, self::$mode, $iv);
		$encryptedData = $iv . $encryptedData;

		return base64_encode($encryptedData);
	}

	static public function decrypt($data, $key) {

		if (strlen($key) > 32 || !$key)
			return trigger_error(&#39;key too large or key is empty.&#39;, E_USER_WARNING) && False;

		$data = base64_decode($data);
		if (!$data)
			return False;

		$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, self::$mode);
		$iv = substr($data, 0, $ivSize);

		$data = substr($data, $ivSize);

		$decryptData = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $data, self::$mode, $iv);

		return $decryptData;
	}
}
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template