Envelope Format v4.0 (normative)

  • Status: Normative specification, implemented in cryptography_suite.envelope. Pending independent cryptographic review; the format is frozen for 4.0 as of 4.0.0rc1 (RFC-0010, RFC-0036), and any change to it restarts the public review.

  • Resolves: the RFC-0005 “Unresolved questions” and decision-register item D-002 (magic bytes, integer labels, suite construction and identifier, recipient-manifest construction, context-binding construction, CDDL).

  • Test vectors: vectors/envelope-v4.0.json

The key words MUST, MUST NOT, SHOULD, and MAY are to be interpreted as in BCP 14 (RFC 2119, RFC 8174) when, and only when, they appear in all capitals. All integers are unsigned and big-endian. || is concatenation. u8, u32, u64 are 1-, 4-, and 8-byte big-endian unsigned integers.

1. Overview

+-----------------------------------------------------------------+
| preamble (16 bytes)                                             |
|   magic | major | minor | profile | flags | header_len | rcpt_len|
+-----------------------------------------------------------------+
| protected header  (header_len bytes, deterministic CBOR map)     |
+-----------------------------------------------------------------+  <- protected
| recipient section (rcpt_len bytes, deterministic CBOR map)      |     bytes end
+-----------------------------------------------------------------+     before rcpt
| record 0 | record 1 | ... | final record                        |
+-----------------------------------------------------------------+

The protected bytes are the first 12 preamble bytes followed by the protected header. They never change for the life of an envelope, including across rewrap. The recipient section is the only mutable part; it is authenticated separately so it can be replaced without touching ciphertext.

2. Preamble

Offset

Size

Field

Value

0

4

magic

89 43 53 45 ("\x89CSE")

4

1

major

4

5

1

minor

0 for this specification

6

1

profile

1 one-shot, 2 streaming

7

1

flags

0; every other value is reserved

8

4

header_len

u32 length of the protected header, ≥ 1

12

4

rcpt_len

u32 length of the recipient section, ≥ 1

A reader MUST reject a wrong magic as FORMAT_INVALID, and a major version other than 4, an unknown profile, or nonzero flags as FORMAT_UNSUPPORTED. A reader MUST accept any minor version: minor additions are noncritical labels that do not change the interpretation of existing fields. Both lengths MUST be checked against the limits of section 9 before the bytes they describe are read.

3. Deterministic CBOR profile

The protected header, the recipient section, and the canonical context use the RFC 8949 section 4.2.1 core deterministic encoding restricted to:

  • major types 0 (unsigned integer), 2 (byte string), 3 (UTF-8 text), 4 (array), and 5 (map);

  • definite lengths with every argument in its shortest form;

  • map keys that are unsigned integers or text strings, ordered by the bytewise lexicographic order of their encodings, with no duplicates.

Negative integers, tags, floating-point numbers, simple values (including true, false, and null), indefinite lengths, reserved additional information, invalid UTF-8, trailing bytes, nesting deeper than 8, and more than 128 entries in a top-level map MUST be rejected as FORMAT_INVALID.

4. Protected header

protected-header = {
  1 => uint,                ; suite identifier, 1 = suite 1
  2 => bstr .size 32,       ; message identifier (random)
  3 => uint,                ; chunk_size: plaintext bytes per non-final record
  4 => bstr .size 32,       ; key commitment
  5 => bstr .size 32,       ; context commitment
  6 => tstr,                ; policy identifier, 1..128 characters
  7 => [* uint],            ; critical labels, strictly increasing
  ? 8 => uint,              ; created_at, seconds since the Unix epoch
  ? 9 => uint,              ; plaintext_length: REQUIRED for profile 1,
                            ;   FORBIDDEN for profile 2
  * uint => any,            ; labels >= 10: extensions
}
  • chunk_size MUST be 1 to 4 194 304 and MUST NOT exceed the reader’s policy maximum (LIMIT_EXCEEDED otherwise).

  • created_at MUST be at most 253 402 300 799 (9999-12-31T23:59:59Z). It is written only when the policy enables creation times.

  • plaintext_length MUST be at most 67 108 864.

  • Text fields MUST NOT contain C0 control characters or DEL.

  • Labels 1–9 are defined here and MUST NOT appear in critical. Every label in critical MUST be present in the map. A reader that does not understand a label listed in critical MUST fail with CRITICAL_FIELD_UNSUPPORTED. A v4.0 reader understands no extension label, so any nonempty critical fails.

  • Unknown labels not listed in critical MUST be ignored. They remain covered by the protected bytes, so they cannot be altered.

