前端RSA加密方法jsencrypt encryptlong以及遇到的问题

注意:
加密的对象一定要是字符串 如果你加密的是字符串且数据少 则npm i jsencrypt 即可
如果加密的是对象并且数据多 比如含有token 用npm i encryptlong -S
npm i jsencrypt加密长对象将返回false 或者报Message too long for RSA.
//引入对应包
//npm i jsencrypt
npm i encryptlong -S
//import JsEncrypt from 'jsencrypt'
import { JSEncrypt } from 'encryptlong'

//公钥
const publicKey = '-----BEGIN PUBLIC KEY-----公钥-----END PUBLIC KEY-----'
//私钥
const privateKey = '-----BEGIN RSA PRIVATE KEY-----私钥-----END RSA PRIVATE KEY----'

//公钥加密
export function encrypt(str) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey)
  //return encryptor.encrypt(str)
  return encryptor.encryptLong(str)
}

//私钥解密
export function decrypt(str) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey)
  //return decryptor.decrypt(str)
  return encryptor.encryptLong(str)
}

用法:

//加密数据
const data = { sumu: 123456 }
//加密结果
const resEncrypt = encrypt(JSON.stringify(data))
//解密结果
const resDecrypt = decrypt(resEncrypt)
posted @ 2025-06-04 17:50  苏沐~  阅读(399)  评论(0)    收藏  举报