PHP与JS使用AES/CBC进行通讯

前端加密,引入aes.js (下载地址:aes.zip),代码如下:

<script src="/js/aes.js"></script>
//AES-128-CBC加密模式,key需要为16位,key和iv可以一样
//定义密钥
var key = CryptoJS.enc.Utf8.parse('dvyYRQlnPRCMdQSe');
//定义IV偏移
var iv = CryptoJS.enc.Utf8.parse('face0123456789ai');
//加密
function encrypt(data) {
return CryptoJS.AES.encrypt(data, key, {iv: iv, mode: CryptoJS.mode.CBC}).toString();
}
//解密
function decrypt(data) {
return CryptoJS.AES.decrypt(data, key, {iv: iv}).toString(CryptoJS.enc.Utf8);
}
var encrypted = encrypt('你好世界,我是荔枝!');
console.log(encrypted);//IuacjXO0XNdmgl0oI4lS+7nPGACpfEmuXtAeRcPKTR0=
var decrypted = decrypt(encrypted);
console.log(decrypted);//你好世界,我是荔枝!

PHP后端类代码(Aes.class.php)

<?php
/**
* AES加密类库
* Class AesUtil
*/
class AesUtil
{
/**
* AES/CBC 加密
* @param $data
* @param $encryptKey
* @param $localIV
* @return string
*/
public static function encrypt($data, $encryptKey, $localIV)
{
if (PHP_VER >= 7.1) {
//php7.1新版本加密
return base64_encode(openssl_encrypt($data, 'aes-128-cbc', $encryptKey, OPENSSL_RAW_DATA, $localIV));
} else {
//php7.1以下版本加密
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
mcrypt_generic_init($module, $encryptKey, $localIV);
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($data) % $block);
$data .= str_repeat(chr($pad), $pad);
$encrypted = mcrypt_generic($module, $data);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return base64_encode($encrypted);
}
}

/**
* AES/CBC 解密
* @param $data
* @param $encryptKey
* @param $localIV
* @return bool|string
*/
public static function decrypt($data, $encryptKey, $localIV)
{
if (PHP_VER >= 7.1) {
//php7.1新版本解密
return openssl_decrypt(base64_decode($data), 'aes-128-cbc', $encryptKey, 1, $localIV);
} else {
//php7.1以下版本解密
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
mcrypt_generic_init($module, $encryptKey, $localIV);
$data = mdecrypt_generic($module, base64_decode($data));
$data = str_replace("", "", $data);
return $data;
}
}
}

引入上面的Util类,然后下面是示例代码

//加密,结果:IuacjXO0XNdmgl0oI4lS+7nPGACpfEmuXtAeRcPKTR0=
echo $encrypt = aes::encrypt('你好世界,我是荔枝!', "dvyYRQlnPRCMdQSe", "face0123456789ai");
//解密,结果:你好世界,我是荔枝!
echo aes::decrypt($encrypt, "dvyYRQlnPRCMdQSe", "face0123456789ai");引入上面的Util类,然后下面是示例代码
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注