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

前端 0

一、安装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) {        return null;    }    return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);};

2. 修改 rsa.js文件下的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. 保存文件

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

1. 封装decrypt.js文件,在文件中引入jsencrypt,并对解密方法重写

import JSEncrypt from 'jsencrypt'import { parseBigInt } from 'jsencrypt/lib/lib/jsbn/jsbn'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}export function decrypt(data, publicKey) {    const encrypt = new JSEncrypt()    encrypt.setPublicKey(publicKey)    // 不支持公钥解密    // 自定义解析方法支持公钥解析    const rsaKey = encrypt.getKey()    rsaKey.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)    }    return encrypt.decrypt(data)  }

2. 引用decrypt.js文件,调用方法解密

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

也许您对下面的内容还感兴趣: