
canonicalize
JSON canonicalize function. Creates crypto safe predictable canonicalization of
JSON as defined by RFC8785.
TypeScript type definitions are included.
Usage
Normal Example
import canonicalize from 'canonicalize';
const json = {
"from_account": "543 232 625-3",
"to_account": "321 567 636-4",
"amount": 500,
"currency": "USD"
}
console.log(canonicalize(json));
Crazy Example
import canonicalize from 'canonicalize';
const json = {
"1": {"f": {"f": "hi","F": 5} ,"\n": 56.0},
"10": { },
"": "empty",
"a": { },
"111": [ {"e": "yes","E": "no" } ],
"A": { }
}
console.log(canonicalize(json));
Via CLI
The function can be executed directly using npx without explicit installation. This allows JSON files and arbitrary input to be canonicalized with standard input/output:
npx canonicalize < input.json > output.json
echo '{
"from_account": "543 232 625-3",
"to_account": "321 567 636-4",
"amount": 500,
"currency": "USD"
}' | npx canonicalize > simple-data.json
curl --silent https://pokeapi.co/api/v2/pokemon/pikachu | npx canonicalize > pikachu.json
Best practices for signature schemes
Here follows an example of how untrusted input can be processed and validated
before being treated as safe.
import canonicalize from 'canonicalize';
const untrustedInputText = ;
const inputSignature = ;
const untrustedInputObject = JSON.parse(untrustedInputText);
const canonicalText = canonicalize(untrustedInputObject);
const isValid = validateSignature(canonicalText, inputSignature);
if (isValid) {
const validatedInput = JSON.parse(canonicalText);
}
Forwarding untrustedInputText downstream passes on bytes an attacker could
have altered while verification still succeeded; a consumer that resolves
duplicate property names first-one-wins will then read a different document
than the one you validated.
Install
As a library:
npm install canonicalize --save
As a CLI tool:
npm install -g canonicalize
canonicalize < input.json > output.json
Test
npm test