canonical_json 1.0.0
canonical_json: ^1.0.0

Dart native js
Flutter Android iOS web

Encoder and decoder for a canonical JSON format, useful when cryptographically hashing or signing JSON objects.

Canonical JSON Encoder/Decoder #

This package provides an encoder and decoder for encoding/decoding canonical JSON. The canonical JSON format does not support floating-point numbers and the decoder validates that the value is indeed a canoncially encoded JSON value.

Disclaimer: This is not an officially supported Google product.

Example #

import 'package:canonical_json/canonical_json.dart';
void main() {
  // Encode a message
  final bytes = canonicalJson.encode({
    'from': 'alice',
    'message': 'Hi Bob',
  });
  final hash = sha256(bytes); // using a sha256 from some library...
  // Decode message
  try {
    final msg = canonicalJson.decode(bytes);
    if (!fixedTimeEqual(sha256(canonicalJson.encode(msg)), bytes)) {
      print('Expected a different hash!');
    }
    print(msg['message']);
  } on InvalidCanonicalJsonException {
    print('Message was not canonical JSON!');
  }
}

Canonical JSON Format #

  • Integers are encoded without leading zeros.
  • Floating point numbers are not permitted.
  • Map keys appear in sorted by byte values.
  • Whitespace is not permitted (outside of strings).
  • Only allow escape sequences in strings are \\ and \".
  • Strings must be valid UTF-8 in Unicode Normalization Form C.

This follows the rules outlined in canoncial JSON, with the deviation that this package requires strings to be encoded as valid UTF-8 in Unicode Normalization Form C rather than arbitrary byte values. This is only recommended by canoncial JSON, but this library takes the oppinion that binary values should be encoded.

See Also #

4
likes
95
pub points
66%
popularity

Publisher

google.dev

Encoder and decoder for a canonical JSON format, useful when cryptographically hashing or signing JSON objects.

Homepage
Repository (GitHub)
View/report issues

Documentation

API reference

License

Apache 2.0 (LICENSE)

Dependencies

typed_data, unorm_dart

More

Packages that depend on canonical_json