一、使用Hutool生成token
// jwt的密钥
String jwtKey = "test";
Map<String, Object> payload = new HashMap<>();
payload.put(RegisteredPayload.SUBJECT, "demo");
payload.put(RegisteredPayload.ISSUER, "test");
payload.put(RegisteredPayload.JWT_ID, "1607326287763841025");
payload.put(RegisteredPayload.ISSUED_AT, 1703832885680L);
String token = JWTUtil.createToken(payload, jwtKey.getBytes());
System.out.println("生成的token是" + token);
二、使用Hutool校验token
JWT jwt = JWTUtil.parseToken(token);
jwt.setKey(jwtKey.getBytes(StandardCharsets.UTF_8));
String[] splitString = token.split("\\.");
String base64EncodedHeader = splitString[0];
String base64EncodedBody = splitString[1];
String base64EncodedSignature = splitString[2];
String signature = jwt.getSigner().sign(base64EncodedHeader, base64EncodedBody);
if (!base64EncodedSignature.equals(signature)) {
System.out.println("JWT校验不通过");
} else {
System.out.println("JWT校验通过");
}
三、不使用Hutool校验token
JWT jwt = JWTUtil.parseToken(token);
jwt.setKey(jwtKey.getBytes(StandardCharsets.UTF_8));
String[] splitString = token.split("\\.");
String base64EncodedHeader = splitString[0];
String base64EncodedBody = splitString[1];
String base64EncodedSignature = splitString[2];
Mac hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(jwtKey.getBytes(), "HmacSHA256");
hmac.init(secretKey);
// 创建待签名的数据
String data = base64EncodedHeader + "." + base64EncodedBody;
// 执行签名
byte[] rawHmac = hmac.doFinal(data.getBytes());
// 对签名进行Base64url编码
String signature = Base64.getUrlEncoder().withoutPadding().encodeToString(rawHmac);
if (!base64EncodedSignature.equals(signature)) {
System.out.println("JWT校验不通过");
} else {
System.out.println("JWT校验通过");
}