0


前端使用jsencrypt库实现RSA公钥解密——uniapp同样适用

一、安装jsencrypt库

npm i jsencrypt

方法一、更改库的原生方法

在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. 保存文件

方法二、重写库的原生方法

1. 封装decrypt.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. 引用decrypt.js文件,调用方法解密

import{
        decrypt
    }from'./decrypt.js'let decrypted =decrypt(encryptedData, publicKey);
    console.log(decrypted);// 解密后的明文

本文转载自: https://blog.csdn.net/m0_52941894/article/details/135206085
版权归原作者 Amazing JSR 所有, 如有侵权,请联系我们删除。

“前端使用jsencrypt库实现RSA公钥解密——uniapp同样适用”的评论:

还没有评论