5. Recipient section

recipient-section = {
  1 => [1*32 recipient],
  2 => bstr .size 32,       ; recipient-manifest MAC (section 6.4)
}

recipient = {
  1 => tstr,                ; provider identifier (lowercase reverse-DNS)
  2 => tstr,                ; key identifier, 1..2048 characters
  3 => tstr,                ; immutable key version, 1..2048 characters
  4 => tstr,                ; wrapping algorithm identifier
  5 => bstr,                ; wrapped data key, 1..65536 bytes
  ? 6 => { 1*32 tstr => tstr }, ; provider-safe metadata, omitted when empty
}

No other labels are permitted in the recipient section or in a recipient. Each recipient’s deterministic encoding MUST NOT exceed the policy’s per-recipient bound. Every recipient wraps the same data key; a key version is always resolved and immutable, never an alias.

6. Suite 1: CS4-AES256GCM-HKDF-SHA512-COMMIT

Suite identifier 1. All primitives are NIST-approved algorithms supplied by pyca/cryptography (no FIPS-validation claim is made).

6.1 Per-envelope material

The sealer generates, from the operating system CSPRNG, for every envelope including an empty one:

  • DEK: 32 bytes (the data-encryption key; never stored, only wrapped);

  • message_id: 32 bytes.

6.2 Key schedule

okm = HKDF-SHA-512(
        IKM  = DEK,
        salt = message_id,
        info = "cryptography-suite/v4 suite-1 key-schedule",
        L    = 128)

content_key    = okm[0:32]     ; AES-256-GCM key for records
key_commitment = okm[32:64]    ; stored in header label 4
context_key    = okm[64:96]    ; keys the context commitment
recipients_key = okm[96:128]   ; keys the recipient-manifest MAC

6.3 Commitments

context_commitment = HMAC-SHA-256(context_key,
                       "cryptography-suite/v4 context" || 0x00 ||
                       canonical_context)

canonical_context is the deterministic CBOR map (section 3) of the application context: Unicode NFC-normalized text keys mapped to NFC text or byte strings. The context itself is never stored. Because the commitment is keyed by material derived from the DEK, a party without the DEK cannot test guesses of low-entropy context values offline.

A reader MUST recompute key_commitment from the unwrapped DEK and compare it to header label 4 in constant time before using any other derived key. A mismatch is AUTHENTICATION_FAILED.

6.4 Recipient-manifest MAC

header_digest  = SHA-512(protected_bytes)
recipients_mac = HMAC-SHA-256(recipients_key,
                   "cryptography-suite/v4 recipients" || 0x00 ||
                   header_digest || CBOR(recipient list))

CBOR(recipient list) is the deterministic encoding of label 1 of the recipient section. A mismatch is AUTHENTICATION_FAILED.

6.5 Records

record      = u8 type || u32 ct_len || ciphertext
type        = 0 (non-final) | 1 (final)
nonce(i)    = 0x00000000 || u64(i)
aad(i, t)   = "cryptography-suite/v4 record" || 0x00 ||
              header_digest || u64(i) || u8(t)
ciphertext  = AES-256-GCM-Encrypt(content_key, nonce(i), plaintext_i, aad(i, t))

Records are numbered from 0. A non-final record MUST carry exactly chunk_size plaintext bytes; the final record carries 0 to chunk_size bytes and MAY be empty only when it is record 0. ct_len is the plaintext length plus the 16-byte tag. There MUST be exactly one final record, it MUST be last, and the envelope MUST end immediately after it (TRAILING_DATA otherwise). At most 2^32 − 1 records are allowed. For profile 1 the total plaintext MUST equal plaintext_length.

The content key is unique to the envelope, so deterministic nonces never repeat under a key. Binding the index and the final flag in both nonce and AAD (the STREAM construction of Hoang, Reyhanitabar, Rogaway, and Vizár) rejects reordered, duplicated, dropped, truncated, and extended records.

7. Provider binding

Providers receive protected_bytes as the binding argument of wrap_data_key and unwrap_data_key and MUST bind the wrapped DEK to it (for example as AES-GCM additional data or a KMS encryption context over its SHA-256). Providers never receive the application context, any derived key, or plaintext. A provider that detects a binding mismatch SHOULD raise AuthenticationError.

8. Processing rules

