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


注意
加密的对象一定要是字符串 如果你加密的是密码 则npm i jsencrypt 即可
如果加密的是对象并且数据还挺多的 比如含有token 用npm i encryptlong -S
npm i jsencrypt加密长对象将返回false 或者报Message too long for RSA.

npm地址

npm i jsencrypt

npm 地址

npm i encryptlong -S

在utils文件夹里新建rsa.js文件

// 普通的就是 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(passwd) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey)
  // 普通的就是return encryptor.encrypt(passwd)
  return encryptor.encryptLong(passwd)
}

// 私钥解密
export function decrypt(passwd) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey)
 // 普通的就是return decryptor.decrypt(passwd)
  return encryptor.encryptLong(passwd)
}

vue页面用法

import { encrypt, decrypt } from '@/utils/rsa'

toPurchase(id, host) {
      // 加密数据
      const data = { xxxxx: xxxxxxxxxxx}
      const resultEncrypt = encrypt(JSON.stringify(data))
      // resultEncrypt 是加密结果
      // 后面涉及到url拼接就不做展示了
},
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