javaopenid-connectjjwt

Key bytes can only be specified for HMAC signatures. Please specify a PublicKey or PrivateKey instance


I am trying to read a Json Web Token(JWT) generated from Google OpenID Connect's Id Token in order to get the claims and to verify using jjwt library. I have tried several ways to fix it with the code below.


 String publicKeyFromJsonFile = "-----BEGIN PUBLIC KEY-----xxxxxxx-----END PUBLIC KEY-----"

 Claims claims = Jwts.parser()
                .setSigningKey(publicKeyFromJsonFile)
                .parseClaimsJws(jwt).getBody();

 System.out.println(claims);


but I am getting this error:

java.lang.IllegalArgumentException: Key bytes can only be specified for HMAC signatures. Please specify a PublicKey or PrivateKey instance

Please what could be the right approach to follow ?


Solution

  • I think I have been able to fix the gotcha by parsing the publicKey as an RSAPublicKey. Below is the nitty-gritty of how i went about it.

     public static Optional<RSAPublicKey> getParsedPublicKey(){
           // public key content...excluding '---PUBLIC KEY---' and '---END PUBLIC KEY---'
            String PUB_KEY =System.getenv("PUBLIC_KEY") ; 
    
           // removes white spaces or char 20
            String PUBLIC_KEY = "";
              if (!PUB_KEY.isEmpty()) {
                PUBLIC_KEY = PUB_KEY.replace(" ", "");
            }
    
            try {
                byte[] decode = com.google.api.client.util.Base64.decodeBase64(PUBLIC_KEY);
                X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(decode);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(keySpecX509);
                return Optional.of(pubKey);
    
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                e.printStackTrace();
                System.out.println("Exception block | Public key parsing error ");
                return Optional.empty();
            }
    

    Hope it helps :).