使用JWT创建解析令牌及RSA非对称加密详解

  @Test

  public void test() throws InvalidKeySpecException, NoSuchAlgorithmException {

  RSAPublicKey publicKey = RsaAlgorithmFactory.getPublicKey(publicKey1);

  //Security.addProvider(new BouncyCastleProvider());

  RSAPrivateKey privateKey = RsaAlgorithmFactory.getPrivateKey(privateKey1);

  System.out.println(privateKey.getFormat());

  Map headers = new HashMap<>();

  headers.put("ip", "123.12.123.25.12");

  JWTCreator.Builder builder = JWT.create()

  //JWT唯一标识 jti

  .withJWTId(UUID.randomUUID().toString())

  .withHeader(headers)

  .withClaim("username", "田润叶")

  .withClaim("password", "不喜欢")

  //发布者 iss

  .withIssuer("顾养民")

  //发布时间 iat

  .withIssuedAt(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()))

  //受众|收件人 aud

  .withAudience("田海民", "孙玉婷")

  //指定JWT在指定时间之前不得接受处理 nbf

  .withNotBefore(Date.from(LocalDateTime.now().plusMinutes(-1).atZone(ZoneId.systemDefault()).toInstant()))

  //JWT的主题 sub

  .withSubject("令牌")

  //JWT的密钥ID(实际未用到),用于指定签名验证的密钥 kid com.auth0.jwt.algorithms.RSAAlgorithm.verify

  .withKeyId("sd")

  //JWT过期时间 exp

  .withExpiresAt(LocalDateTime.now().plusMinutes(5).atZone(ZoneId.systemDefault()).toInstant());

  String jwtToken = JwtFactory.createJwtToken(builder, Algorithm.RSA256(publicKey, privateKey));

  Assert.assertNotNull(jwtToken);

  DecodedJWT jwt = JwtFactory.verifyJwtToken(jwtToken, Algorithm.RSA256(publicKey, privateKey));

  Assert.assertEquals(jwt.getClaim("username").asString(), "田润叶");

  Assert.assertEquals(jwt.getClaim("password").asString(), "不喜欢");

  Assert.assertEquals(jwt.getHeaderClaim("ip").asString(), "123.12.123.25.12");

  Assert.assertEquals(jwt.getIssuer(), "顾养民");

  Assert.assertEquals(jwt.getAudience().get(0), "田海民");

  Assert.assertEquals(jwt.getAudience().get(1), "孙玉婷");

  }