pom.xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
public class JwtUtil {
/**
* 匹配jwt
* @param token
* @param base64Security
* @return
*/
public static Claims parseJwt(String token,String base64Security){
try {
Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
.parseClaimsJws(token).getBody();
return claims;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 创建jwt
* @param name 用户名
* @param base64Security 密钥
* @param seconds 过期时间
* @return
*/
public static String createJwt(String name,String base64Security,Long seconds){
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Long time = System.currentTimeMillis();
Date date = new Date(time+seconds*1000);
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
Key signKey = new SecretKeySpec(apiKeySecretBytes,signatureAlgorithm.getJcaName());
JwtBuilder jwtBuilder = Jwts.builder().setHeaderParam("typ","JWT")
.claim("user_name",name)
.signWith(signatureAlgorithm,signKey)
.setExpiration(date);
return jwtBuilder.compact();
}
public static void main(String[] args) {
System.out.println(createJwt("aa","emhhbmdzYW4=",1800L));
System.out.println(parseJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX25hbWUiOiJhYSIsImV4cCI6MTU5OTAxNjY1Nn0.XrK1TMWI4jfr0BnShdPDgyIAObigtws4b_NXrJJpbsA","emhhbmdzYW4="));
}
}