1.引入JS插件包
aes.js
core.js
enc-base64.js
mode-ecb-min.js
pad-nopadding-min.js
2.JS使用
function aesDecrypt(encrypted, key) {
console.log("encrypted="+encrypted);
var encrypted1 = CryptoJS.enc.Base64.parse(encrypted);
var decrypted = CryptoJS.AES.decrypt(encrypted, CryptoJS.enc.Utf8.parse(key), {
iv:CryptoJS.enc.Utf8.parse(key),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.NoPadding
});
decrypted = CryptoJS.enc.Utf8.stringify(decrypted);// 轉換為 utf8 字元串
console.log("decrypted="+decrypted);
return decrypted;
}
3.java代碼
/**
* 向js頁面 輸出參數進行加密 (AES/CBC/NoPadding)
* @param data 要加密的資料
* @param key 加密key
* @param iv 加密iv
* @return 加密的結果
* @throws Exception
*/
public static String encryptJS(String data, String key, String iv){
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/補碼方式"
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes("UTF-8");//如果有中文,記得加密前的字元集
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != ) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, , plaintext, , dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return Base64.encodeBase64String(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}