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

本文介绍了在Java环境下,结合SpringCloud实现JWT与RSA非对称加密来创建安全的Token。内容包括配置YML文件、定义Token载荷、密钥工具类、Token工具类的编写,以及密码加密的盐工具类。通过私钥加密和公钥解密确保安全性,同时强调了公钥和私钥的正确管理和使用。
————JWT+RSA非对称加密生成token&spm=1001.2101.3001.5002&articleId=109028243&d=1&t=3&u=12a87635f9ea45078b271afbb9b82fff)
2945

被折叠的 条评论
为什么被折叠?



