Class JSONObjectWriter

java.lang.Object
org.webpki.json.JSONObjectWriter

public class JSONObjectWriter extends Object
Creates JSON objects and performs serialization using a variety of formats.

Also provides built-in support for encoding JSF (JSON Signature Format), JEF (JSON Encryption Format) and JWK objects.

  • Field Details

    • MAX_INTEGER

      public static final long MAX_INTEGER
      Integers outside of this range are not natively supported by I-JSON/JavaScript.
      See Also:
    • SIGNATURE_DEFAULT_LABEL_JSON

      public static final String SIGNATURE_DEFAULT_LABEL_JSON
      See Also:
  • Constructor Details

    • JSONObjectWriter

      public JSONObjectWriter(JSONObjectReader objectReader)
      For updating already read JSON objects.
      Parameters:
      objectReader - Existing object reader
    • JSONObjectWriter

      public JSONObjectWriter()
      Creates a fresh JSON object and associated writer.
  • Method Details

    • setupForRewrite

      public void setupForRewrite(String name)
      Prepares the current object writer for a rewrite of a property.
      Parameters:
      name - Name of property to be rewritten
    • setString

      public JSONObjectWriter setString(String name, String value)
      Set a "string" property.

      Sample:

          "statement": "Life is good!"
       
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
    • setInt

      public JSONObjectWriter setInt(String name, int value)
      Set an int property.

      Sample:

          "headCount": 300
       
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
    • setInt53

      public JSONObjectWriter setInt53(String name, long value)
      Set a long property.

      Sample:

          "quiteNegative": -800719925474099

      Note that long data is limited to 53 bits of precision (9007199254740992L), exceeding this limit throws an exception. If you need higher precision use setLong(String, long).
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
      See Also:
    • setLong

      public JSONObjectWriter setLong(String name, long value)
      Set a long property.

      Sample:

          "quiteLong": "89007199254740991"

      Note: This method puts the value within quotes to provide full 64-bit precision which does not have a native counterpart in JavaScript.
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
      See Also:
    • setDouble

      public JSONObjectWriter setDouble(String name, double value)
      Set a double property.

      Sample:

          "Planck's Constant": 6.62607004e-34
       
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
    • setBigInteger

      public JSONObjectWriter setBigInteger(String name, BigInteger value)
      Set a BigInteger property.

      Note: this is a mapped type since there is no BigInteger type in JSON.

      Sample:

          "aPrettyHugeNumber": "94673335822222222222222222222222222222222222222222222"
       
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
    • setBigDecimal

      public JSONObjectWriter setBigDecimal(String name, BigDecimal value)
      Set a BigDecimal property.

      Note: this is a mapped type since there is no BigDecimal type in JSON.

      Sample:

          "big": "56.67e+450"
       
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
    • setMoney

      public JSONObjectWriter setMoney(String name, BigDecimal value)
      Set a Money property.

      Note: this is a mapped type since there is no Money type in JSON.

      Specification: https://www.w3.org/TR/payment-request/#dfn-valid-decimal-monetary-value.

      Sample:
          "amount": "460.25"
       
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
      See Also:
    • setMoney

      public JSONObjectWriter setMoney(String name, BigDecimal value, int decimals)
      Set a Money property.

      Note: this is a mapped type since there is no Money type in JSON.

      Specification: https://www.w3.org/TR/payment-request/#dfn-valid-decimal-monetary-value.

      Sample:
          "amount": "460.25"
       
      Parameters:
      name - Property
      value - Value
      decimals - Number of fractional digits
      Returns:
      Current instance of JSONObjectWriter
      See Also:
    • setBoolean

      public JSONObjectWriter setBoolean(String name, boolean value)
      Set a boolean property.

      Sample:

          "theEarthIsFlat": false
       
      Parameters:
      name - Property
      value - Value
      Returns:
      Current instance of JSONObjectWriter
    • setNULL

      public JSONObjectWriter setNULL(String name)
      Set a null property.

      Sample:

          "myKnowledgeOfTheLispProgrammingLanguage": null
       
      Parameters:
      name - Property
      Returns:
      Current instance of JSONObjectWriter
      See Also:
    • setDateTime

      public JSONObjectWriter setDateTime(String name, GregorianCalendar dateTime, EnumSet<ISODateTime.DatePatterns> format)
      Set an ISO formatted dateTime property.

      Note: this is a mapped type since there is no dateTime type in JSON.

      Sample:

          "received": "2016-11-12T09:22:36Z"
       
      Parameters:
      name - Property
      dateTime - Date/time value
      format - Requited output format
      Returns:
      Current instance of JSONObjectWriter
      See Also:
    • setBinary

      public JSONObjectWriter setBinary(String name, byte[] value)
      Set a byte[] property.

      This method utilizes Base64Url encoding.

      Sample:

          "nonce": "lNxNvAUEE8t7DSQBft93LVSXxKCiVjhbWWfyg023FCk"
       
      Parameters:
      name - Property
      value - Array of bytes
      Returns:
      Current instance of JSONObjectWriter
      See Also:
    • setObject

      public JSONObjectWriter setObject(String name, JSONObjectReader objectReader)
      Set a JSON object.

      This method assigns a property name to an already existing object reader which is useful for wrapping JSON objects.

      Parameters:
      name - Property
      objectReader - Object reader
      Returns:
      Current instance of JSONObjectWriter
    • setObject

      public JSONObjectWriter setObject(String name, JSONObjectWriter objectWriter)
      Set a JSON object.

      This method assigns a property name to an already created object writer which is useful for nested JSON objects.

      Parameters:
      name - Property
      objectWriter - Object writer
      Returns:
      Current instance of JSONObjectWriter
    • setObject

      public JSONObjectWriter setObject(String name)
      Set (create) a JSON object.

      This method creates an empty JSON object and links it to the current object through a property.

      Parameters:
      name - Property
      Returns:
      New instance of JSONObjectWriter
    • setArray

      public JSONArrayWriter setArray(String name)
      Set (create) a JSON array.

      This method creates an empty JSON array and links it to the current object through a property.

      Parameters:
      name - Property
      Returns:
      New instance of JSONArrayWriter
    • setArray

      public JSONObjectWriter setArray(String name, JSONArrayWriter arrayWriter)
      Set a JSON array.

      This method assigns a property name to an already created array writer which is useful for nested JSON objects.

      Parameters:
      name - Property
      arrayWriter - Array writer
      Returns:
      Current instance of JSONObjectWriter
    • setBinaryArray

      public JSONObjectWriter setBinaryArray(String name, List<byte[]> values)
      Set an array of byte[] property.

      This method puts each byte array (after Base64Url encoding) into a single JSON array.

      Sample:

          "blobs": ["lNxNvAUEE8t7DSQBft93LVSXxKCiVjhbWWfyg023FCk","LmTlQxXB3LgZrNLmhOfMaCnDizczC_RfQ6Kx8iNwfFA"]
       
      Parameters:
      name - Property
      values - List holding arrays of bytes
      Returns:
      Current instance of JSONObjectWriter
      See Also:
    • setStringArray

      public JSONObjectWriter setStringArray(String name, String[] values)
      Set a String[] property.

      This method puts each String into a single JSON array.

      Sample:

          "usPresidents": ["Clinton","Bush","Obama","Trump"]
       
      Parameters:
      name - Property
      values - Array of String
      Returns:
      Current instance of JSONObjectWriter
    • setDynamic

      public JSONObjectWriter setDynamic(JSONObjectWriter.Dynamic jsonSetDynamic)
      Set JSON data using an external (dynamic) interface.

      Sample using a construct suitable for chained writing:

          setDynamic((wr) -> optionalString == null ? wr : wr.setString("opt", optionalString)); 
       
      Parameters:
      jsonSetDynamic - Interface (usually Lambda)
      Returns:
      An instance of JSONObjectWriter
    • copyElement

      public JSONObjectWriter copyElement(String newName, String sourceName, JSONObjectReader source)
      Copy arbitrary JSON data from a JSONObjectReader
      Parameters:
      newName - Property name in the current object
      sourceName - Property name in the source object
      source - The JSON reader object
      Returns:
      An instance of JSONObjectWriter
    • setSignature

      public JSONObjectWriter setSignature(JSONSigner signer)
      Set a JSF "signature"object.

      This method performs all the processing needed for adding a JSF signature to the current object.

      Parameters:
      signer - The interface to the signing key and type
      Returns:
      Current instance of JSONObjectWriter
       
      Sample Code:
      import java.io.IOException;
      
      import java.security.PrivateKey;
      import java.security.PublicKey;
      
      import org.webpki.crypto.AsymKeySignerInterface;
      import org.webpki.crypto.AsymSignatureAlgorithms;
      import org.webpki.crypto.SignatureWrapper;
      
      import org.webpki.json.JSONAsymKeySigner;
      import org.webpki.json.JSONAsymKeyVerifier;
      import org.webpki.json.JSONObjectReader;
      import org.webpki.json.JSONObjectWriter;
      import org.webpki.json.JSONParser;
      import org.webpki.json.JSONSignatureDecoder;
                 .
                 .
                 .
          public void signAndVerifyJSF(PrivateKey privateKey, PublicKey publicKey) {
      
              // Create an empty JSON document
              JSONObjectWriter writer = new JSONObjectWriter();
      
              // Fill it with some data
              writer.setString("myProperty", "Some data");
      
              // Sign document
              writer.setSignature(new JSONAsymKeySigner(privateKey, publicKey, null));
      
              // Serialize document
              String json = writer.toString();
      
              // Print signed document on the console
              System.out.println(json);
      
      {
        "myProperty": "Some data",
        "signature": {
          "algorithm": "ES256",
          "publicKey": {
            "kty": "EC",
            "crv": "P-256",
            "x": "PxlJQu9Q6dOvM4LKoZUh2XIe9-pdcLkvKfBfQk11Sb0",
            "y": "6IDquxrbdq5ABe4-HQ78_dhM6eEBUbvDtdqK31YfRP8"
          },
          "value": "vHXWLfhmkl2qk3Eo5gwBFJy68RFMCJziviO8QkUAwarjNL4yrd5VGbYnYzoVLWj50up5A908_8eVDt_W0xJo7g"
        }
      }
      
              // Parse document
              JSONObjectReader reader = JSONParser.parse(json);
      
              // Get and verify signature
              JSONSignatureDecoder signature = reader.getSignature(new JSONCryptoHelper.Options());
              signature.verify(new JSONAsymKeyVerifier(publicKey));
      
              // Print document payload on the console
              System.out.println("Returned data: " + reader.getString("myProperty"));
          }
      
    • setSignature

      public JSONObjectWriter setSignature(String signatureLabel, JSONSigner signer)
    • setMultiSignature

      public JSONObjectWriter setMultiSignature(JSONSigner signer)
      Set a JSF multi-signature object.

      This method performs all the processing needed for adding multiple JSF signatures to the current object.

      Parameters:
      signer - Signature interface
      Returns:
      Current instance of JSONObjectWriter
    • setMultiSignature

      public JSONObjectWriter setMultiSignature(String signatureLabel, JSONSigner signer)
    • setChainedSignature

      public JSONObjectWriter setChainedSignature(JSONSigner signer)
      Set a JSF chained-signature object.

      This method performs all the processing needed for adding multiple JSF signatures to the current object.

      Parameters:
      signer - Signature interface
      Returns:
      Current instance of JSONObjectWriter
    • setChainedSignature

      public JSONObjectWriter setChainedSignature(String signatureLabel, JSONSigner signer)
    • createCorePublicKey

      public static JSONObjectWriter createCorePublicKey(PublicKey publicKey, AlgorithmPreferences algorithmPreferences)
      Create a JSF (JWK) formatted public key.

      Typical use:

          setObject("myPublicKey", JSONObjectWriter.setCorePublicKey(myPublicKey, AlgorithmPreferences.JOSE);
      
      Resulting JSON:
          "myPublicKey": {
               .
            depends on the actual public key type and value   
               .
          }
      
      Parameters:
      publicKey - Public key value
      algorithmPreferences - JOSE or SKS algorithm notation
      Returns:
      New instance of JSONObjectWriter
    • setPublicKey

      public JSONObjectWriter setPublicKey(PublicKey publicKey, AlgorithmPreferences algorithmPreferences)
      Set a JSF (JWK) formatted public key.

      Resulting JSON:

          "publicKey": {
               .
            depends on the actual public key type and value   
               .
          }
      
      Parameters:
      publicKey - Public key value
      algorithmPreferences - JOSE or SKS algorithm notation
      Returns:
      Current instance of JSONObjectWriter
    • setPublicKey

      public JSONObjectWriter setPublicKey(PublicKey publicKey)
      Set a JSF (JWK) formatted public key.

      This method is equivalent to setPublicKey(PublicKey, AlgorithmPreferences) using AlgorithmPreferences.JOSE as second argument.

      Parameters:
      publicKey - Public key value
      Returns:
      Current instance of JSONObjectWriter
    • setCertificatePath

      public JSONObjectWriter setCertificatePath(X509Certificate[] certificatePath)
      Set a JSF certificate path property.

      Each path element (certificate) is base64url encoded and the path must be sorted where certificate[i] is signed by certificate[i + 1].

      Resulting JSON:

          "certificatePath": ["MIIETTCCAjWgAwIBAgIGAUoqo74...gfdd" {,...}]
      
      Parameters:
      certificatePath - Sorted certificate path array
      Returns:
      Current instance of JSONObjectWriter
    • createEncryptionObject

      public static JSONObjectWriter createEncryptionObject(byte[] unencryptedData, ContentEncryptionAlgorithms contentEncryptionAlgorithm, JSONEncrypter encrypter)
      Create a JEF encrypted object.
      Parameters:
      unencryptedData - Data to be encrypted
      contentEncryptionAlgorithm - Content encryption algorithm
      encrypter - Holds keys etc.
      Returns:
      New instance of JSONObjectWriter
    • createEncryptionObjects

      public static JSONObjectWriter createEncryptionObjects(byte[] unencryptedData, ContentEncryptionAlgorithms contentEncryptionAlgorithm, List<JSONEncrypter> encrypters)
      Create a JEF encrypted object for multiple recipients.
      Parameters:
      unencryptedData - Data to be encrypted
      contentEncryptionAlgorithm - Content encryption algorithm
      encrypters - Holds keys etc.
      Returns:
      New instance of JSONObjectWriter
    • serializeToString

      public String serializeToString(JSONOutputFormats outputFormat)
      Serialize current object writer to a Java String.
      Parameters:
      outputFormat - Any JSONOutputFormats
      Returns:
      JSON string data
    • serializeToBytes

      public byte[] serializeToBytes(JSONOutputFormats outputFormat)
      Serialize current object writer to a Java byte[].
      Parameters:
      outputFormat - Any JSONOutputFormats
      Returns:
      JSON UTF-8 data
    • toString

      public String toString()
      Pretty print JSON of current object writer.
      Overrides:
      toString in class Object