安装AES文件
终端输入命令:npm install crypto-js --save-dev
在src目录下common下新建个放公用js文件夹,再建一个AES.js文件
在AES.js中填写如下代码
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, keyStr) {
var key = CryptoJS.enc.Utf8.parse(keyStr);
var iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412');//十六位十六进制数作为秘钥偏移量(ABCDEF1234123412)
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
return encrypted.ciphertext.toString().toUpperCase();
},
//解密
decrypt(word, keyStr) {
var key = CryptoJS.enc.Utf8.parse(keyStr);
var iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412');//十六位十六进制数作为秘钥偏移量(ABCDEF1234123412)
var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
var decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
}
在main.js引入
import AES from '@/common/AES.js'
调用
var dic = this.AESDecrypt.decrypt(‘要解密的字符串’,'解密秘钥');