JsonCanonicalization
JSON Canonicalization Scheme (JCS), RFC 8785.
Produces the canonical UTF-8 serialization of a JsonElement so that two structurally equal JSON values (same members, any key order or whitespace) always hash to the same bytes:
object members are sorted by the UTF-16 code units of their names (RFC 8785 §3.2.3),
no insignificant whitespace,
strings use the minimal escaping of ECMAScript
JSON.stringify(RFC 8785 §3.2.2.2): only",\and U+0000..U+001F are escaped, using the short forms\b \t \n \f \rand lowercase\u00xxotherwise; everything else (including non-ASCII) is emitted as is,numbers are parsed as IEEE-754 doubles and serialized like ECMAScript
Number.prototype.toString(RFC 8785 §3.2.2.3), so1.0,1, and1e0are all1. The literal must match the JSON number grammar (RFC 8259 §6): forms Kotlin/Java would accept but JSON does not (1d,1f, hex floats,NaN,Infinity,+1, leading zeros) are rejected, as are non-finite values. Integer literals (no fraction or exponent) whose magnitude exceeds 2^53 are REJECTED too: the double conversion RFC 8785 prescribes would silently map distinct integers to the same canonical bytes (and so the same digest), so such values must be carried as JSON strings,strings must be well-formed UTF-16: a lone surrogate cannot be encoded as UTF-8 and is rejected instead of being replaced by
?.
All rejections throw IllegalArgumentException.
Unlike DigestUtils.canonicalizeJson (key sorting only, numbers emitted verbatim), this output is interoperable with any RFC 8785 implementation.
Functions
Canonical JSON text of element per RFC 8785.
UTF-8 bytes of canonicalize; this is what RFC 8785 hashes and signs.