Ani512
Ani512

Reputation: 1

How to check the validity of a signature using JWKs and the base string the signature was created against

I have a signature (String) that has been generated from a url and some query params. I wanted to know how to validate this signature. I have another url that provides me the public JWKs. I am using the com.auth0.jwk package - https://github.com/auth0/jwks-rsa-java to get the JWKs and using the java.security.Signature to validate the signature value. Using Java 16.

Code that I tried -

private static boolean validateSignature(String cleanedUrl, String sig) throws Exception {
        List<Jwk> jwks = new UrlJwkProvider(new URL("INSERT_THE_SIGNING_KEY_URL")).getAll();

        boolean verified = false;

        for (Jwk jwk : jwks) {
            ECPublicKey ecPublicKey = (ECPublicKey) jwk.getPublicKey();

            Signature verifier = Signature.getInstance("SHA256withECDSA");
            verifier.initVerify(ecPublicKey);
            verifier.update(cleanedUrl.getBytes(StandardCharsets.UTF_8));

            // example param here - 53zV4lP78kUcsForjdbkNDvOtnxoFR173V0UC6uPhF3ljESJa7lotg9n+7XqnGx20EEPiKpunqo7uuX3f30qww
            sig = sig.replace("-", "+").replace("_", "/");
            try {

                // Fails all the time because the signature is too short
                verified = verifier.verify(Base64.getDecoder().decode(sig));
            } catch (Exception e) {

                // java.security.SignatureException: Invalid encoding for signature
                // java.io.EOFException: not enough content
                System.out.println("Error while verifying the signature");
            }

            if (verified) {
                break;
            }
        }

        return verified;
    }

I am replacing the '-' with '+' and '_' with '/' according to client documentation. I cannot provide the url or the signing keys.

Any thoughts on what am I doing wrong?

Upvotes: 0

Views: 148

Answers (0)

Related Questions