8.1 Seal

  1. Validate caller types, plaintext and context sizes, required context keys, and the provider allowlist from the policy. No provider call occurs before these checks pass.

  2. describe_key resolves the primary key, then each additional recipient key, to an immutable, enabled version with the wrap capability. A sealer MUST NOT emit an envelope when any configured recipient fails to resolve or wrap: a silently missing escrow recipient is a recovery failure that surfaces only during an incident.

  3. Generate DEK and message_id; derive the key schedule.

  4. Build the protected header and protected_bytes.

  5. wrap_data_key(DEK, binding = protected_bytes) once per recipient key, each through the provider that owns it, primary first; build the recipient section with its MAC.

  6. Emit the preamble, header, recipient section, and records.

8.2 Open

  1. Parse the preamble, header, and recipient section within policy limits.

  2. Select the recipients whose key the reader trusts. The reader, not the envelope, decides which wrapping keys count: a recipient is a candidate only when its provider identifier and key identifier name a key in the reader’s own configuration, either literally or through an alias the reader’s provider resolves, and, when the reader pins a version, that version. A recipient that names any other key, even one the reader’s provider could use, MUST NOT reach the provider (RFC-0031, F-1). Each (provider, key, version) is tried at most once.

  3. For each candidate, in envelope order: unwrap with binding = protected_bytes, derive the key schedule, and verify the key commitment. An authentication failure, a provider failure, or KEY_STATE_DENIED moves on to the next candidate; any other policy refusal is final. The first candidate that passes is used; if none does, the last failure is reported, and KEY_NOT_FOUND when there was no candidate.

  4. Verify the recipient-manifest MAC, then the context commitment against the caller’s context (CONTEXT_MISMATCH on failure, without naming any field).

  5. Authenticate and decrypt records in order. One-shot open returns nothing until every record and the end of input have been verified. Stream open writes each authenticated record to an uncommitted TransactionalSink and commits only after the final record and end of input verify; any failure aborts the sink.

8.3 Inspect

Inspect performs steps 1 of open plus record framing validation (without decryption) and makes no provider call. Its result is marked not_verified and exposes only an opaque context-commitment identifier, "cs4-ctx:" || base64url(context_commitment).

8.4 Rewrap

Rewrap opens the recipient section as in 8.2 steps 1–4 (except the context commitment) and wraps the same DEK to the resolved destination version with the same binding. The replaced recipient is:

  1. the recipient the caller names, by provider and key identifier and, when given, version (RFC-0032);

  2. otherwise the one with the destination’s provider and key identifier (rotation to a new version of the same logical key), when the envelope has one;

  3. otherwise the first recipient, which a sealer writes as its primary (migration to another key).

The choice never depends on which recipient unwrapped, so its result does not depend on which key service was available (RFC-0035). Every other recipient is kept in place, so neither a rotation nor a migration drops an escrow recipient even when the escrow key performed the unwrap. When the caller names a recipient: if the envelope does not hold it, rewrap fails with KEY_NOT_FOUND before any key is used, unless the envelope already holds the destination’s version, in which case it is returned unchanged; if the envelope holds both the named recipient and the destination’s version, the named recipient is removed and nothing is wrapped; and if another recipient holds a different version of the destination’s key, rewrap fails with POLICY_DENIED, so that no envelope holds two versions of one logical key. Rewrap recomputes the MAC and copies every record byte unchanged. Content authentication is preserved, not reverified. Rewrapping to the version already present returns the envelope unchanged. A streaming rewrap MAY emit the new recipient section before the records have been read, provided that a later framing failure (section 6.5) discards the entire output; only a fully validated envelope is ever committed.

8.5 Range open

Range open returns the plaintext bytes [offset, offset + length) and reads only the records that cover them.

  1. Perform open steps 1–4 against the envelope’s first bytes.

  2. Derive the layout from the envelope size S. With stride = 5 + chunk_size + 16 and (full, rem) = divmod(S − prefix_length, stride): if rem = 0, the final record is record full − 1 with chunk_size plaintext bytes (and full = 0 is FORMAT_INVALID); otherwise it is record full with rem − 21 plaintext bytes, which MUST be nonnegative and MAY be zero only when full = 0. A one-shot envelope’s plaintext_length MUST equal the size the layout implies.

  3. Record i starts at prefix_length + i · stride. Its type MUST be final exactly when i is the final index, and its ct_len MUST equal the layout’s plaintext size plus 16 (FORMAT_INVALID otherwise). Each record is authenticated exactly as in 6.5, which binds its index and final flag.

  4. A request that extends past the end returns the bytes up to the end and MUST authenticate the final record, even when no plaintext from it is returned, so truncation cannot pass as a short read.

