Validate JWT signature with public key ECDSA (Error Decoding Signature bytes)

Asked

Viewed 208 times

0

Good, I need help validating a json web token signed with ES256 algorithm using a public key from a .pem. file I am using a lib from Java JWT and Bouncy Castle. I have this code:

        String stringPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
            "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZJJLaGLY+56III7D3+aMmRzv8+Bt\n" +
            "FV4Gz5HfZjQlIe3ytv/PCzSX+orEUz3Dbc1xT9cgRJfwpp2+JAIoyAuwLg==\n" +
            "-----END PUBLIC KEY-----";
    String accessTokenString = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJtc2kiOiI5NzE1NTA5ODc2NTUiLCJmZWEiOiJzaWdudXAtZGF0YSIsImlzcyI6IkNEUCIsImV4cCI6MTU1NDU2NjMzNiwiaWF0IjoxNTU0MzkzNTM2LCJzaWQiOiIwNDI0MDMwMDg5NzI4MTg3QG5haS5lcGMubW5jMTMwLm1jYzMxMC4zZ3BwbmV0d29yay5vcmcifQ.RwxoGmFd1_dQPeGN-0gnWIW79xXvGHoyJKBbCKajgO75UooceS6tskxwqViEuP1gZD66UE8Bd2L0FaeI2aS_IA";

    PublicKey publicKey = decodePublicKey(stringPublicKey);

    Jws<Claims> claimsJws = Jwts.parser() //
            .setSigningKey(publicKey) //
            .parseClaimsJws(accessTokenString) //
            ;

public static PublicKey decodePublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {

    String stringPublicKey = key;
    stringPublicKey = stringPublicKey.replace("-----BEGIN PUBLIC KEY-----\n", "");
    stringPublicKey = stringPublicKey.replace("-----END PUBLIC KEY-----", "");
    stringPublicKey= stringPublicKey.replaceAll("\r\n", "");
    stringPublicKey= stringPublicKey.replaceAll("\n", "");
    byte[] encoded = Base64.decodeBase64(stringPublicKey);

    X509EncodedKeySpec spec = new X509EncodedKeySpec(encoded);

    KeyFactory kf = KeyFactory.getInstance("ECDSA","BC");

    return kf.generatePublic(spec);
}

At the moment of validating the signature I have the following exception: Signatureexception with "error Decoding Signature bytes".

io.jsonwebtoken.SignatureException: Unable to verify Elliptic Curve signature using configured ECPublicKey. error decoding signature bytes. at io.jsonwebtoken.impl.crypto.EllipticCurveSignatureValidator.isValid(EllipticCurveSignatureValidator.java:46) ~[hotdeploy_9207100474820885290.jar:0.6.0] at io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator.isValid(DefaultJwtSignatureValidator.java:47) ~[hotdeploy_9207100474820885290.jar:0.6.0] at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:339) ~[hotdeploy_9207100474820885290.jar:0.6.0] at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:458) ~[hotdeploy_9207100474820885290.jar:0.6.0] at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:518) ~[hotdeploy_9207100474820885290.jar:0.6.0]

Thanks for any help.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.