本文章向大家介绍怎么在PHP中实现一个AES加密、解密封装类的基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
php是一个嵌套的缩写名称,是英文超级文本预处理语言,它的语法混合了C、Java、Perl以及php自创新的语法,主要用来做网站开发,许多小型网站都用php开发,因为php是开源的,从而使得php经久不衰。
具体如下:
<?php
/**
* Class AES
* 用于AES加解密数据
*/
class AES
{
protected $cipher = MCRYPT_RIJNDAEL_256; //AES加密算法
protected $mode = MCRYPT_MODE_CBC; //采用cbc加密模式
protected $key; //密钥
protected $iv; //cbc模式加密向量,如为空将采用密钥代替
/**
* AES constructor.
*
* @param $key 密钥
* @param null $iv 向量 可选 如为空将采用密钥代替
*
* @throws Exception
*/
public function __construct($key, $iv = NULL)
{
if (!extension_loaded("mcrypt")) {
// throw new \Exception("mcrypt extension do not exist. it was DEPRECATED in PHP 7.1.0, and REMOVED in PHP 7.2.0. use OpenSSL instead");
}
$this->key = $key;
$this->iv = $iv;
}
/**
* 加密数据
* @param $data
*
* @return string
*/
public function encrypt($data)
{
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');
$key = hash("sha256", $this->key, true);
$iv = isset($this->iv) ? hash("sha256", $this->iv, true) : $key;
$data = $this->padding($data);
mcrypt_generic_init($td, $key, $iv);
$encryptedData = base64_encode(mcrypt_generic($td, $data));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $encryptedData;
}
/**
* 解密数据
* @param $data
*
* @return bool|string
*/
public function decrypt($data)
{
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');
$key = hash("sha256", $this->key, true);
$iv = isset($this->iv) ? hash("sha256", $this->iv, true) : $key;
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, base64_decode($data));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $this->unPadding($decrypted_data);
}
/**
* 填充数据到分组大小的整数倍
* @param null $data
*
* @return string
*/
protected function padding($data = null)
{
$blockSize = 32; //MCRYPT_RIJNDAEL_256算法的分组大小是32字节
$pad = $blockSize - (strlen($data) % $blockSize);
return $data . str_repeat(chr($pad), $pad);
}
/**
* 去掉填充的数据
* @param null $data
*
* @return bool|string
*/
protected function unPadding($data = null)
{
$pad = ord($data[strlen($data) - 1]);
if ($pad > strlen($data)) {
return false;
}
if (strspn($data, chr($pad), strlen($data) - $pad) != $pad) {
return false;
}
return substr($data, 0, -1 * $pad);
}
/**
* @return mixed
*/
public function getSecretKey()
{
return $this->key;
}
/**
* @param mixed $key
*/
public function setSecretKey($key)
{
$this->key = $key;
}
/**
* @return null
*/
public function getIv()
{
return $this->iv;
}
/**
* @param null $iv
*/
public function setIv($iv)
{
$this->iv = $iv;
}
}
//使用方法:
$keyStr = 'sq8f77fwhksk';
$aes = new AES($keyStr);
$str = 'www.jb51.net';
$chgstr = $aes->encrypt($str);
echo $chgstr;
echo "<br/>";
$rstr = $aes->decrypt($chgstr);
echo $rstr;
以上就是小编为大家带来的怎么在PHP中实现一个AES加密、解密封装类的全部内容了,希望大家多多支持亿速云!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。