enc.js 1.21 KB
const config = require('./../../config');
const CryptoJS = require('./crypto-js.min');
const Encrypt = require('./jsencrypt.min');

var rsa = new Encrypt.JSEncrypt();

function makeEncrypt(param) {

  let key = config.NET_CONFIG.RSA_PUBLIC_KEY; // 公钥
  let iv = config.NET_CONFIG.AES_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];
    }
    1
    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;
}

module.exports = {
  makeEncrypt
}