JWT 加密工具类
Posted 胡庚申
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JWT 加密工具类相关的知识,希望对你有一定的参考价值。
package com.util.jwt;
import com.google.common.collect.Maps;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;
/**
* @author: HuGoldWater
* @description:
*/
public class JwtUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(JwtUtil.class);
/**
* 秘钥
* - 默认:123456
*/
private String secret = "123456";
/**
* 有效期,单位秒
* - 默认2周
*/
private Long expirationTimeInSecond = 1626021786L;
/**
* 从token中获取claim
*
* @param token token
* @return claim
*/
public Claims getClaimsFromToken(String token) {
try {
return Jwts.parser()
.setSigningKey(this.secret.getBytes())
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
LOGGER.error("token解析错误", e);
throw new IllegalArgumentException("Token invalided.");
}
}
/**
* 获取token的过期时间
*
* @param token token
* @return 过期时间
*/
public Date getExpirationDateFromToken(String token) {
return getClaimsFromToken(token)
.getExpiration();
}
/**
* 判断token是否过期
*
* @param token token
* @return 已过期返回true,未过期返回false
*/
private Boolean isTokenExpired(String token) {
Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
/**
* 计算token的过期时间
*
* @return 过期时间
*/
private Date getExpirationTime() {
return new Date(System.currentTimeMillis() + this.expirationTimeInSecond * 1000);
}
/**
* 为指定用户生成token
*
* @param claims 用户信息
* @return token
*/
public String generateToken(Map<String, Object> claims) {
Date createdTime = new Date();
Date expirationTime = this.getExpirationTime();
byte[] keyBytes = secret.getBytes();
SecretKey key = Keys.hmacShaKeyFor(keyBytes);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(createdTime)
.setExpiration(expirationTime)
// 你也可以改用你喜欢的算法
// 支持的算法详见:https://github.com/jwtk/jjwt#features
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
/**
* 判断token是否非法
*
* @param token token
* @return 未过期返回true,否则返回false
*/
public Boolean validateToken(String token) {
return !isTokenExpired(token);
}
public static void main(String[] args) {
// 1. 初始化
JwtUtil jwtOperator = new JwtUtil();
jwtOperator.expirationTimeInSecond = 1209600L;
jwtOperator.secret = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt";
// 2.设置用户信息
Map<String, Object> objectObjectHashMap = Maps.newHashMap();
objectObjectHashMap.put("id", "1");
// 测试1: 生成token
String token = jwtOperator.generateToken(objectObjectHashMap);
// 会生成类似该字符串的内容: eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk4MTcsImV4cCI6MTU2Njc5OTQxN30.27_QgdtTg4SUgxidW6ALHFsZPgMtjCQ4ZYTRmZroKCQ
System.out.println(token);
// 将我改成上面生成的token!!!
String someToken = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE2MjUxNTc4NjgsImV4cCI6MTYyNjM2NzQ2OH0.wNeIceDm7IombYsa13Cq4EOdz_RNq1GcGOm8UMlTWHk";
// 测试2: 如果能token合法且未过期,返回true
Boolean validateToken = jwtOperator.validateToken(someToken);
System.out.println(validateToken);
// 测试3: 获取用户信息
Claims claims = jwtOperator.getClaimsFromToken(someToken);
System.out.println(claims);
// 将我改成你生成的token的第一段(以.为边界)
String encodedHeader = "eyJhbGciOiJIUzI1NiJ9";
// 测试4: 解密Header
byte[] header = Base64.decodeBase64(encodedHeader.getBytes());
System.out.println(new String(header));
// 将我改成你生成的token的第二段(以.为边界)
String encodedPayload = "eyJpZCI6IjEiLCJpYXQiOjE2MjUxNTc4NjgsImV4cCI6MTYyNjM2NzQ2OH0";
// 测试5: 解密Payload
byte[] payload = Base64.decodeBase64(encodedPayload.getBytes());
System.out.println(new String(payload));
// 测试6: 这是一个被篡改的token,因此会报异常,说明JWT是安全的
jwtOperator.validateToken("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk3MzIsImV4cCI6MTU2Njc5OTMzMn0.nDv25ex7XuTlmXgNzGX46LqMZItVFyNHQpmL9UQf-aUx");
}
}
eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE2MjUxNTc5MDgsImV4cCI6MTYyNjM2NzUwOH0.bR8aQKFed1pvf7yLCuJIsi6i7tuAm5Aoyy4HCePTOPo
true
{id=1, iat=1625157868, exp=1626367468}
{"alg":"HS256"}
{"id":"1","iat":1625157868,"exp":1626367468}
Exception in thread "main" io.jsonwebtoken.security.SignatureException: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:383)
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:513)
at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:573)
at com.util.jwt.JwtUtil.getClaimsFromToken(JwtUtil.java:43)
at com.util.jwt.JwtUtil.getExpirationDateFromToken(JwtUtil.java:58)
at com.util.jwt.JwtUtil.isTokenExpired(JwtUtil.java:69)
at com.util.jwt.JwtUtil.validateToken(JwtUtil.java:113)
at com.util.jwt.JwtUtil.main(JwtUtil.java:154)
来源:
https://www.itmuch.com/other/jwt-util/
以上是关于JWT 加密工具类的主要内容,如果未能解决你的问题,请参考以下文章