Range open authenticates every returned byte and its position. It does not read, and therefore does not authenticate, records outside the range, and it does not detect bytes appended after the final record unless the range reaches the end. Readers that need the whole envelope verified use open.

9. Limits

Policy values may only lower these hard ceilings.

Resource

Hard ceiling

Default policy

Enterprise policy

Protected header

1 MiB

64 KiB

64 KiB

Canonical context

1 MiB

64 KiB

64 KiB

Recipients

32

4

4

One recipient entry

64 KiB

16 KiB

16 KiB

One-shot plaintext

64 MiB

16 MiB

16 MiB

Streaming plaintext

1 TiB

100 GiB

100 GiB

Chunk size (read)

4 MiB

1 MiB

1 MiB

Chunk size (written)

—

64 KiB

64 KiB

Records

2^32 − 1

—

—

CBOR nesting / top-level map entries

8 / 128

—

—

10. Error mapping

Condition

Code

Wrong magic, malformed CBOR, missing or ill-typed field, framing violation, truncation

FORMAT_INVALID

Unsupported major version, profile, flags, or suite

FORMAT_UNSUPPORTED

A length or count above the effective limit

LIMIT_EXCEEDED

Unknown label listed as critical

CRITICAL_FIELD_UNSUPPORTED

Bytes after the final record

TRAILING_DATA

Key commitment, recipient MAC, record tag, or provider binding failure

AUTHENTICATION_FAILED

Context commitment mismatch

CONTEXT_MISMATCH

No recipient for any configured provider

KEY_NOT_FOUND

Default messages for AUTHENTICATION_FAILED and CONTEXT_MISMATCH are identical so the human-readable text is not an oracle.

11. Security considerations

  • Key commitment. Without it, an AES-GCM ciphertext can be crafted to decrypt validly under two different keys (“invisible salamanders”), letting a malicious sender show different plaintexts to different recipients. The key commitment binds every recipient to the one DEK that produced it.

  • Context confidentiality. The context is authenticated but never stored; only a DEK-keyed commitment is. Envelope holders without the DEK learn nothing about the context beyond its absence from the header.

  • Nonce and data limits. Each envelope has its own 256-bit content key, so the per-key record count (at most 2^32 − 1) and per-record size (at most 4 MiB) stay far below AES-GCM’s per-key limits.

  • Streaming release. Plaintext from a stream is only ever written to an uncommitted transactional sink, so a truncated or tampered stream leaves no committed output. Unsafe destinations (pipes, sockets, stdout) are refused.

  • Insiders. Any holder of a recipient key can unwrap the DEK and therefore re-authenticate the recipient section or seal new data under the same message; recipients are trusted for confidentiality, not for non-repudiation. Use signatures outside this format for that property.

  • Reader-side key trust. The format has no signature, so an envelope is authentic only because a key the reader trusts unwrapped its DEK. A reader that let the envelope choose the key would accept any envelope wrapped under a key the attacker controls but the reader’s provider can also use (an attacker’s KMS key the reader’s role may decrypt with, or an HPKE identity loaded for another purpose). Section 8.2 step 2 therefore makes key selection the reader’s decision.

  • Metadata. Provider identifier, key identifier and version, recipient count, chunk size, plaintext length (one-shot), record count, and optional creation time are visible.

  • Memory. Python cannot guarantee zeroization; the SDK keeps its own copies of the DEK and derived keys in mutable buffers that it overwrites after use (best effort only).

  • Side channels. Commitment and MAC comparisons are constant time; pyca/cryptography provides the AES-GCM, HKDF, and HMAC implementations. No broader constant-time guarantee is made.

12. Conformance and vectors

vectors/envelope-v4.0.json contains positive vectors with every intermediate value (canonical context, protected bytes, header digest, each derived key, commitments, MAC) and negative vectors with their expected error code. A conforming reader, given a provider that returns dek_hex for each listed wrapped key when the binding hashes to binding_sha256_hex, opens every positive vector and rejects every negative vector with the listed code. The repository checks the vectors against the Python implementation and against an independent reader that is written only from this document (tests/unit/test_envelope_vectors.py). A second-language implementation is a release gate (RFC-0005, RFC-0010); the JavaScript reader in interop/javascript (RFC-0023) opens every vector and agrees with the Python implementation on random and tampered envelopes.