I have to verify signature using java-jwt library, I have token and public key and public key starts from ssh-rsa AA............... And I have to use RSA256 Algorithm, When I checked github I found following
Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
But my public key in form of String, and I dont have private key.. Please suggest me how to verify signature.
When using asymmetric key encryption we need private key to create signature and public key to verify. Coming to your question
1. Private is not present
Its fine, you need not have private key to verify a signature . Regarding the lib you are using , its variable args . It means you can just pass one depending on signing/verifying . Below is the java method where only public key is used.
public boolean verifyToken(String token,RSAPublicKey publicKey){
try {
Algorithm algorithm = Algorithm.RSA256(publicKey, null);
JWTVerifier verifier = JWT.require(algorithm)
//more validations if needed
.build();
verifier.verify(token);
return true;
} catch (Exception e){
System.out.println("Exception in verifying "+e.toString());
return false;
}
}
2. Public key is in string format, not in java PublicKey format.
You need a mechanism to convert your public key string file to Java PublicKey format. Below is one method I can suggest.
public static RSAPublicKey getPublicKeyFromString(String key) throws
IOException, GeneralSecurityException {
String publicKeyPEM = key;
/**replace headers and footers of cert, if RSA PUBLIC KEY in your case, change accordingly*/
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.decodeBase64(publicKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
return pubKey;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With