0

I am trying to decode and verify JWT token in my service using the following code:

String  jwtSecret= "my_key";
Claims claims = Jwts.parser()
        .setSigningKey(jwtSecret)
        .parseClaimsJws(jwt).getBody();
return claims;

The above code does not work and throws the following exception:

java.lang.IllegalArgumentException: Key bytes cannot be specified for RSA signatures.  Please specify a PublicKey or PrivateKey instance.

I have tried creating Public key also but it didn't work. Can anyone state what I am missing?

tmarwen
  • 15,750
  • 5
  • 43
  • 62
Sonali
  • 447
  • 1
  • 4
  • 19

2 Answers2

0

Looks like you are JJWT for trying to decode the JWT. Where are you getting the public key from?

Instead of passing in the public key as a string, you should build a PublicKey first, then pass that in. If you have access to the exponent and modulus of the key:

BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(key.getN()));

BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(key.getE()));

RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(publicSpec);

If you don't, this post explains how you can build it from a string, but you have ensure that the string is formatted correctly.

In case you are interested, here is a more detailed post that I wrote on how to validate and parse a JWT signed by an Authorization server using JJWT.

sgonzalez
  • 741
  • 6
  • 20
0

Key I was using was not correct. I came to know when I tried generating the token with the key I was using and decoded with my same above code and same key , it worked. So I checked with the team which was handling the JWT token generation I found key was different.

Sonali
  • 447
  • 1
  • 4
  • 19