小程序使用jsencrypt加密,报Uncaught TypeError: Cannot read property ‘appName‘ of undefine

736 阅读1分钟

小程序使用jsencrypt对参数进行aes加密,在手机网页端可以正常使用,在小程序项目安装后使用报错。由于jsncrypt代码里面含有window、document、navigator对象,这些对象可以在pc端、移动端的浏览器使用,但是小程序没有这些对象,所以直接在小程序引入jsencrypt.js会直接报错,下面主要介绍如何在jsencrypt.js里面对这些对象进行兼容。

Uncaught TypeError: Cannot read property 'appName' of undefined
  • 源代码
if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
    BigInteger.prototype.am = am2;
    dbits = 30;
} else if (j_lm && (navigator.appName != "Netscape")) {
    BigInteger.prototype.am = am1;
    dbits = 26;
} else { // Mozilla/Netscape seems to prefer am3
    BigInteger.prototype.am = am3;
    dbits = 28;
}
  • navigator主要是对浏览器的判断,同时小程序中没有appName,直接删除或者保留最后一个else即可。这个解决后还会有其他的问题按照报错做兼容处理即可
BigInteger.prototype.am = am3;
dbits = 28;
  • 兼容window.crypto
if (window.crypto && window.crypto.getRandomValues) {
  // Extract entropy (2048 bits) from RNG if available
  var z = new Uint32Array(256);
  window.crypto.getRandomValues(z);
  for (t = 0; t < z.length; ++t) {
    rng_pool[rng_pptr++] = z[t] & 255;
  }
}
  • 注释上面代码改为下方代码
var getRandomValues = function (array) {
  for (var i = 0, l = array.length; i < l; i++) {
    array[i] = Math.floor(Math.random() * 256);
  }    return array;
}
var z = new Uint32Array(256);
getRandomValues(z);
  • 兼容window.removeEventListener、window.detachEvent,直接将所有的监听事件注释即可。
if (window.removeEventListener) {
  window.removeEventListener("mousemove", onMouseMoveListener_1, false);
}
else if (window.detachEvent) {
  window.detachEvent("onmousemove", onMouseMoveListener_1);
}
  • JSEncrypt对象不存在,直接注释即可。
window.JSEncrypt = JSEncrypt

修改后