用到了这个包 compile 'io.jsonwebtoken:jjwt:0.9.1'
可以到这里去生成一堆密钥 http://web.chacuo.net/netrsakeypair
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static java.time.ZoneOffset.UTC;
public class TokenHelper {
static String publicKey = "QgkAQIDAQAB";
static String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8";
public static Claims parseJwt(String jsonWebToken) {
if (jsonWebToken == null || !jsonWebToken.startsWith("Bearer ")) {
throw new RuntimeException("token is not valid");
}
try{
return Jwts.parser().setSigningKey(getPublicKey())
.parseClaimsJws(jsonWebToken.substring(7)).getBody();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static String createToken () {
Date expiration = Date.from(LocalDateTime.now(UTC).plusDays(7).toInstant(UTC));
Map<String, Object> claims = new HashMap<>();
claims.put("companyId", "1");
claims.put("userId", "2");
// 这里要注意 用到了setClaims 方法 setSubject 和 setExpiration 就不好用了
// 可以把这两个值也放到claims里 或者不用setClaims 用 setClaim 一个一个放
return "Bearer " + Jwts.builder()
.setSubject("subject")
.setExpiration(expiration)
.setClaims(claims)
.setIssuer("test1")
.signWith(SignatureAlgorithm.RS256, getPrivateKey())
.compact();
}
public static PublicKey getPublicKey(){
try{
byte[] keyBytes = Base64.getDecoder().decode(publicKey.getBytes());
X509EncodedKeySpec keySpec=new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory=KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static PrivateKey getPrivateKey() {
try {
byte[] keyBytes;
keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
网友评论