Maven 依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
加密解密示范
package com.sixmonth.micro.serv.page.common.jwt;
import java.util.Date;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import com.alibaba.fastjson.JSONObject;
import com.sixmonth.micro.serv.common.util.UUIDUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
public class JWTUtils {
static String SECRETKEY = "KJHUhjjJYgYUllVbXhKDHXhkSyHjlNiVkYzWTBac1Yxkjhuad";
public static SecretKey generalKey(String stringKey) {
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
public static String createJWT(String uuid, String subject, long expirationDate) throws Exception {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
SecretKey key = generalKey(SECRETKEY);
JwtBuilder builder = Jwts.builder().setIssuer("").setId(uuid).setIssuedAt(now).setSubject(subject)
.signWith(signatureAlgorithm, key);
if (expirationDate >= 0) {
long expMillis = nowMillis + expirationDate*1000;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
public static Claims parseJWT(String jwt) throws ExpiredJwtException, UnsupportedJwtException,
MalformedJwtException, SignatureException, IllegalArgumentException {
SecretKey key = generalKey(SECRETKEY);
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
return claims;
}
public static void main(String[] args) {
try {
JSONObject subject = new JSONObject(true);
subject.put("tem", "哈哈哈");
subject.put("userName", "sixmonth");
String token = createJWT(UUIDUtils.getUUID(), subject.toJSONString(), 10);
Claims claims = parseJWT(token);
System.out.println("解析jwt:"+claims.getSubject());
JSONObject tem = JSONObject.parseObject(claims.getSubject());
System.out.println("获取json对象内容:"+tem.getString("userName"));
System.out.println(claims.getExpiration()+"///"+claims.getExpiration().getTime());
} catch (Exception e) {
e.printStackTrace();
}
}
}