Reputation: 133
I'm validating a JWT token coming from Azure and use JJWT. I retrieve the modulus and exponent from the keys document related to my tid, which are fields n and e respectively. The validation fails with error: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
This is the code. Does anybody see the mistake i made? The code runs fine all up to the validation where it throws the signature mismatch error.
private Claims extractClaimsForRsaSignedJwts(String token, String mod, String exp) {
Claims claims = null;
byte[] modBytes = Base64.decodeBase64(mod.getBytes());
byte[] expBytes = Base64.decodeBase64(exp.getBytes());
BigInteger modulus = new BigInteger(modBytes);
BigInteger exponent = new BigInteger(expBytes);
RSAPublicKeySpec pubKeySpecification = new RSAPublicKeySpec(modulus, exponent);
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
RSAPublicKey rsaPub = null;
try {
rsaPub = (RSAPublicKey) keyFac.generatePublic(pubKeySpecification);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JwtParser jwtParser = Jwts.parser().setSigningKey(rsaPub);
try {
claims = jwtParser.parseClaimsJws(token).getBody();
} catch (Exception e) {
// JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
System.out.println("The RSA JWT key validation failed: " + e.getMessage());
}
return claims;
}
Thanks!
Jan
Upvotes: 2
Views: 460
Reputation: 133
I found the problem! the BigInteger should be constructed with signum 1 for positve numbers! Now the code works like a charm for AzureAD JWT signature validation.
BigInteger modulus = new BigInteger(1, modBytes);
BigInteger exponent = new BigInteger(1, expBytes);
This is the final code: Screen Shot Of Code With Correction
Upvotes: 3