Two Valid JSON Files, One Signature: Why Canonicalisation Matters
Here are two valid JSON files. One says to pay Alice 10. The other contains both 1000000 and 10 as the amount. With a perfectly ordinary "parse, re-serialise, verify" routine, one signature passes for both.
{"amount":10,"to":"alice"}
{"amount":1000000,"amount":10,"to":"alice"}
Ed25519 is doing its job here; the code in front of it quietly changes what is being checked.
Signatures cover bytes, and JSON has many spellings
A signature covers an exact byte string and knows nothing about objects or fields, so changing one space makes verification fail.
JSON, meanwhile, lets you write the same data in lots of ways:
- object members in any order
- any amount of whitespace between tokens
10,10.0or1e1"alice"or"alice"
If anything between signer and verifier decodes and re-encodes the document (a proxy, a queue, a database column such as Postgres jsonb), the bytes can change while the data apparently doesn't. The tempting fix is canonicalisation: boil both sides down to one agreed spelling before signing or verifying.
The homemade version accepts files it should reject
In Go, the homemade canonicaliser usually looks like this. It works in the demo, because encoding/json sorts map keys when it marshals.
func canon(raw []byte) ([]byte, error) {
var v any
if err := json.Unmarshal(raw, &v); err != nil {
return nil, err
}
return json.Marshal(v)
}
Sign {"amount":10,"to":"alice"}, then verify the signature against canon(file). The reordered file passes, as intended. So does the file with two amount members, because encoding/json keeps the last one and throws the first away without complaint.
This bites when something else reads the original bytes. RFC 8259 says member names SHOULD be unique, and warns that receivers behave unpredictably when they aren't. A consumer that takes the first value sees a payment of 1000000, carrying a signature your verifier approved for 10.
Numbers have a similar hole. Decoding into any turns every number into a float64, so these two documents canonicalise to identical bytes, ending in 992:
{"id":9007199254740993}
{"id":9007199254740992}
Quick detour, because this one is lovely. A float64 has 53 bits of significand, so above 253 it can no longer hold every integer. 9007199254740993 is the first positive one to fall down the gap. If that field is an account ID, two different accounts now share a signature.
RFC 8785 pins down one spelling
The JSON Canonicalization Scheme (JCS, RFC 8785, an Informational RFC) defines the output properly:
- no whitespace between tokens
- object members sorted by name, comparing UTF-16 code units
- numbers written the way ECMAScript writes an IEEE 754 double
- strings escaped in one prescribed, minimal way
- input restricted to I-JSON, which forbids duplicate names
Sorting map keys doesn't give you JCS. Go's json.Marshal escapes <, > and & as < and friends by default, which JCS does not. It also writes negative zero as -0, where JCS writes 0. A signer using a real JCS library and a verifier using your helper will disagree on some inputs and agree on all your test fixtures.
Hang on, why UTF-16? That is how JavaScript compares strings. U+1F600 (an emoji) is stored as a surrogate pair starting 0xD83D, so it sorts before U+FF61, a halfwidth full stop. Compare the UTF-8 bytes, as Go's string ordering does, and you get the opposite order.
JCS also leaves Unicode normalisation alone. A precomposed "é" and an "e" followed by a combining accent look the same on screen, but remain different strings with different signatures.
Verify first, then use only what you verified
Go 1.27 has JCS in the standard library, as jsontext.Value.Canonicalize. It rejects duplicate member names. This verifier also decodes from the canonical bytes, so the program acts on exactly what the signature covered.
package payment
import (
"crypto/ed25519"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"slices"
)
type Payment struct {
To string `json:"to"`
Amount int64 `json:"amount"`
}
func Verify(pub ed25519.PublicKey, raw, sig []byte) (Payment, error) {
var p Payment
// Canonicalize rewrites the value, so work on a copy.
c := jsontext.Value(slices.Clone(raw))
if err := c.Canonicalize(); err != nil {
return p, fmt.Errorf("canonicalise: %w", err)
}
if !ed25519.Verify(pub, c, sig) {
return p, errors.New("bad signature")
}
// Decode the bytes that were verified, never raw.
if err := json.Unmarshal(c, &p, json.RejectUnknownMembers(true)); err != nil {
return Payment{}, fmt.Errorf("decode: %w", err)
}
return p, nil
}
Given the signature over the original payment, a reordered file with 1e1 as the amount verifies and decodes as 10. The duplicate-member file fails before the signature is even checked.
Large integers still need care. JCS treats every number as a double, so 9007199254740993 still becomes 9007199254740992. Decoding the canonical bytes keeps verification and behaviour consistent, but the value may not be what the sender meant. Put IDs and other large integers in strings, and have the signer reject numbers that cannot survive the trip.
Go's CanonicalizeRawInts(false) option preserves integer digits instead. That departs from strict JCS, so both ends would have to agree on it.
Better still, don't canonicalise at all
If you control the format, sign the payload bytes and carry those exact bytes to the verifier. Check the signature, then parse them, with nothing to reconstruct.
Existing formats do this:
- JWS signs the base64url-encoded header and payload as transmitted.
- DSSE signs the payload bytes together with a payload type, using length prefixes so the boundary between them is unambiguous.
The cost is that your payload travels as an opaque blob, often base64 encoded, and intermediaries must leave it alone. I think that is usually a bargain. Canonicalisation earns its place when the JSON has to stay readable and editable in transit, or when each side rebuilds the document from its own records.
Signing raw bytes doesn't remove parser disagreements. A genuine signer can still be tricked into signing a document with duplicate members, which two consumers then read differently. Parse strictly after verifying.
Tests that should fail loudly
Round-tripping your own output proves very little. Feed the verifier awkward input instead:
- duplicate names, including one spelled with a
\uescape - integers either side of 253
-0,1e1and very small exponents- member names containing emoji and characters above U+E000
- strings containing
<,&and U+2028 - trailing data after the closing brace
If the signer and verifier use different languages, run the same vectors through both and compare the canonical bytes, before any keys get involved. A hex diff will tell you far more than a "bad signature" error ever will.