RSA公钥解密
一、使用npm管理项目依赖时可以通过直接更改文件的方式使该修改生效
在node_modules目录下,根据如下路径找到rsa.js文件
jsencrypt/lib/lib/jsbn/rsa.js
- 1、修改 RSAKey.prototype.decrypt 方法(将doPrivate改为doPublic)
RSAKey.prototype.decrypt=function(ctext){var c =parseBigInt(ctext,16);// var m = this.doPrivate(c);var m =this.doPublic(c);if(m ==null){returnnull;}returnpkcs1unpad2(m,(this.n.bitLength()+7)>>3);};
- 2、修改 rsa.js文件下的pkcs1unpad2方法
functionpkcs1unpad2(d, n){var b = d.toByteArray();var 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){returnnull;}}var ret ="";while(++i < b.length){var c = b[i]&255;if(c <128){// utf-8 decode
ret += String.fromCharCode(c);}elseif((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;}
- 3、保存文件即可
保存修改后的rsa.js文件,一般情况下不需要重新编译也可生效,如有问题就重新build或serve一下,需要注意的是,如果删除了node_modules文件夹,或重新安装了jsencrypt,或对jsencrypt进行了版本升级,该功能均会失效,需要重新修改
二、修改RSA中prototype的decrypt方法
- 1、封装js文件,在文件中引入jsencrypt,并对解密方法重写
import JSEncrypt from'jsencrypt'import{ parseBigInt }from'jsencrypt/lib/lib/jsbn/jsbn'functionpkcs1unpad2(d, n){var b = d.toByteArray()var i =0while(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){returnnull}}var ret =''while(++i < b.length){var c = b[i]&255if(c <128){// utf-8 decode
ret += String.fromCharCode(c)}elseif((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
}exportfunctiondecrypt(data, publicKey){const encrypt =newJSEncrypt()
encrypt.setPublicKey(publicKey)// 不支持公钥解密// 自定义解析方法支持公钥解析const rsaKey = encrypt.getKey()
rsaKey.decrypt=function(ctext){var c =parseBigInt(ctext,16)var m =this.doPublic(c)if(m ==null){returnnull}returnpkcs1unpad2(m,(this.n.bitLength()+7)>>3)}return encrypt.decrypt(data)}
- 2、直接引用js文件,调用方法解密就行
有更好的方法,可以评论区留言
相关资源:
https://blog.csdn.net/anjiongyi/article/details/119391187?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522169094637016800192245768%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=169094637016800192245768&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v1~rank_v31_ecpm-7-119391187-null-null.142v92controlT0_2&utm_term=%E5%89%8D%E7%AB%AF%E4%BD%BF%E7%94%A8jsencrypt%E5%AE%9E%E7%8E%B0RSA%E5%85%AC%E9%92%A5%E8%A7%A3%E5%AF%86&spm=1018.2226.3001.4187
https://blog.csdn.net/jianggujin/article/details/130760512
版权归原作者 砚言 所有, 如有侵权,请联系我们删除。