i know there are multiple questions, but none have seem to adapt to what i need.
I need to validate a JWT token, i only have the PublicKey (which is fine as with that i can validate the sign of jwt.
Code is as follow.
First we have publicKey
private static final String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA88aLoh5l9W9UY3Hb+YGU\r\n"
+ "ZQBwVWuNTNpF5nm9uU+MqmB7EUmTYdD4Jk09zjBUutnggY10Jbjxdrv09HnHrqbj\r\n"
+ "+hyOyIXgSsVIK5bGZVHKLJzzZmWgn0QgcEXzR97J47MFeWkn0tEgDlP8LEMZE7ix\r\n"
+ "9WgoJHGGtUaQV5MM3U9S13zyRmaYekCVfLh2REHevb1aHgDReCLx92ZIdc9ldE9g\r\n"
+ "99v87E5zNKSv3AI8EVRt/Tpjfyuk7XTEqY6pz83tCfy1uch8NihhVjY8O2J3pilP\r\n"
+ "VW/L83GMJ5Shea0mE2Dq9Gh4lrVvAy+OHkarwGgdlYLwy1Dmof2SYCCq2SJyv5ZR\r\n"
+ "fwIDAQAB";
Then inside a method we got
JWTVerifier verifierToken = JWT.require(Algorithm.RSA256((RSAPublicKey) getPublicFederaKey(), null)).build();
DecodedJWT decodeJwt = verifierToken.verify(token);
Map<String, Object> claims = new HashMap<String, Object>();
String codiceFiscale = decodeJwt.getClaim("CODICEFISCALE").asString();
System.err.println("CODICE FISCALE: "+codiceFiscale);
if (decodeJwt.getExpiresAt().before(java.util.Calendar.getInstance().getTime())) {
throw new RuntimeException("Expired token!");
}
If you see on verifiedToken it makes reference to getPublicFederaKey();
private PublicKey getPublicFederaKey() throws CustomException {
PublicKey key = null;
try{
String keyTrimmed = publicKey.trim().replace("\n", "").replace("\r", "");
System.err.println(keyTrimmed);
int stringLength = keyTrimmed.length(); //392
String hexString = Hex.encodeHexString(publicKey.getBytes("UTF-8"));
byte[] hexedPublicKey = DatatypeConverter.parseHexBinary(hexString);
X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(hexedPublicKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
key = kf.generatePublic(keySpecX509);
} catch (Exception e) {
throw new CustomException(e.getMessage());
}
return key;
}
I saw an answer here and tried the hexParsing directly with the String but gave me error of illegal character present for hex or sth like that (i think its because it has a-f characters) so i guessed ok, its because it is waiting for a hex instead of raw String.
Then before i tried with Base64 something similar to this
rsa = Cipher.getInstance("RSA");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pkey.getBytes());
PublicKey pk = keyFactory.generatePublic(publicKeySpec);
Then at the end as you can see i am triying to replicate "Duncan Jones" response to no avail.
java.security.InvalidKeyException: invalid key format on generating RSA public key
In any case what i need is the String publicKey (i cut the ----BEGIN---- -----END----), to be transformed to java.security.PublicKey to then be cast to java.security.interfaces.RSAPublicKey
Thank you very much in advance.