首页 / 后端开发 / 服务端渲染中使用Rsa加密操作

服务端渲染中使用Rsa加密操作

2021-01-30 01:30 后端开发 阅读 4384 来源

在使用nuxtjs开发过程中,有的接口数据我们需要在asyncData中拿到,以便于我们来动态渲染title等标签,来帮助我们达到更好的seo优化的效果。最近在项目开发中有遇到在asyncData中使用jsencrypt进行Rsa加密的时候,报错navigation未定义,这是因为asyncData函数是在服务器端运行的,但windows、navigation等这些只存在于客户端。如果我们需要在服务端进行Rsa加密怎么办?在这里给教大家用node-rsa这个包在服务端进行加密

一、要使用首先安装,这在里我们用npm进行安装

npm install node-rsa --save-dev

二、新建文件进行引用


const NodeRsa = require('node-rsa')

// 加密
function encrypt (str) {
  const publicKey = `公钥`
  const nodersa = new NodeRsa(publicKey)
  // nodersa.setOptions({ encryptionScheme: 'pkcs1' })
  const encrypted = nodersa.encrypt(str, 'base64')
  return encrypted
}

//解密
function decrypt (str) {
  const privateKey = `私钥`

  const nodersa = new NodeRsa(privateKey)
  const decrypted = nodersa.decrypt(str, 'pkcs1')

  return decrypted
}

export default { encrypt, decrypt }


完成以上步骤我们就可以在asyncData等服务端函数中使用Rsa加密了

猜你喜欢