第一步:
//安装
npm install crypto-js --save-dev
第二步:在src目录下新建个放公用js文件夹(common),再建一个DES.js文件,例如
第三步:在DES.js中填写如下代码
import cryptoJs from 'crypto-js';
//随机生成指定数量的16进制key
export const 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;
}
//DES加密
export const encryptDes = (message, key) => {
var keyHex = cryptoJs.enc.Utf8.parse(key)
var option = { mode: cryptoJs.mode.ECB, padding: cryptoJs.pad.Pkcs7 }
var encrypted = cryptoJs.DES.encrypt(message, keyHex, option)
return encrypted.ciphertext.toString()
}
//DES解密
export const decryptDes = (message, key) => {
var keyHex = cryptoJs.enc.Utf8.parse(key)
var decrypted = cryptoJs.DES.decrypt(
{
ciphertext: cryptoJs.enc.Hex.parse(message)
},
keyHex,
{
mode: cryptoJs.mode.ECB,
padding: cryptoJs.pad.Pkcs7
}
)
return decrypted.toString(cryptoJs.enc.Utf8)
}
第四步:在需要的地方引入
import { encryptDes, decryptDes,generatekey } from '@/common/DES.js'
第五步:调用,例如在methods方法中调用
var keys = generatekey(16);
//如果是对象/数组的话,需要先JSON.stringify转换成字符串
var encrypts = encryptDes(JSON.stringify(cars),keys);
var dess = JSON.parse(decryptDes(encrypts,keys));
// var encrypts = that.$encrypt('1234asdasd',keys);
// var dess = that.$decrypt(encrypts,keys);
console.log(encrypts)
console.log(encrypts.length)
console.log(dess)
参考资料: