代码
package com.zsl.util;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtil {
private static String key = "l0UsM01W/W3s+o4o/j+DIdiK1uo+4CJ46blUXwg9Fis=";
private static Long offset = 60 * 1000L;
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
map.put("username", "zsl");
map.put("password", "xxxxx");
String jwy = jwt(map);
System.out.println(jwy);
System.out.println(parse("eyJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6Ijk5MDEyNiIsInVzZXJuYW1lIjoienNsIiwiaWF0IjoxNjM2MDM2NjM5LCJleHAiOjE2MzYwMzY2OTl9.ZgjVpCxdWeOcQ5tBHp_n3sH84GpA6MFeP2-GFgQ65Cw"));
}
public static Claims parse(String jwt) {
Jws<Claims> parse = Jwts.parserBuilder()
.setSigningKey(key)
.build().parseClaimsJws(jwt);
return parse.getBody();
}
public static String jwt(Map map) {
Date currentDate = new Date();
Date invalidDate = new Date(currentDate.getTime() + offset);
SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(key));
String compact = Jwts.builder()
.setClaims(map)
.setIssuedAt(currentDate)
.setExpiration(invalidDate)
.signWith(secretKey)
.compact();
return compact;
}
public static String generateSecretKey() {
SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String encode = Encoders.BASE64.encode(secretKey.getEncoded());
return encode;
}
}