1、pom依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> <version>2.2.2.RELEASE</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.12.5</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.16</version> </dependency> </dependencies>
2、生成公私钥,私钥生成token
package com.nancal.util; import com.nancal.vo.KeyPairVO; import io.jsonwebtoken.Jwts; import org.apache.tomcat.util.codec.binary.Base64; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Date; import java.util.HashMap; import java.util.Map; public class RSAKeyUtils { /** * token过期时间 * 24小时 */ private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000; /** * */ private final static int KEY_SIZE = 2048; /** * 获取秘钥对对象 * * @return * @throws NoSuchAlgorithmException */ public static KeyPairVO getKeyPairVO() throws NoSuchAlgorithmException { // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); // 初始化密钥对生成器 keyPairGenerator.initialize(KEY_SIZE, new SecureRandom()); // 生成一个密钥对,保存在keyPair中 KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 得到公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); String publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded()); // 得到私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded()); Map<String, String> payLoadMap = new HashMap<>(); payLoadMap.put("userId", "2001"); payLoadMap.put("userName", "admin"); // 设置过期时间 Date expirDate = new Date(System.currentTimeMillis() + EXPIRE_TIME); String token = Jwts.builder() .claims(payLoadMap) .expiration(expirDate) .issuedAt(new Date()) .signWith(privateKey, Jwts.SIG.PS512) .compact(); KeyPairVO keyPairVO = new KeyPairVO(); keyPairVO.setPublicKey(publicKeyStr); keyPairVO.setPrivateKey(privateKeyStr); keyPairVO.setToken(token); return keyPairVO; } /** * 通过私钥获取token * * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static String getTokenByPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException { String privateKeyStr = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCdrPTee8ghBorY1ifMl/J9nNNIU6mObaguf/CZx4QK38hhb0YZLR/yd/3j5bdBp0zDDWLSUTG1idQanDZ5K75OISb7ApSiOqgrruw+klIzUohpnRPlTljfdHesGmyCVpEhHwevlhQC+Yaew/3960NAWU6sHViXkYE7zC+HwWVKQJ/nnG3cTXd87S5CT10BaVs3G3n4ahQCs4z7MWTiXMAtS0i25Cq2Tf3MC3meEK4amdVJB0TD6ESiU9HLo1uBGuIGxunCvaP3s+LTFmIy9+givp4Sbo1h3F69WISW53lJLEB9L+P7TZAL9sQkfOiggZNs3Kz4xUtta02o6kMGbaxDAgMBAAECggEAUBtfDOm2c5DvWdrzvW41NLxIW6alrkbn+zfk9Tv4Sc4H7/iolIHoiTeNNguvXxuwVCio3FGD/8dWi25x/n3K4cbWFxDoksNaTVdBj0inmouD4qR7RzTW0jBJ3JZQKqfwc/Nf5EVLRXegfWj10duE/1xgK/F84QR7s/W48C/BVkdSQs6E1Mo3UNjZQkeR367k5JgvQjXFC20DgYrFWnIQumLIFYal26+AxFDVqlfmoZo2lUYOgCLaabX1lNMRMMyo21tgNrJcpHOJfe5FVkRUFvW2Zi0JKLnieoPqUbI9j+1h8QjxzVRrqGutyTc7JrPH6tqd3MQtooKNeL9tdieXgQKBgQDYQk8tlN1wNCcaWrd90ZQQS2R0tn7iGUAntTVnkPykdEYzaWRrinsKLc5cwl/ri0t2BlECuZZ1c9WZwLVXfCHlxpVpP5vp9bDozY+Z5prygpXOe0OC7MspI21lqin7w6icUjoHPz540qV68BZV6tqaJzOjhcsbFqnT4Og8dCr0NQKBgQC6pqYiXDwlF7A51ONfcEng2kTUlea15psD+jf4HGu1hbHH+9MwNOLZI9LfI+utkt3+cxVx2LulgUf5OIC6y0s1wu3A1agoy2PuM1o5kBJUwS0DiR4hDFsOkh6BS7yDCmmMEYj4Pgp4TyiE9CWWDATYzlBGKcQaoub/C7EIQCs9lwKBgFsglfy/HhCJ6XBRicCa76luG4aS4CSmP0J8OWTK06r41BwV7Rrj37UKWEr+HS1EJSg2wSxEyAH2Lav8aG3VAPOyGoOfKjQMM9/lvv07D0/hdv7rMieZYIKVSyPr8IUGjaZRf+JN5CVFnjWPtdm+fR84JapiVpOzmRyPSU0wJmmBAoGALtJPKp9olwVyN4+n2fEZF0aprYpM7aSDjmPeVmcKveZjyn7pY1Zg8YeDBmbEYC5Pcdz8rCpqKAJeQ65g3HrSyxGzAoSWQmWDE+Xd5EK31nr/B7wFytSGowkUjeqpx1V9VJ2xdlRZ3AQ/bdqw8wrgzGI00OT5RJVIzQHpzuAJ+NECgYB9Z5h7wyNh+g+D5TD7uL1FO688HabPXnfvqIa3XwtRGnLrrotnqwy0K9Wq9fdTChHWhP+jIgpMxByYq433jZXHsO/Rry43Mj6cAAlkZNAQp8x2jjH8G9+IZq0wh1L5WBbYdjiJlKKNLC1XfiAN/8qdfEWXIQUGsr80vL33WsJQDg=="; // 将字符串Base64解码 byte[] decodeKey = java.util.Base64.getDecoder().decode(privateKeyStr); // 创建x509证书封装类 PKCS8EncodedKeySpec x509= new PKCS8EncodedKeySpec(decodeKey); // 指定RSA KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // 生成私钥 PrivateKey privateKey = keyFactory.generatePrivate(x509); Map<String, String> payLoadMap = new HashMap<>(); payLoadMap.put("userId", "1001"); payLoadMap.put("userName", "admin"); // 设置过期时间 Date expirDate = new Date(System.currentTimeMillis() + EXPIRE_TIME); String token = Jwts.builder() .claims(payLoadMap) .expiration(expirDate) .issuedAt(new Date()) .signWith(privateKey, Jwts.SIG.PS512) .compact(); return token; } }
package com.nancal.vo; public class KeyPairVO { private String publicKey; private String privateKey; private String token; public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }