VUE AES对称加密

通过cnpm或者npm引入cryptoJS

npm install crypto-js --save-dev

在工具目录utils下新建文件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) {
        keyStr = keyStr ? keyStr : 'abcdsxyzhkj12345'; //判断是否存在ksy,不存在就用定义好的key
        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, keyStr) {
        keyStr = keyStr ? keyStr : 'abcdsxyzhkj12345';
        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();
    }
 
}

在需要用到的地方引入

import AES from "@/utils/AES.js";

或者在main.js中全局引入

import AES from '@/utils/AES.js'
Vue.prototype.AES = AES

调用

var keys = AES.generatekey(16);
 
//如果是对象/数组的话,需要先JSON.stringify转换成字符串
 
var encrypts = AES.encrypt(JSON.stringify(cars),keys);
var dess = JSON.parse(AES.decrypt(encrypts,keys));
// var encrypts = that.$encrypt('1234asdasd',keys);
 
// var dess = that.$decrypt(encrypts,keys);
console.log(encrypts)
console.log(encrypts.length)
console.log(dess)

你可能感兴趣的:(vue,vue)