Vue中使用crypto-js实现前端加密后端解密的功能
1,前端添加相应的依赖
“crypto-js”: “^4.1.1”
npm install crypto-js
2,前端添加工具类
import CryptoJS from 'crypto-js';
export default {
//随机生成指定数量的16进制key
generatekey(num) {
let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let key = "";
for (var i = 0; i < num; i++) {
let randomPoz = Math.floor(Math.random() * library.length);
key += library.substring(randomPoz, randomPoz + 1);
}
return key;
},
//加密
encrypt(word) {
var keyStr ="0123456789101112";
var key = CryptoJS.enc.Utf8.parse(keyStr);
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
return encrypted.toString();
},
//解密
decrypt(word) {
var keyStr ="0123456789101112";
var key = CryptoJS.enc.Utf8.parse(keyStr);
var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
}
3,在man.js中将方法挂载到Vue实例上面
4,前端加密和解密
5,后端解密工具类
@Slf4j
public class AesUtil {
private static final String ALGORITHMS = "AES/ECB/PKCS5Padding";
private static final String KEY = "0123456789101112";
/**
* 加密
*
* @param content 内容
* @return java.lang.String
*/
public static String encrypt(String content) {
try {
//获得密码的字节数组
byte[] raw = KEY.getBytes();
//根据密码生成AES密钥
SecretKeySpec skey = new SecretKeySpec(raw, "AES");
//根据指定算法ALGORITHM自成密码器
Cipher cipher = Cipher.getInstance(ALGORITHMS);
//初始化密码器,第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二个参数为生成的AES密钥
cipher.init(Cipher.ENCRYPT_MODE, skey);
//获取加密内容的字节数组(设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
//密码器加密数据
byte[] encodeContent = cipher.doFinal(byteContent);
//将加密后的数据转换为字符串返回
return Base64.encodeBase64String(encodeContent);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 解密
*
* @param encryptStr 加密后的内容
* @return java.lang.String
*/
public static String decrypt(String encryptStr) {
try {
//获得密码的字节数组
byte[] raw = KEY.getBytes();
//根据密码生成AES密钥
SecretKeySpec skey = new SecretKeySpec(raw, "AES");
//根据指定算法ALGORITHM自成密码器
Cipher cipher = Cipher.getInstance(ALGORITHMS);
//初始化密码器,第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二个参数为生成的AES密钥
cipher.init(Cipher.DECRYPT_MODE, skey);
//把密文字符串转回密文字节数组
byte[] encodeContent = Base64.decodeBase64(encryptStr);
//密码器解密数据
byte[] byteContent = cipher.doFinal(encodeContent);
//将解密后的数据转换为字符串返回
return new String(byteContent, StandardCharsets.UTF_8);
} catch (Exception e) {
log.error("String : {} aes decrypt error", encryptStr);
return null;
}
}
}