累了一天了,话不多说了,直接上代码自行理解吧
HTML(index.html)代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP和JS的AES相互加解密方法(CryptoJS) - 远昔博客</title>
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script>
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/aes.min.js"></script>
<script src="https://cdn.bootcss.com/zepto/1.1.5/zepto.min.js"></script>
</head>
<body>
<div style="margin:0 18%;">
<h4>加密测试:</h4>
<ul>
<li id="encrypt_key"></li>
<li id="encrypt_string"></li>
</ul>
</div>
<div style="margin:0 18%;">
<h4>解密测试:</h4>
<ul>
<li id="decrypt_key">解密的密钥(PHP端生成):</li>
<li id="decrypt_string">JS解密后字符串:</li>
</ul>
</div>
<script type="text/javascript">
function encrypt(str, key, iv) {
//密钥16位
var key = CryptoJS.enc.Utf8.parse(key);
//加密向量16位
var iv = CryptoJS.enc.Utf8.parse(iv);
var encrypted = CryptoJS.AES.encrypt(str, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
});
return encrypted;
}
function decrypt(str, key, iv) {
var key = CryptoJS.enc.Utf8.parse(key);
var iv = CryptoJS.enc.Utf8.parse(iv);
var decrypted = CryptoJS.AES.decrypt(str, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
</script>
<script>
var key = '2s039f8jlvnapof09vbhn234';
var iv = 'A92v63wqfzftstgb';
var data = 'fcdc.cn|1658324044';
var encrypted_string = encrypt(data, key, iv);
$("#encrypt_key").text("【JS加密密钥】:" + key);
$("#encrypt_string").text("【JS加密后字符串】:" + encrypted_string);
var data2 = "tORfCZnp4a7C+CoBoe5/QBU150yrw1B7P4mecSFLwCY=";
var decrypted_string = decrypt(data2, key, iv);
$("#decrypt_key").text("【解密的密钥(PHP端生成)】:" + key);
$("#decrypt_string").text("【JS解密后字符串】:" + decrypted_string);
</script>
</body>
</html>
PHP(index.php)代码:
<?php
$key = '2s039f8jlvnapof09vbhn234';
$iv= 'A92v63wqfzftstgb';
$data = 'fcdc.cn|1658324044';
$encrypt=@base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv));//加密
echo $encrypt;
$decrypt=@mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypt), MCRYPT_MODE_CBC, $iv); //解密
echo $decrypt;
?>
附言:宝塔PHP需要安装mcrypt拓展
评论
发表评论: