From Speedy Butterfly, 5 Years ago, written in Plain Text.
This paste is a reply to Re: Untitled from Sexy Flamingo - view diff
Embed
  1. JWTHelper:
  2. public String generateToken(String payload, Key key) {
  3.         return builderFactory
  4.                 .createJwtBuilder()
  5.                 .setPayload(payload)
  6.                 .setHeaderParam("typ", "JWT")
  7.                 .setHeaderParam("alg", signatureAlgorithm.getValue())
  8.                 .signWith(key, signatureAlgorithm)
  9.                 .compact();
  10.     }
  11.  
  12. Caller statement: OAuthService
  13. String strPrivateKey = encryptionUtilities.aesDecrypt(toolConfiguration.getPlatformPrivateKey(),
  14.                     aesSecretKey);
  15. PrivateKey privateKey = encryptionUtilities.string2PrivateKey(strPrivateKey);
  16.             long startTime = System.currentTimeMillis();
  17.             String accessToken = jwtHelper.generateToken(payload, privateKey, tokenExpirationInMilliSeconds);
  18.             LOGGER.info("Time spend in getOauthToken jwtHelper.generateToken {}", System.currentTimeMillis() - startTime);
  19.  
  20.  
  21. EncryptionUtil.java
  22. public PrivateKey string2PrivateKey(String privateKeyString) {
  23.         long startTime = System.currentTimeMillis();
  24.         try {
  25.             KeyFactory kf = KeyFactory.getInstance(ServiceConstants.RSA);
  26.             PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
  27.             PrivateKey privateKey = kf.generatePrivate(keySpecPKCS8);
  28.             LOGGER.info("Time spend in string2PrivateKey {}", System.currentTimeMillis() - startTime);
  29.             return privateKey;
  30.         } catch (IllegalArgumentException | InvalidKeySpecException | NoSuchAlgorithmException e) {
  31.             LOGGER.error(e.getMessage(), e);
  32.             return null;
  33.         }
  34.     }
  35.  
  36.  
  37. -----------------------
  38.  
  39. public Claims readPayloadFromToken(String jwtToken, Key publickey) {
  40.         Claims claims = null;
  41.         try {
  42.             claims = parserFactory
  43.                     .createJwtParser()
  44.                     .setSigningKey(publickey)
  45.                     .parseClaimsJws(jwtToken)
  46.                     .getBody();
  47.         } catch (UnsupportedJwtException | MalformedJwtException | ExpiredJwtException | IllegalArgumentException ex) {
  48.             LOGGER.error("Error in JWT/JWS validation", ex);
  49.         }
  50.         return claims;
  51.     }
  52.  
  53.  
  54. ----------------------------
  55. Gradle Dependency:
  56. /* JWT Dependency */
  57.     compile "io.jsonwebtoken:jjwt-api:0.10.5"