encrypt-util.js 1.23 KB
import CryptoJS from "crypto-js";
import JsEncrypt from "jsencrypt";
let rsa = new JsEncrypt();

/*
 * 创建加密
 * @param data
 * 
 * 设置项 
 * key 公钥 
 * iv 偏移量
 */
export function makeEncrypt(param) {
    let key = "";
    let iv = ""
    rsa.setPublicKey(key);
    let chars = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z".split(",");

    function randomAesKey() {
        let res = "";
        for (let i = 0; i < 16; i++) {
            let id = Math.ceil(Math.random() * (chars.length - 1));
            res += chars[id];
        }
        return res;
    };

    function encryptContent(obj) {
        let aesKey = randomAesKey();
        let key = CryptoJS.enc.Utf8.parse(aesKey);
        let ivR = CryptoJS.enc.Utf8.parse(iv);
        var encrypted = CryptoJS.AES.encrypt(JSON.stringify(obj), key, {
            iv: ivR,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        let content = encrypted.toString(); //返回的是base64格式的密文
        let securityKey = rsa.encrypt(aesKey);

        let result = {
            k: securityKey,
            v: content
        };
        return result;
    };
    let data = encryptContent(param)
    return data;
}