网上很多博客写了php与js的对称加密与解密aes,但是有很多坑,今天我写了一个可以切实可行的js与php加密解密的代码,代码可在线运行,非常方便
首先是js的aes加密
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BFW NEW PAGE</title>
<script id="bfwone" data="dep=jquery.17|https://anyun.org/a/tag/crypto/-js-3.1.9-1/https://anyun.org/a/tag/crypto/-js|crypto-js-3.1.9-1/pad-zeropadding&err=0" type="text/javascript" src="http://repo.bfw.wiki/bfwrepo/js/bfwone.js"></script>
<script type="text/javascript">
bready(function() {
var iv = 'httpwww.bfw.wiki';
var data = "it在线开发环境 bfwstuio";
console.log('JS加密前:'+data);
var key = CryptoJS.enc.Utf8.parse('www.bfw.wikihttp');
var ivv = CryptoJS.enc.Utf8.parse(iv);
var encrypted = CryptoJS.AES.encrypt(data, key, {
iv: ivv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding
});
data = encrypted.toString();
console.log('JS加密后:'+data);
$("#enc_txt").html(data);
var decrypted = CryptoJS.AES.decrypt(data, key, {
iv: ivv, padding: CryptoJS.pad.ZeroPadding
});
var rest = decrypted.toString(CryptoJS.enc.Utf8);
console.log('JS解密后数据:'+rest);
});
</script>
</head>
<body>
<div id="enc_txt">
</div>
</body>
</html>
js加密后传给php,后端的aes解密代码
<?php
$data = 'it在线开发环境 bfwstuio';
$key = 'www.bfw.wikihttp';
$methon = 'AES-128-CBC';
$iv = "httpwww.bfw.wiki";
$decrypted = base64_encode(openssl_encrypt($data, $methon, $key, 1, $iv)); //加密
echo 'PHP加密后:'.$decrypted;
$jsencodedata = "XRP4t0mMLrEKlAhB60mqSR7GTEsE4OfR+pGpPxu5Oxo=";
$decrypted = openssl_decrypt($jsencodedata, 'AES-128-CBC', $key, OPENSSL_ZERO_PADDING, $iv); // 解密
echo 'PHP解密后:'.$decrypted;
?>
ok,代码可以在线编辑运行,不用复制到本地就可看到效果