前端使用jsencrypt进行RSA公钥解密

默认jsencrypt是不支持公钥解密的,需要更改
1.将jsencrypt.js源码复制一分到utils包下



2.然后对utils包下的jsencrypt进行更改

更改RSAKey.prototype.decrypt 方法(将doPrivate改为doPublic)

	RSAKey.prototype.decrypt = function (ctext) {
        var c = parseBigInt(ctext, 16);
        var m = this.doPublic(c);
        if (m == null) {
            return null;
        }
        return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
    };

原:

新:

更改pkcs1unpad2方法,更换内容如下:

function pkcs1unpad2(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) {
        return null
      }
    }
    var ret = ''
    while (++i < b.length) {
      var 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
  }
  

原:

新:

3. 实际使用:
import JSEncrypt from '@/utils/jsencrypt'

var encryptor = new JSEncrypt();  
	//	私钥加密后的数据
  var data = 'fGrPg4EOup/nopw4f8XCqNenVsPE2Ujr70TvjDvrfUDFFiYcx7ewLG7tM76x7N0nKiO7/QiWZU0GAEhrMBr4oNm+zGCi***MGeLaPUM0KOnYgN6kimFsMOIerd/25S3qdqj4qED84bTaT7VBni1L3APo8JOKVcWIk4kJPKK1nJUNwsQxJvbrD2+nOdrWjRuq3WIftdcEHBiVGycai+j8QUrVTKcTmYFjCWwC7JFRQjYv26pmCbq3rs3CT24xazc4CLDkx+y98H++my7zZkVTI675kH+pYlZbQfBkiHvLtCHUOEi+RDXhGNi9GO2DVTBVnAP173BV2VyFFYj85qeD/Qw==';
	// 公钥
var publicKey = 
  '-----BEGIN PUBLIC KEY-----\n' +  
  'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3IHVdOJg+nqaZGKc9wXJ'+
  'KUqwI95F/qCvPQoDyf0cDZzebbAGEOs4m7LAQwfa6A+q6cRhBHtDYco6cv7wufmi'+
  'qJ9U7yVFnvha1wi3jkXn1AxUAvUw+bLtrhjZg/akxAukXX7fsOdCPbk8AitlnaH1'+
  '2S5Np0Ugxx/rN+LOkkxwAOIzu/z1SvGLoPGFDHW/7mna8txs3SwlpG3TDGOXOsEu'+
  '4vcXbRKmLApUlrluhny7GTGGVi8TqrmviyrfcAj/098AI5aRzv/Y0TchsJVOtoaz'+
  'CsHjjp/Cf4RnSuL+KyBio7wGlR+Iyy/ywpMUiae3vJb3qd0Wx8824SbgClTIA1f4'+
  'HwIDAQAB'+
    '\n-----END PUBLIC KEY-----';  

  // console.log("111",decrypt(data,publicKey));

  encryptor.setPublicKey(publicKey);  
  var decryptedData = encryptor.decrypt(data,publicKey);  
    
  // 显示解密结果  
  console.log("解密:",decryptedData);


转载请说明出处内容投诉
CSS教程_站长资源网 » 前端使用jsencrypt进行RSA公钥解密

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买