Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify Signature using JWT ( java-jwt)

Tags:

java

jwt

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.

like image 383
user9607509 Avatar asked Jan 28 '23 08:01

user9607509


1 Answers

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;
    }
like image 171
Sai Prannav Krishna Avatar answered Jan 30 '23 21:01

Sai Prannav Krishna