JSON Web Signature (JWS) with Elliptic Curve (EC)

This is an example how to create and verify a JSON Web Signature (JWS) using Elliptic Curve (EC) public / private key cryptography. The payload is a simple string but can also be a JSON string or BASE64URL encoded data.

The EC keys should be of sufficient length to match the required level of security. Note that while EC signatures are shorter than an RSA signature of equivalent strength, they may take more CPU time to verify.

The Nimbus JOSE+JWT library supports all standard EC digital signature algorithms:

  • ES256 - EC P-256 DSA with SHA-256
  • ES384 - EC P-384 DSA with SHA-384
  • ES512 - EC P-521 DSA with SHA-512

The example uses the key ID ("kid") parameter of the JWS header to indicate the signing key and simplify key roll-over. The exact method by which the recipient establishes the public EC key candidate(s) to check the signature must be specified by the application's security protocol.

Example code:

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.*;
import com.nimbusds.jose.jwk.*;
import com.nimbusds.jose.jwk.gen.*;


// Generate an EC key pair
ECKey ecJWK = new ECKeyGenerator(Curve.P_256)
    .keyID("123")
    .generate();
ECKey ecPublicJWK = ecJWK.toPublicJWK();

// Create the EC signer
JWSSigner signer = new ECDSASigner(ecJWK);

// Creates the JWS object with payload
JWSObject jwsObject = new JWSObject(
    new JWSHeader.Builder(JWSAlgorithm.ES256).keyID(ecJWK.getKeyID()).build(),
    new Payload("Elliptic cure"));

// Compute the EC signature
jwsObject.sign(signer);

// Serialize the JWS to compact form
String s = jwsObject.serialize();


// The recipient creates a verifier with the public EC key
JWSVerifier verifier = new ECDSAVerifier(ecPublicJWK);

 // Verify the EC signature
assertTrue("ES256 signature verified", jwsObject.verify(verifier));
assertEquals("Elliptic cure", jwsObject.getPayload().toString());