JSEncrypt: 非对称加密 RSA

1、修改源码,搜索:"t.prototype.getPublicKey = function(", 在后面接着加3个函数

(t.prototype.encryptLong = function(data) {
  const text = this.encode2Unicode(data);
  const akey = this.key;
  const maxLength = ((akey.n.bitLength() + 7) >> 3) - 11;
  try {
    const arr = [];
    if (text.length > maxLength) {
      const matchResult = text.match(/.{1,117}/g);
      matchResult.forEach(function (entry) {
        const temp = akey.encrypt(entry);
        arr.push(temp);
      });
      return this.hex2b64(arr.join(""));
    } else {
      let t = akey.encrypt(text);
      return this.hex2b64(t);
    }
  } catch (ex) {
    return false;
  }
}),
(t.prototype.encode2Unicode = function(text) {
  if (text == null) {
    return "";
  }
  const newText = [];
  for (var i = 0; i < text.length; i++) {
    var code = text.charCodeAt(i);
    if (code >= 128) {
      //91 is "[", 93 is "]".
      newText.push("\\u" + code.toString(16));
    } else {
      newText.push(text.charAt(i));
    }
  }
  return newText.join('');
}),
(t.prototype.hex2b64 = function(h) {
  var b64map =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var b64pad = "=";

    var i;
    var c;
    var ret = "";
    for (i = 0; i + 3 <= h.length; i += 3) {
      c = parseInt(h.substring(i, i + 3), 16);
      ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
    }
    if (i + 1 == h.length) {
      c = parseInt(h.substring(i, i + 1), 16);
      ret += b64map.charAt(c << 2);
    } else if (i + 2 == h.length) {
      c = parseInt(h.substring(i, i + 2), 16);
      ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
    }
    while ((ret.length & 3) > 0) ret += b64pad;
    return ret;
}),

2、前端用pubulicKey加密 ,后端用privateKey解密

const publicKey = '';

const ins = new JSEncrypt();

ins.setPublicKey(publicKey);

return ins.encryptLong(text);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值