前端RSA公钥解密

发布时间 2023-09-20 10:56:39作者: 沧海一水u

前端加解密使用的jsencrypt包,jsencrypt包中只有公钥加密,私钥解密的方法,但项目中要求前端公钥解密,通过重写jsencrypt包中的方法来实现

/**
* 重写JSEncrypt解密方法以支持公钥解密
* */
private pkcs1unpad2(d, n) {
const b = d.toByteArray();
let i = 0;
while (i < b.length && b[i] === 0) {
++i;
}
// if (b.length - i !== n - 1 || b[i] !== 2) {
// return null
// }
++i;
while (b[i] !== 0) {
if (++i >= b.length) {
return null;
}
}
let ret = '';
while (++i < b.length) {
const c = b[i] & 255;
if (c < 128) { // utf-8 decode
ret += String.fromCharCode(c);
} else if ((c > 191) && (c < 224)) {
ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
++i;
} else {
ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
i += 2;
}
}
return ret;
}

public rsaDecryFn(str,pubKey) {
  if (str) {
const encrypt: any = new JSEncrypt();
encrypt.setPublicKey(pubKey);
// 自定义解析方法支持公钥解析
const rsaKey: any = encrypt.getKey();
const that = this;
rsaKey.decrypt = function(ctext) {
const c = parseBigInt(ctext, 16);
const m = this.doPublic(c);
if (m == null) {
return null;
}
return that.pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
};
rsaKey.decryptLong = function (text: string) {
const maxLength = ((this.n.bitLength() + 7) >> 3);
try {
if (text.length > maxLength) {
let ct = '';
const lt = text.match(/.{1,256}/g);
lt.forEach((entry) => {
const t1 = (this as any).decrypt(entry);
ct += t1;
});
return ct;
}
const y = this.decrypt(text);
return y;
} catch (ex) {
return false;
}
};
try {
return encrypt.getKey().decryptLong(b64tohex(str));
} catch (ex) {
return false;
}
}
return str;
}


调用rsaDecryFn方法来公钥解密