前端公钥加密解密

前端加密

一般情况下,我们都是使用公钥加密、私钥解密,这时JSEncrypt已经基本可以解决问题,使用方式如下:

JSEncrypt

安装
 npm install jsencrypt 
引入
 import JSEncrypt from 'jsencrypt'
JSEncrypt加密(公钥)
const publicKey = await getPublicKey() // 从接口获取公钥
const encrypt = new JSEncrypt() // 设置公钥
encrypt.setPublicKey(publicKey)
const pass = encrypt.encrypt(password) // 密码加密
JSEncrypt解密(私钥)
const publicKey = '私钥'
const crypt = new JSEncrypt() // 设置私钥
crypt.setKey(publicKey)
const content = crypt.decrypt(passContent) // 解密

有时候我们没有办法拿到私钥去解密,就只能使用公钥解密,此时JSEncrypt已无法满足,只能使用node rsa

Node-rsa

官方文档

安装
npm install node-rsa
npm install @types/node-rsa -D
使用公钥解密
const res = await getPublicKey() // 获取公钥
const publicKey = `-----BEGIN PUBLIC KEY-----\n${
      
      res.data}\n-----END PUBLIC KEY-----` // 公钥封装,加入前后缀
const NodeRSA = require('node-rsa')
const key = new NodeRSA(publicKey)
password = key.decryptPublic(pwd, 'utf8') // 解密

猜你喜欢

转载自blog.csdn.net/Guoxuxinwen/article/details/129950904