定义全局方法
main.js
import DESKeys from "./utils/key";
import CryptoJS from "crypto-js"; // npm install crypto-js@4.2.0
/**
* 配置全局的加密方法(DES)
* 参数 plaintext 需要加密的字符串
*/
Vue.prototype.$encruptionDes = function (plaintext) {
//进行加密
let DesKey = DESKeys;
let key = CryptoJS.enc.Utf8.parse(DesKey);
let encrypted = CryptoJS.DES.encrypt(plaintext, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
};
/**
* 配置全局的解密方法(DES)
* 参数 ciphertext 需要解密的密文(Base64编码)
*/
Vue.prototype.$decryptionDes = function (ciphertext) {
let DesKey = DESKeys;
let key = CryptoJS.enc.Utf8.parse(DesKey);
let encryptedWordArray = CryptoJS.enc.Base64.parse(ciphertext);
let cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: encryptedWordArray
});
let decrypted = CryptoJS.DES.decrypt(cipherParams, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return decrypted.toString(CryptoJS.enc.Utf8);
};
// 定义反转义函数
Vue.prototype.$htmlUnescape = function(str) {
if (!str) return '';
const div = document.createElement('div');
div.innerHTML = str;
const result = div.textContent || div.innerText || '';
div.remove();
return result;
};
utils/key.js
let ab = 'CAE';
let bc = 'q2n';
let cd = 'qno';
let de = 'tM=';
let DesKeys = ab + bc + cd + de;
export default DesKeys;
使用方法
存取之前进行编码
存:encodeURIComponent(this.bindPassword)
取:let userPassword = decodeURIComponent(this.$decryptionDes(userPassword));
console.log('返回值Des解密解决转义', this.$htmlUnescape(userAccount),