Confirmation Key for jose4j JwtConsumer

I use jose4j to test and process JWT. The JWT is as follows, and it is being tested on the JWT main page. enter image description here

However, I cannot do the same with jose4j java library. An exception complains about the verification key that I installed. But there are many types of keys defined in the library, and I tried them, but no luck. The code is as follows:

import java.util.Map; import org.jose4j.jwt.JwtClaims; import org.jose4j.jwt.consumer.InvalidJwtException; import org.jose4j.jwt.consumer.JwtConsumer; import org.jose4j.jwt.consumer.JwtConsumerBuilder; import org.jose4j.keys.HmacKey; public class YGJWT { public static void main(String args[]) throws InvalidJwtException { String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"; String secret = "secret"; JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(new HmacKey(secret.getBytes())) //what kind of key do i need to use it here? .build(); JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); Map<String, Object> claimsMap = jwtClaims.getClaimsMap(); claimsMap.forEach((String key, Object val) -> { System.out.println(key + ": " + val.toString()); }); } } 

Any help is appreciated.

+4
source share
1 answer

I assume that you are getting an exception something like this? org.jose4j.lang.InvalidKeyException: A key of the same size as the hash output (ie 256 bits for HS256) or larger MUST be used with the HMAC SHA algorithms but this key is only 48 bits

HmacKey is the correct type for HS256 , but the key is technically too short according to the second paragraph http://tools.ietf.org/html/rfc7518#section-3.2 which has the same text as the exception message.

You can get around this by building a JwtConsumer with .setRelaxVerificationKeyValidation() , which allows you to use shorter keys. It looks like this (adding only one line to the snippet from your example):

  JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(new HmacKey(secret.getBytes())) .setRelaxVerificationKeyValidation() // allow shorter HMAC keys when used w/ HSxxx algs .build(); 

In general, although I would try to avoid using a short password, such as a key, such as a "secret", and suggest using a stronger key when possible.

+5
source

All Articles