aes/cbc/pkcs5padding/128加解密
程序员文章站
2024-03-14 14:42:46
...
//******aes/cbc/pkcs5padding/128加解密******
private function aesEncrypt($data,$iv=''){
$enc_key = 'KlW';//随机生成16为由大小写字符和数字组成的字符串
$enc_iv = self::aesRandom(16,'1234567890abcdefghijklmnopqrstuvwxyz');//随机生成16位iv
if($iv){
$enc_iv=$iv;
}
$method = MCRYPT_RIJNDAEL_128;
$mode = MCRYPT_MODE_CBC;
//优化
$block = mcrypt_get_block_size($method, $mode);
$pad = $block - (strlen($data)%$block);
$pad = $data.str_repeat(chr($pad), $pad);
$td = mcrypt_module_open($method, '', $mode, '');
mcrypt_generic_init($td , $enc_key , $enc_iv);
$encrypt = mcrypt_generic($td, $pad);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return base64_encode($enc_iv.$encrypt);//iv拼密串之后base64
}
private function aesDecrypt($data){
$dec_key = 'lW';//随机生成16为由大小写字符和数字组成的字符串
$data = base64_decode($data) ;//base64
$dec_iv = substr($data, 0, 16);//前16位为iv
if(strlen($dec_iv)<16){
return false;
}
$data = substr($data,16); //16位后未密串
$method = MCRYPT_RIJNDAEL_128;
$mode = MCRYPT_MODE_CBC;
$td = mcrypt_module_open($method, '', $mode, '');
mcrypt_generic_init($td , $dec_key , $dec_iv);
$decrypt = mdecrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
//Remove the padding
$pad = ord($decrypt[($len = strlen($decrypt))-1]);
//优化
$beforePad = strlen($decrypt) - $pad;
$decrypt = substr($decrypt, $beforePad) == str_repeat(substr($decrypt, -1), $pad) ? substr($decrypt, 0, $len - $pad) : $decrypt;
return $decrypt;
}
private function aesRandom($length, $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789')
{
$hash = '';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++)
{
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
private function checkOpenid($openid){
if(!$openid){
$json = json_encode(array('success'=>false,'msg'=>'参数非法'));
return $json;
}
// $openid = str_replace(' ', '+', urldecode($openid));
return $this->aesDecrypt(urldecode($openid));
}
上一篇: RSA加密超长数据 前端js 作为参考
下一篇: 文件下载代码
推荐阅读
-
aes/cbc/pkcs5padding/128加解密
-
AES-128-CBC 加密
-
Java实现AES/CBC/PKCS7Padding加解密的方法
-
AES(128、ECB、PKCS5Padding)
-
基于NodeJS开发钉钉回调接口实现AES-CBC加解密
-
php aes 128 CBC加密、解密函数 php aes mcrypt php aes ecb php java aes加密解
-
Java利用 AES/ECB/PKCS5Padding 算法加解密
-
php aes 128 CBC加密、解密函数 php aes mcrypt php aes ecb php java aes加密解
-
拿来主义之_AES加解密(CBC模式)
-
IOS 与 PHP 通信加密,使用AES 128 CBC no padding