Search code examples
javaauth0ecdsa

Auth0: The Token's Signature couldn't be generated when signing using the Algorithm: SHA256withECDSA


everyone! I'm trying to sign a JWT info and JWT data with ES256 using the auth0 ECDSA256 algorithm.

ECPublicKey publicKeyRs = getPublicKey();
    ECPrivateKey privateKeyRs = getPrivateKey();
    Algorithm algorithmRs = Algorithm.ECDSA256(publicKeyRs, privateKeyRs);

    signedToken = JWT.create()
    .withExpiresAt(new Date())
    .withSubject(jwtData.getSub()).
    withAudience(jwtData.getAud()).sign(algorithmRs);

but when I run the sign function to create a JWT I face this error:

Exception in thread "main" com.auth0.jwt.exceptions.SignatureGenerationException: The Token's Signature couldn't be generated when signing using the Algorithm: SHA256withECDSA
at com.auth0.jwt.algorithms.ECDSAAlgorithm.sign(ECDSAAlgorithm.java:65)
at com.auth0.jwt.JWTCreator.sign(JWTCreator.java:441)
at com.auth0.jwt.JWTCreator.access$100(JWTCreator.java:26)
at com.auth0.jwt.JWTCreator$Builder.sign(JWTCreator.java:419)

And it caused by:

Caused by: java.security.SignatureException: Invalid DER signature format.
at com.auth0.jwt.algorithms.ECDSAAlgorithm.DERToJOSE(ECDSAAlgorithm.java:118)
at com.auth0.jwt.algorithms.ECDSAAlgorithm.sign(ECDSAAlgorithm.java:63)
... 6 more

Would you please help with these errors and tell me where I went wrong?


Solution

  • Here a simple example of how you can get a signed JWT token using ES256 and how you can verify it :

    import io.jsonwebtoken.Claims;
    import io.jsonwebtoken.Jws;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    import io.jsonwebtoken.security.Keys;
    
    import java.security.KeyPair;
    import java.time.LocalDate;
    
    public class Jwt {
    
        public static void main(String[] args) {
            KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.ES256);
    
            //generate signed JWT token
            String signedToken = Jwts.builder()
                    .setExpiration(java.sql.Date.valueOf(LocalDate.now().plusWeeks(2)))
                    .setSubject("your subject")
                    .setAudience("your audience")
                    .signWith(keyPair.getPrivate())
                    .compact();
    
            //verify signed JWT token (no exceptions means check is OK)
            Jws<Claims> claimsJws = Jwts.parser()
                    .setSigningKey(keyPair.getPublic())
                    .parseClaimsJws(signedToken);
        }
    }