1. 安装crypto-js
npm install crypto-js -D
2. 在src目录下,建立crypto文件夹,新建index.js文件,写入加密代码
/*
* @Descripttion: 对用户登录信息进行加密处理
* @version:
* @Author: zhangfan
* @email: 2207044692@qq.com
* @Date: 2020-08-13 13:47:29
* @LastEditors: zhangfan
* @LastEditTime: 2020-08-13 14:47:09
*/
import CryptoJS from 'crypto-js';
export default {//加密
set(word, keyStr){
keyStr = keyStr ? keyStr : 'abcdefghijklmnop'; //16位的密钥,自己定义,和下面的密钥要相同
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();
},
//解密
get(word, keyStr){
keyStr = keyStr ? keyStr : 'abcdefghijklmnop';
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. 组件内引入并使用
import Crypto from "@/crypto/index.js";
//加密用户名和密码
vm.$Cookies.set("userName", escape(Crypto.set(vm.ruleForm.userName)), { expires: 7 });
vm.$Cookies.set("password", escape(Crypto.set(vm.ruleForm.password)), { expires: 7 });
//解密用户名和密码
vm.userName = Crypto.get(unescape(vm.$Cookies.get("userName")));
vm.password = Crypto.get(unescape(vm.$Cookies.get("password")))