package com.example.TestProject.reviewToken;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author ZhuRuiLin
* @description TODO
* @date 2022/9/22 22:04
**/
@Slf4j
public class TestJavaJwtToken {
private String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCV8tpvKfqlzUIvkyD0Zi/8nQHFZx2xxpfal17iHNTYtIZil2YgkANYrRHEnF1wKFbKRZH1zHQsLLkEojt3nz0jyLmZjv94pVmcoXGIsbOkYHp1WaO6HegRdhdqfDZiTlCs4lPqQgGHh4yBdBgb8ZH8DI5Xp/koetVi0LpwdPxJrQIDAQAB";
private String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJXy2m8p+qXNQi+TIPRmL/ydAcVnHbHGl9qXXuIc1Ni0hmKXZiCQA1itEcScXXAoVspFkfXMdCwsuQSiO3efPSPIuZmO/3ilWZyhcYixs6RgenVZo7od6BF2F2p8NmJOUKziU+pCAYeHjIF0GBvxkfwMjlen+Sh61WLQunB0/EmtAgMBAAECgYAXWoZ4r8IQ1qILRM/qIIwyvMVM2F2AlZyK9+5YKwNfaOZRLqFCSwuqYPIWe//1euLhh+pOrPQe+Swrs5StcciUsCPYTA9uoUydUC2A5rXbYAdIihKQYI+JbrUcTWFF7wIwUbGzp10Uog3HPJlW+qciNC7td01jtFPYURqLpUI5hQJBAMRwzL6Nph1IiQdWyhX1Bp03GyprW/dnnUe89yg/83PBzHtAgByGKHpkzAht/P9Oi0NkVEJJlJywMtJmm0R0m8cCQQDDaXgrOAs++ZxSoPM4+3w7iMMDbS09WkGC/MxnHCWPfPXsx/zkh3xEZdoHc8GYfw+wobucMKsf8Y4Sq+XZIGbrAkEAq+8StUHjf8Pp85t5+yff5yDBTSp0byGoXo69QORgYBPitono145wxVeN4V7rTkZfy9d3jCE8yrvJb7BQ++SYJwJBAJojpK16rKxFGoC3AoPNI4aWbzVRtiCyBAD9xYID2sDfUeEvMxVUpboSGTRNo8TVXRv3x1QBs8ojsOybeVeWzncCQQCgcCPLr8l2mIxGwC182+8+4IWt++jLqd7C36yhNGV2XRT5C7X5a+5osG5GBdYFhLRZkHElA+bkV9LXcP5FXwYY";
public String createToken(TestUserInfo userInfo) {
LocalDateTime expire = LocalDateTime.now().plusHours(3);
Date expireDate = Date.from(expire.atZone(ZoneId.systemDefault()).toInstant());
Map<String, Object> headers = new HashMap<>();
headers.put("alg", "RSA");
headers.put("type", "JWT");
String userInfoStr = JSONObject.toJSONString(userInfo);
Algorithm rsa = Algorithm.RSA256(getPublicKey(PUBLIC_KEY), getPrivateKey(PRIVATE_KEY));
String token = JWT.create().withExpiresAt(expireDate).withHeader(headers).withClaim("user", userInfoStr).sign(rsa);
return token;
}
/**
* 从token中解析出用户信息
*
* @param token
* @return
*/
public TestUserInfo getInfoFromToken(String token) {
Algorithm rsa = Algorithm.RSA256(getPublicKey(PUBLIC_KEY), getPrivateKey(PRIVATE_KEY));
JWTVerifier verifier = JWT.require(rsa).build();
DecodedJWT decodedJWT = verifier.verify(token);
String userInfosTR = decodedJWT.getClaim("user").asString();
return JSONObject.parseObject(userInfosTR, TestUserInfo.class);
}
/**
* 打印出一堆公钥和私钥,将打印内容复制出来备用, 为了持久化存储
*/
@SneakyThrows
public void printKey() {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair keyPair = generator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
log.info("publicKey={}", publicKeyStr);
log.info("privateKey={}", privateKeyString);
}
/**
* 根据字符串得到对应公钥对象
*
* @param keyStr
* @return
*/
@SneakyThrows
public RSAPublicKey getPublicKey(String keyStr) {
byte[] bytes = Base64.getDecoder().decode(keyStr);
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
RSAPublicKey key = (RSAPublicKey) factory.generatePublic(spec);
return key;
}
/**
* 根据字符串得到对应私钥对象
*
* @param keyStr
* @return
*/
@SneakyThrows
public RSAPrivateKey getPrivateKey(String keyStr) {
byte[] bytes = Base64.getDecoder().decode(keyStr);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
RSAPrivateKey key = (RSAPrivateKey) factory.generatePrivate(spec);
return key;
}
}
使用RSA算法生成token和解析token
最新推荐文章于 2024-07-15 16:44:14 发布