一 生成公私钥
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Key publicKey = keyPair.getPublic();
Key privateKey = keyPair.getPrivate();
System.out.println( (new BASE64Encoder()).encodeBuffer(privateKey.getEncoded()));
System.out.println( (new BASE64Encoder()).encodeBuffer(publicKey.getEncoded()));
}
生成公私钥备用
二 颁发token项目使用私钥生成
通过BASE64编码转换为私钥
byte[] keyBytes;
keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec);
通过私钥生成数据 claim 为自定义数据
public static String ecode(String account, String subject, long expired, Map<String, Object> data, Key privateKey)
{
try
{
JSONObject HEADER = JSONObject.parseObject("{'type':'JWT','sign':'RS256'}");
Long nowMillis = System.currentTimeMillis();
Date createTime = new Date(nowMillis);
Date expiredTime = new Date(nowMillis + expired);
JwtBuilder builder = Jwts.builder();
builder.setHeader(HEADER).setId(UUID.randomUUID().toString()).setIssuer("颁发者").setAudience(account).setSubject(subject).setIssuedAt(createTime).setNotBefore(createTime).setExpiration(expiredTime).signWith(SIGNATURE_TYPE, privateKey);
builder.claim("data", data);
return builder.compact();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
三 通过公钥获取数据
通过BASE64编码转换为公钥
byte[] keyBytes = Base64.getDecoder().decode("publicKeyString");
X509EncodedKeySpec keySpec=new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
keyFactory.generatePublic(keySpec);
通过公钥解析数据
String jwtString = "";
// 使用公钥解析JWT内容
Claims claims = dcode(jwtString, keyFactory.generatePublic(keySpec));
System.out.println(claims.getExpiration());
System.out.println(new Date());
System.out.println(claims.getExpiration());
System.out.println(claims.get("data"));
System.out.println();
解析token decode
public Claims decode(String jwtToken,PublicKey publicKey){
return (Claims) Jwts.parser().setSigningKey(publicKey).parse(jwtToken).getBody();
}