利用CryptoJS进行aes的AES/ECB/PKCS5Padding加密

时间:2022-05-18 18:21:59

CryptoJS是javascrpit强大的加密解密库,服务端采用AES/ECB/PKCS5Padding加密,所以前端CryptoJS也要采用aes的ecb加密

注意事项:

1、PKCS5Padding的补码方式,其实就是PKCS7

2、加密模式是ecb

3、还可以设置偏移量,我服务端没设置,故前端js也不需要

引入的js库

<!-- CryptoJS -->
<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>
js代码
var key = CryptoJS.enc.Utf8.parse(getKey());

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();
}
这里采用动态密钥方式加密,所以每次都会从服务端重新获取一次密钥key