PHP实现的AES加密、解密封装类与用法示例
本文实例讲述了PHP实现的AES加密、解密封装类与用法。分享给大家供大家参考,具体如下:
key=$key;
$this->iv=$iv;
}
/**
*加密数据
*@param$data
*
*@returnstring
*/
publicfunctionencrypt($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
*
*@returnbool|string
*/
publicfunctiondecrypt($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);
}
/**
*填充数据到分组大小的整数倍
*@paramnull$data
*
*@returnstring
*/
protectedfunctionpadding($data=null)
{
$blockSize=32;//MCRYPT_RIJNDAEL_256算法的分组大小是32字节
$pad=$blockSize-(strlen($data)%$blockSize);
return$data.str_repeat(chr($pad),$pad);
}
/**
*去掉填充的数据
*@paramnull$data
*
*@returnbool|string
*/
protectedfunctionunPadding($data=null)
{
$pad=ord($data[strlen($data)-1]);
if($pad>strlen($data)){
returnfalse;
}
if(strspn($data,chr($pad),strlen($data)-$pad)!=$pad){
returnfalse;
}
returnsubstr($data,0,-1*$pad);
}
/**
*@returnmixed
*/
publicfunctiongetSecretKey()
{
return$this->key;
}
/**
*@parammixed$key
*/
publicfunctionsetSecretKey($key)
{
$this->key=$key;
}
/**
*@returnnull
*/
publicfunctiongetIv()
{
return$this->iv;
}
/**
*@paramnull$iv
*/
publicfunctionsetIv($iv)
{
$this->iv=$iv;
}
}
//使用方法:
$keyStr='sq8f77fwhksk';
$aes=newAES($keyStr);
$str='www.nhooo.com';
$chgstr=$aes->encrypt($str);
echo$chgstr;
echo"
";
$rstr=$aes->decrypt($chgstr);
echo$rstr;
?>
运行结果:
pDyiRRNaxlss2b6SgoiVPdkD2m1QWhX393lh2iFgGdY=
www.nhooo.com
PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:
文字在线加密解密工具(包含