一、nodejs加解密工具类:
/**
* AES util
*/
const CryptoJS = require('crypto-js')
export const AES = {
//加密
encode: (params) => {
let { data, param, key } = params
let result = JSON.parse(JSON.stringify(data))
param.forEach(ele => {
let data = result[ele]
key = CryptoJS.enc.Utf8.parse(key)
let iv = key
let encrypted = CryptoJS.AES.encrypt(data,key,{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
})
result[ele] = encrypted.toString();
})
return result
},
decode: (params) => {
let { data, param, key } = params
let result = JSON.parse(JSON.stringify(data))
param.forEach(ele => {
let data = result[ele]
key = CryptoJS.enc.Utf8.parse(key)
let iv = key
let decrypt = CryptoJS.AES.decrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
});
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
result[ele] = decryptedStr.toString();
})
return result
}
}
使用方法:
(1)加密:
let user = AES.encode({
data: {//要加密的数据
username:'123456',
password:'123456'
},
key: '1234567887654321',//加密的key
param: ['password']//要加密哪些属性
})
(2)解密:
let user = AES.decode({
data: {//要解密的数据
username:'123456',
password:'lBTqrKS0kZixOFXeZ0HRng=='
},
key: '1234567887654321',
param: ['user']//要解密哪些属性
})
二、Java解密:
private static String decryptAES(String data, String pass) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding");
SecretKeySpec keyspec = new SecretKeySpec(pass.getBytes(), KEY_ALGORITHM);
IvParameterSpec ivspec = new IvParameterSpec(pass.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] result=cipher.doFinal(Base64.decode(data.getBytes(CharsetUtil.UTF_8)));
return new String(result, CharsetUtil.UTF_8);
}
使用方法:
try {
String s = decryptAES("lBTqrKS0kZixOFXeZ0HRng==", "1234567887654321");
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
三、Java加密:
private static String encryptAES(String data,String pass) throws Exception {
byte[] raw = pass.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(pass.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(data.getBytes());
return new Base64().encode(encrypted);
}
使用方法:
String e=encryptAES("123456","1234567887654321");
System.out.println(e);