Java校园淘项目实战(1)————JWT+RSA非对称加密生成token

本文介绍了在Java环境下,结合SpringCloud实现JWT与RSA非对称加密来创建安全的Token。内容包括配置YML文件、定义Token载荷、密钥工具类、Token工具类的编写,以及密码加密的盐工具类。通过私钥加密和公钥解密确保安全性,同时强调了公钥和私钥的正确管理和使用。

springCloud环境配置好了,接下来就是先把工具类写好,因为接下来要写用户接口微服务,所有打算先把密钥工具类和生成token的工具类写好。
(1)yml配置,里面声明了公钥和私钥存放的地方。

server:
  port: 10021
spring:
  application:
    name: commons-service
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka/
    registry-fetch-interval-seconds: 10
  instance:
    prefer-ip-address: true
    ip-address: 127.0.0.1
    instance-id: ${spring.application.name}:${server.port}
    lease-renewal-interval-in-seconds: 5
    lease-expiration-duration-in-seconds: 20

schooltao:
  rsa:
    publicKeyPath: "D:\\schoolProject\\rsa\\rsaPub.txt"
    privateKeyPath: "D:\\schoolProject\\rsa\\rsaPri.txt"
    secure: "schooltao"
    cookieName: "TAO_TOKEN"

(2)token使用私钥加密,公钥解密。
token的载荷对象,里面包含了id和name,没有把密码放在里面,是为了更加安全

package com.tao.common.pojo;

public class UserInfo {
    /**
     * 用户ID
     */
    private Long userId;
    /**
     * 用户账号
     */
    private String userName;


    public UserInfo() {
    }

    public UserInfo(Long userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

(3)密钥工具类
注意:大家一定要记住,必须要把公钥和私钥生成的字节数组经过base64加密,因为token是采用base64加密的,在获取公钥和私钥的时候,一定要记得使用base64解密。

package com.tao.common.utils;


import org.apache.commons.io.FileUtils;
import org.bouncycastle.util.encoders.Base64Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值