公钥私钥的生成和node中jwt非对称加密的实现

  1. 公钥私钥的生成环境

    1. 在mac上面可以直接使用openssl
    2. 在Windows上面cmd无法使用openssl,但git bash上可以使用openssl
  2. 生成公钥私钥的方法

    1. 在git bash中输入openssl打开openssl交互式工具
    2. 生成私钥:genrsa -out private.key 1024(genrsa表示非对称加密,-out表示导出私钥,private.key表示私钥名称,1024表示私钥长度)

    在这里插入图片描述

    c. 通过私钥生成公钥:rsa -in private.key -pubout -out public.key

    在这里插入图片描述

  3. node中引入jwt:npm i jsonwebtoken

  4. 使用jwt生成token

const jwt = require('jsonwebtoken')//引入jwt
const { PRIVATE_KEY } = require('./../app/config')

class AuthController {
  async login(ctx,next){

    const { id, name } = ctx.user
    const token = jwt.sign({id, name}, PRIVATE_KEY, {
      expiresIn: 60*60*24, //过期时间一天
      algorithm: 'RS256' //采用的算法
    } )

    ctx.body = {
      id,
      name,
      token
    }
  }
}

module.exports = new AuthController()
  1. 实现验证token的中间件
const jwt = require('jsonwebtoken');

const errorType = require('../constants/error-types');
const { PUBLIC_KEY } = require('../app/config');

const verifyToken = async function(ctx,next){
  //1.获取token
  const authorization = ctx.headers.authorization;
  const token = authorization.replace('Bearer ','');
  //2.验证token
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ['RS256']
    });
    ctx.user = result;
    console.log("user",result)
    await next();
  } catch (err) {
    const error = new Error(errorType.UNAUTHORIZATION);
    ctx.app.emit('error', error, ctx);
  }
}

module.exports = {
  verifyToken
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值