Trending

World technology news

→
How CBOR map ordering changes a file digest
Software Engineering · 2020
Software Engineering2020

How CBOR map ordering changes a file digest

Compare two deterministic CBOR orders from the 2020 RFC 8949 and see how a ten-byte greenhouse configuration produces two SHA-256 digests.

Archive retrospective · Topic year 2020

Developer's JournalPublished: Dec 5, 20266 min read
Reading progress0%
In this article
  1. One configuration with two different file digests
  2. Encode keys before comparing them
  3. Where the earlier profile differs
  4. Reproducing the ten-byte outputs
  5. Use the same profile on the device and in storage
  6. What an interoperability fixture should prove

One configuration with two different file digests

Imagine two maintenance tools that deliver a configuration to a greenhouse controller. A desktop tool opens the profile saved by the field team. A gateway tool builds the same profile from its local settings. The configuration travels as a map. In this example, numeric key 84 sets a temperature alarm, numeric key -3 sets the number of samples in a moving average, and the text key r records the schema revision. The archive uses each file's SHA-256 digest to avoid storing an identical package twice. When the tools write the same entries in different orders, both files describe the same settings but take separate addresses in storage. The team needs a common description of the bytes to produce. RFC 8949, published in December 2020, documents two CBOR map sorting rules that let the protocol make that choice explicit. The greenhouse and its field numbers are fictional.

Encode keys before comparing them

The first byte, a3, announces a map with three key-value pairs. Decimal 84 becomes 18 54. The first byte signals a positive integer whose magnitude follows in one additional byte, while 54 in hexadecimal is decimal 84. CBOR represents negative numbers through the quantity -1 minus the value. For -3, that quantity is two and fits in the additional information of byte 22. The text key r becomes 61 72. The first byte declares one byte of UTF-8 text and the second carries the character. Core deterministic ordering compares these encoded keys from their first bytes. The comparison sees 18, 22 and 61 in that order. The encoder sorts whole entries alongside the encoded keys, so it preserves values 42, 4 and 2 alongside their respective fields. Input order can change without changing those relationships.

Application flowConceptual sketch · summary of the article's technical flow
Illustrative diagram. The order of the same three keys and the full byte sequence under both profiles.

Where the earlier profile differs

RFC 7049, published in 2013, recommended sorting keys by encoded length first in its description of Canonical CBOR. It compared the encoded bytes after finding that two keys had equal length. RFC 8949 retains this sorting option in Section 4.2.3. The distinction appears at the front of our map. Core ordering chooses 18 54 before 22 because 18 is smaller than 22. Length-first ordering moves 22 to the front because its key occupies one byte. Keys 84 and r each take two bytes, so the comparison between those two still puts 84 first. A library upgrade can affect future file digests if its default output changes. A compatibility check can record the section number as a reference for its expected bytes, especially when settings called canonical appear in more than one tool.

Reproducing the ten-byte outputs

The code ran locally on Node.js v24.19.0 without extra packages. It encodes keys and values separately, sorts the pairs using the selected comparison and concatenates the result. The output for core ordering was a31854182a2204617202. Length-first ordering produced a322041854182a617202. Both arrays contain ten bytes. Reversing the entry list reproduced each profile's earlier output. The executable assertion also checked that the digests differ. The digest for core ordering starts with 0ad6ddaf and the length-first digest starts with 0ec3aab8. The sample handles small integers, short UTF-8 strings and a flat map. It demonstrates the ordering rule on a current runtime. The test used neither a historical version of an encoder nor data collected from an actual controller.

import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';

const settings = [[84, 42], [-3, 4], ['r', 2]];

function smallItem(majorType, argument) {
  assert(Number.isInteger(argument) && argument >= 0 && argument <= 255);
  const type = majorType << 5;
  return argument < 24
    ? Buffer.from([type | argument])
    : Buffer.from([type | 24, argument]);
}

function encodeItem(value) {
  if (Number.isInteger(value)) {
    return value < 0 ? smallItem(1, -1 - value) : smallItem(0, value);
  }
  assert.equal(typeof value, 'string');
  const text = Buffer.from(value, 'utf8');
  return Buffer.concat([smallItem(3, text.length), text]);
}

function encodeMap(entries, compare) {
  const pairs = entries.map(([key, value]) => [encodeItem(key), encodeItem(value)]);
  pairs.sort(([left], [right]) => compare(left, right));
  return Buffer.concat([smallItem(5, pairs.length), ...pairs.flat()]);
}

const byBytes = Buffer.compare;
const byLength = (left, right) => left.length - right.length || byBytes(left, right);
const core = encodeMap(settings, byBytes);
const lengthFirst = encodeMap(settings, byLength);
assert.equal(core.toString('hex'), 'a31854182a2204617202');
assert.equal(lengthFirst.toString('hex'), 'a322041854182a617202');
assert.deepEqual(encodeMap(settings.toReversed(), byBytes), core);
assert.deepEqual(encodeMap(settings.toReversed(), byLength), lengthFirst);

const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
assert.notEqual(sha256(core), sha256(lengthFirst));
console.log(JSON.stringify({
  node: process.version,
  core: { hex: core.toString('hex'), sha256: sha256(core) },
  lengthFirst: { hex: lengthFirst.toString('hex'), sha256: sha256(lengthFirst) },
  reversedEntryOrderChecked: true,
}, null, 2));

Use the same profile on the device and in storage

A configuration format can state which data types it permits, how it sorts maps and which bytes it hashes. If the threshold travels as a whole number of degrees Celsius, the schema can specify the integer type and unit. A user interface can display 42.0 while the protocol continues to carry the integer 42. In a repository that already holds older files, test reading, writing and verification separately. A digest verifier can use the stored bytes to check a stored digest. Recording the encoding profile alongside older objects will help later maintenance distinguish files with the same values and different serializations. Give both producers a deliberately shuffled input, then compare the expected bytes directly. If clients can receive configurations from a different schema revision, define how each revision handles fields it cannot interpret before relying on the archive for restoration.

What an interoperability fixture should prove

A useful test fixture tracks the decoded settings and the encoded output. First, check that both tools understand the same three settings. Next, choose one profile and check that both tools produce its expected octets. Finally, keep the two numeric keys with different encoded lengths in the fixture to detect a change in ordering. A test restricted to small positive integers may pass under both rules and miss the distinction. If the application later adds tags or a new number type, preserve the current fixture and develop another with its own expected output. Store the profile and the original binary alongside the test digest. The original provides a way to locate the first differing byte if one producer starts writing a different representation of the same model. Leave machine-specific timestamps and paths out of the expected output. Record the runtime version in the test receipt and keep the exact output separately so it can accompany a support report.

367 reads ✎ Write a comment

Reader discussion

Discussion prompt

Which data would you verify before applying this development in your field?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.