Skip to content

trestle.core.canonicalization

trestle.core.canonicalization ¤

Canonical JSON helpers for reproducible OSCAL artifact digests.

Classes¤

Functions¤

canonicalize_json_object(json_obj) ¤

Return RFC 8785 canonical UTF-8 bytes for a parsed JSON-compatible object.

Source code in trestle/core/canonicalization.py
51
52
53
54
55
56
def canonicalize_json_object(json_obj: Any) -> bytes:
    """Return RFC 8785 canonical UTF-8 bytes for a parsed JSON-compatible object."""
    try:
        return rfc8785.dumps(json_obj)
    except rfc8785.CanonicalizationError as error:
        raise TrestleError(f'Unable to canonicalize JSON object according to RFC 8785: {error}')

canonicalize_json_text(json_text) ¤

Parse JSON text and return its parsed object and canonical bytes.

Source code in trestle/core/canonicalization.py
39
40
41
42
43
44
45
46
47
48
def canonicalize_json_text(json_text: str) -> Tuple[Any, bytes]:
    """Parse JSON text and return its parsed object and canonical bytes."""
    try:
        json_obj = json.loads(
            json_text, object_pairs_hook=_object_pairs_without_duplicates, parse_constant=_reject_json_constant
        )
    except json.JSONDecodeError as error:
        raise TrestleError(f'Input is not valid JSON: {error}')

    return json_obj, canonicalize_json_object(json_obj)

load_canonical_json_file(path) ¤

Load a JSON document and return its parsed object and canonical bytes.

Source code in trestle/core/canonicalization.py
31
32
33
34
35
36
def load_canonical_json_file(path: pathlib.Path) -> Tuple[Any, bytes]:
    """Load a JSON document and return its parsed object and canonical bytes."""
    if not path.exists() or not path.is_file():
        raise TrestleError(f'JSON path does not exist or is not a file: {path}')

    return canonicalize_json_text(path.read_text(encoding=const.FILE_ENCODING))

sha256_digest_hex(data) ¤

Return a SHA-256 digest for canonical bytes.

Source code in trestle/core/canonicalization.py
59
60
61
def sha256_digest_hex(data: bytes) -> str:
    """Return a SHA-256 digest for canonical bytes."""
    return hashlib.sha256(data).hexdigest()

handler: python