java.lang.Object
de.christofreichardt.json.websignature.JWS

public class JWS extends Object
This class provides a Fluent API for generating and validating JSON Web Signatures.

Example 1: Signing

Firstly, we create a keypair:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(ecGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Secondly, we read a JsonObject from a file:
Path path = Path.of("json", "my-json-object.json");
JsonObject jsonObject;
try (JsonReader jsonReader = Json.createReader(new FileInputStream(path.toFile()))) {
    jsonObject = jsonReader.readObject();
}
Now we can sign the jsonObject using the Fluent API:
JWSCompactSerialization compactSerialization = JWS.createSignature()
     .key(keyPair)
     .typ("JOSE")
     .payload(jsonObject)
     .sign();
This will create the following JOSE header within the first part of the JWS Compact Serialization:
{
   "alg": "ES256",
   "typ": "JOSE",
   "jwk": {
       "kty": "EC",
       "crv": "secp256r1 [NIST P-256,X9.62 prime256v1] (1.2.840.10045.3.1.7)",
       "x": "_ickpOtyfliWJQv3QUmYR4PboGupj-VuoVYAa1ACvDk",
       "y": "VSoYSDk3E-E857UolPZmC2htBPUJ69HIaZY3hR7G_PA"
   }
}
(You will get other x,y coordinates with virtual certainty).

Example 2: Validating

Firstly, we create a JsonWebPublicKey from the given jwk header parameter:
JsonWebPublicKey jsonWebPublicKey = JsonWebPublicKey.fromJson(compactSerialization.joseHeader().getJsonObject("jwk"));
Now we can validate the signature:
boolean validated = JWS.createValidator()
    .compactSerialization(compactSerialization)
    .key(jsonWebPublicKey)
    .validate();
assertThat(validated).isTrue();
Author:
Christof Reichardt
See Also:
  • Method Details

    • createSignature

      public static SignatureBegin createSignature()
      Entry point for creating signatures.
      Returns:
      a SignatureBegin instance, an interface of the Fluent API.
    • createValidator

      public static ValidationBegin createValidator()
      Entry point for validating signatures.
      Returns:
      a ValidationBegin instance, an interface of the Fluent API.