CryptoJS是javascrpit强大的加密解密库,服务端采用AES/ECB/PKCS5Padding加密,所以前端CryptoJS也要采用aes的ecb加密
注意事项:
1、PKCS5Padding的补码方式,其实就是PKCS7
2、加密模式是ecb
3、还可以设置偏移量,我服务端没设置,故前端js也不需要
引入的js库
<!-- CryptoJS -->js代码
<script src="<%=request.getContextPath()%>/common/js/CryptoJS v3.1.2/components/core-min.js"></script>
<script src="<%=request.getContextPath()%>/common/js/CryptoJS v3.1.2/components/cipher-core-min.js"></script>
<script src="<%=request.getContextPath()%>/common/js/CryptoJS v3.1.2/components/mode-ecb-min.js"></script>
<script src="<%=request.getContextPath()%>/common/js/CryptoJS v3.1.2/rollups/aes.js"></script>
var key = CryptoJS.enc.Utf8.parse(getKey());这里采用动态密钥方式加密,所以每次都会从服务端重新获取一次密钥key
function getKey(){
//重新请求获取key
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var header = req.getResponseHeader("Random-Key");
return header;
}
/**
* [encrypt 加密]
* @return {[type]} [description]
*/
function encrypt(content) {
var encryptResult = CryptoJS.AES.encrypt(content, key, {
//iv: key,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encryptResult.toString().toUpperCase();
}
/**
* [decrypt 解密]
* @return {[type]} [description]
*/
function decrypt(content) {
var bytes = CryptoJS.AES.decrypt(content.toString(), key, {
//iv: key,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var decryptResult = bytes.toString(CryptoJS.enc.Utf8);
return decryptResult.toString().toUpperCase();
}