1.vue 安裝crypto.js
cnpm install crypto-js --save
ECB:是一種基礎的加密方式,密文被分割成分組長度相等的塊(不足補齊),然后單獨一個個加密,一個個輸出組成密文。
CBC:是一種循環模式,前一個分組的密文和當前分組的明文異或或操作后再加密,這樣做的目的是增強破解難度。(不容易主動攻擊,安全性好於ECB,是SSL、IPSec的標准)
2.新建js文件。
ECB模式:
const CryptoJS = require('crypto-js') // 引用AES源碼js
const key = CryptoJS.enc.Utf8.parse('1234567812345678') // 十六位十六進制數作為密鑰
const iv = CryptoJS.enc.Utf8.parse("1234567812345678");//十六位十六進制數作為密鑰偏移量
// 解密方法
function Decrypt(word) {
let decrypt = CryptoJS.AES.decrypt(word, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
return decryptedStr.toString()
}
// 加密方法
function Encrypt(word) {
let encrypted = CryptoJS.AES.encrypt(word, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString()
}
export default {
Decrypt,
Encrypt
}
3.java端工具類
private final static String password = "1234567812345678";//目前使用
private final static String IV = "1234567812345678";//目前使用
public static String decryptAES(String content) throws Exception {
byte[] contentNew = Base64.decodeBase64(content);
SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // "算法/模式/補碼方式"
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
return new String(cipher.doFinal(contentNew));
}
4.CBC模式
const CryptoJS = require('crypto-js') // 引用AES源碼js
const key = CryptoJS.enc.Utf8.parse('1234567812345678') // 十六位十六進制數作為密鑰
const iv = CryptoJS.enc.Utf8.parse("1234567812345678"); //十六位十六進制數作為密鑰偏移量
// 解密方法
function Decrypt(word) {
var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
let decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
return decryptedStr.toString()
}
// 加密方法
function Encrypt(word) {
let encrypted = CryptoJS.AES.encrypt(word, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
return encrypted.toString()
}
export default {
Decrypt,
Encrypt
}
5.java端
private final static String password = "12334567812345678";//目前使用
private final static String IV = "12334567812345678";//目前使用
public static String decryptAES(String content) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes("ASCII"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = Base64.decodeBase64(content);//先用bAES64解密
return new String(cipher.doFinal(encrypted1));
}
6.前端使用
import encrypt from '@/config/encrypt.js' let pwdNew = encrypt.Encrypt(this.pwd);
