前后端使用rsa加密

2020-10-09  本文已影响0人  前端陈陈陈

一般是客户端初始化时访问登录服务时,服务端面动态生成一对RSA对,公钥传给客户端,客户端拿到后,用户输入密码后,点登录时用公钥加密返回给服务端,服务端用私钥解就行了

import JSEncrypt from 'jsencrypt/bin/jsencrypt'   // 引入
const publicKey = ' //公钥'

const privateKey = '  //密钥'
// 加密
export function encrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对需要加密的数据进行加密
}

// 解密
export function decrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey)
  return encryptor.decrypt(txt)
}

公钥、密钥测试:

import JSEncrypt from 'jsencrypt/bin/jsencrypt'



const publicKey = '   '

const privateKey = '   '

// 加密
function encrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对需要加密的数据进行加密
}

// 解密
function decrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey)
  return encryptor.decrypt(txt)
}
encrypt('SuperMePassword')
const aa = encrypt('SuperMePassword')
const bb = decrypt(aa)
console.log('bbbbbbbbbbbbbb', aa)
上一篇 下一篇

猜你喜欢

热点阅读