/** * 使用jwt创建token * @param id 存储id * @param subject 存储内容 * @param ttlMillis 超时时间 * @return * @throws Exception */
public String createJWT(String id, String subject, long ttlMillis) throws Exception { //从枚举类获取HS256加密我们的key SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //当前时间 long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); SecretKey key = generalKey(); JwtBuilder builder = Jwts.builder() .setId(id) .setIssuedAt(now) .setSubject(subject) .signWith(signatureAlgorithm, key); if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); }
/** * 由字符串生成加密key * @return */ public SecretKey generalKey(){ //加密串 String stringKey = demo+7786df7fc3a34e26a61c034d5ec8245d;
byte[] encodedKey = Base64.decodeBase64(stringKey.getBytes()); SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); return key; }
/** * 解密jwt * @param jwt * @return * @throws Exception */ public Claims parseJWT(String jwt) { SecretKey key = generalKey(); Claims claims = Jwts.parser() .setSigningKey(key) .parseClaimsJws(jwt).getBody(); return claims; }
解密完毕后使用
String json = claims.getSubject();即可获取到加密存入的subject的值
关于jwt生成token与解码获取值的代码展示到这,如有错误请指出