API reference

The package root exports exactly the names an application needs to seal and open envelopes. Providers, streaming, audit, and COSE live in their own modules and are imported explicitly.

Package root

Policy-driven envelope encryption and key lifecycle (v4 pre-release).

The package root exports exactly the RFC-0004 facade: Protector and its value models, protocols, and typed errors. Supporting declarations live in named submodules. Importing the package performs no I/O, reads no environment, and discovers no plugins.

The root exports Protector, Policy, EncryptionContext, KeyRef, KeyProvider, Envelope, EnvelopeMetadata, ErrorCode, and the error classes. Each is documented below, in the module that defines it.

Protector

v4 orchestration: seal, open, inspect, rewrap, and transactional streams.

Protector is the only stable entry point for protecting data. Callers never choose algorithms, nonces, data keys, or KDF parameters; they supply explicit providers, an immutable policy, a primary key reference (plus any additional recipient keys, such as a disaster-recovery escrow key), and the application context. Every failure is a typed, redacted CryptographySuiteError, and no plaintext is released before the data it came from has been authenticated.

class cryptography_suite.protector.Protector(*, policy, primary_key, provider=None, providers=None, additional_keys=(), decryption_keys=(), audit_sink=None)

Seal and open envelopes with explicit providers and a policy.

Every sealed envelope carries one recipient per configured recipient key: the primary_key first, then each of additional_keys (for example a second region’s KMS key or an offline recovery key).

Opening, rewrapping, and range reads unwrap only with trusted keys: the recipient keys and any decryption_keys (for example a key retired from sealing whose envelopes must stay readable). An envelope recipient that names any other key is never sent to a provider, even one the provider’s credentials could use, so an envelope made under a key the caller does not trust is not accepted as authentic (RFC-0031). A trusted key given by alias is matched through the provider’s canonical identifier, such as the key ARN an AWS alias names; that resolution is cached for five minutes.

Parameters:
  • policy (Policy) – The limits and permissions every operation is checked against.

  • primary_key (KeyRef) – The first recipient of every sealed envelope.

  • provider (KeyProvider | None) – The provider that owns the keys, when there is only one.

  • providers (Iterable[KeyProvider] | None) – Several providers, each with a distinct provider_id. Give exactly one of provider and providers.

  • additional_keys (Iterable[KeyRef]) – Further recipients of every sealed envelope, such as an escrow key, a second region, or a quorum.

  • decryption_keys (Iterable[KeyRef]) – Keys trusted for opening and rewrapping only, never for sealing, such as a retired primary key.

  • audit_sink (AuditSink | None) – Receives secret-free events as each operation starts and ends; required when policy.audit_required is set.

Raises:
  • PolicyError – The policy does not allow a provider or this many recipients, requires an audit sink that is missing, or requires a FIPS-mode backend that is not active.

  • TypeError – An argument has the wrong type.

  • ValueError – The keys and providers do not match each other.

A Protector is immutable after construction and safe to share between threads.

property policy: Policy

The policy every operation of this protector is checked against.

seal(plaintext, *, context)

Encrypt plaintext into a new envelope bound to context.

A fresh data key encrypts the plaintext, and every recipient key wraps it, the primary key first. If any recipient key cannot be resolved or cannot wrap, no envelope is returned: a missing escrow recipient would otherwise surface only during an incident.

Parameters:
  • plaintext (bytes | bytearray | memoryview) – Up to policy.max_plaintext_bytes bytes. Use seal_stream() for larger data.

  • context (EncryptionContext) – Authenticated, never stored; open() needs the same context.

Returns:

The envelope. It is not secret; store it anywhere.

Raises:
  • EnvelopeError – The plaintext or context exceeds a policy limit.

  • PolicyError – The context lacks a required key, or a recipient’s key or algorithm is not allowed.

  • ProviderError – A key service failed after the policy’s retries.

Return type:

Envelope

open(envelope, *, context)

Verify envelope completely and return its plaintext.

Only recipients that name a trusted key are unwrapped, in envelope order; a recipient whose key is disabled or unreachable falls back to the next one. Nothing is returned until every record and the end of the envelope have been authenticated.

Parameters:
  • envelope (Envelope | bytes | bytearray | memoryview) – An Envelope or its bytes.

  • context (EncryptionContext) – The context the envelope was sealed with.

Returns:

The plaintext.

Raises:
  • AuthenticationError – The envelope was changed, truncated, or extended, or no trusted key opens it.

  • ContextMismatchError – The context differs from the sealing one. Its message is the same as an authentication failure’s.

  • EnvelopeError – The envelope is malformed, unsupported, or over a policy limit.

  • ProviderError – No recipient names a trusted key (KEY_NOT_FOUND), or a key service failed.

Return type:

bytes

inspect(envelope)

Describe envelope without keys, provider calls, or decryption.

The structure and record framing are checked, but nothing is authenticated, so the result is marked not_verified. It never contains plaintext or context values; the context appears only as an opaque commitment identifier.

Raises:

EnvelopeError – The envelope is malformed, unsupported, or over a policy limit.

Parameters:

envelope (Envelope | bytes | bytearray | memoryview)

Return type:

EnvelopeMetadata

rewrap(envelope, *, destination_key, replace=None)

Move envelope to destination_key without re-encrypting it.

A trusted key unwraps the data key, which is wrapped again for the destination, replacing one recipient:

  • the recipient replace names, when it is given (RFC-0032);

  • otherwise the recipient for the destination’s logical key, when the envelope has one (rotation to a new version);

  • otherwise the first recipient, which the sealer always writes as its primary (migration to another key). Which recipient unwrapped does not matter, so the result never depends on which key service was available (RFC-0035 CORE-5).

Every other recipient is kept, and every record byte is copied unchanged. Rewrapping to a version the envelope already holds returns it unchanged, so a rewrap job can be rerun. Name the recipient with replace whenever it is not the primary key, for example to move an escrow recipient to an escrow key with a new name.

No context is needed, because the content is not decrypted. Its authentication is preserved, not reverified: use open() to verify the content.

Parameters:
  • envelope (Envelope | bytes | bytearray | memoryview) – An Envelope or its bytes.

  • destination_key (KeyRef) – A key of a configured provider. Without a version, the provider’s current version is used.

  • replace (KeyRef | None) – The recipient to replace, by provider and key name, and by version when one is given. If the envelope already holds the destination and not this recipient, it is returned unchanged; if it holds both, this recipient is removed.

Raises:
  • AuthenticationError – No trusted key opens the envelope, or its recipient section was changed.

  • EnvelopeError – The envelope is malformed or over a policy limit.

  • PolicyError – The destination’s algorithm is not allowed, or another recipient already holds a different version of the destination’s key (POLICY_DENIED).

  • ProviderError – The destination belongs to no configured provider (CAPABILITY_UNSUPPORTED), no recipient names a trusted key or the one replace names (KEY_NOT_FOUND), or a key service failed.

Return type:

Envelope

rewrap_stream(source, destination, *, destination_key, replace=None, cancel=None)

Rewrap an envelope of any size from a stream into a sink.

The recipient replaced is chosen as for rewrap(), including replace. Only the recipient section changes; every record is copied unchanged while its framing is checked, so a multi-gigabyte archive is rewrapped in bounded memory. Any failure, including a framing error after the new recipients were written, aborts the sink. Content authentication is preserved, not reverified.

Parameters:
Return type:

EnvelopeMetadata

seal_stream(source, destination, *, context, cancel=None)

Encrypt source into destination in bounded memory.

The plaintext is read in policy.chunk_size records, up to policy.max_stream_bytes. The sink is committed only after the final record is written, and any failure, including cancellation, aborts it, so a partial envelope is never published.

Parameters:
Returns:

Metadata of the envelope written.

Raises:
  • EnvelopeError – The stream exceeds policy.max_stream_bytes.

  • OperationalError – Reading, writing, or committing failed, or the operation was cancelled.

  • PolicyError – The context lacks a required key.

  • ProviderError – A key service failed after the policy’s retries.

Return type:

EnvelopeMetadata

open_stream(source, destination, *, context, cancel=None)

Verify and decrypt source into destination.

Each record is authenticated before its plaintext is written, and the sink is committed only after the final record and the end of the input verify. A tampered, truncated, or extended envelope aborts the sink, so no unauthenticated plaintext is ever published.

Parameters:
  • source (BinaryIO) – A readable binary stream holding the envelope.

  • destination (TransactionalSink) – A TransactionalSink.

  • context (EncryptionContext) – The context the envelope was sealed with.

  • cancel (Callable[[], bool] | None) – Polled between records; returning True stops the operation with CANCELLED.

Returns:

Metadata of the envelope, marked verified.

Raises:
Return type:

EnvelopeMetadata

open_range(source, *, offset, length, context)

Return up to length authenticated plaintext bytes from offset.

Only the records that cover the range are read and authenticated, so reading part of a large object (for example through an object store’s ranged reads behind a seekable file object) costs a few records, not the whole envelope. Every returned byte is authenticated together with its position. A range that extends past the end returns the bytes up to the end, and that end is authenticated by the final record. Records outside the range are not read, so this does not prove that the rest of the envelope is intact; open and open_stream verify everything.

Parameters:
Return type:

bytes

cryptography_suite.protector.inspect_envelope(source, *, policy=None)

Return structural metadata without keys, providers, or authentication.

The result is always not_verified. source may be an envelope, bytes, or a readable binary stream, which is read once in bounded pieces so that inspecting a large envelope does not load it into memory. The policy (default Policy()) bounds what is parsed.

Parameters:
  • source (Envelope | bytes | bytearray | memoryview | BinaryIO)

  • policy (Policy | None)

Return type:

EnvelopeMetadata

Policy

Immutable, validated security policy (RFC-0007).

A Policy is a frozen value whose canonical JSON serialization determines its identifier:

policy_id = "cs-policy-v1:" + base64url(SHA-256(canonical_json))

The identifier, not the policy, is written into every envelope. Policies are composed only by Policy.restrict(), which can never widen authority: allowlists intersect, maxima take the minimum, and requirements accumulate. Importing this module reads no environment and performs no I/O.

Policy.fips() (RFC-0027) restricts recipients to FIPS-approved wrapping algorithms and requires a pyca/cryptography backend running in FIPS mode. Fields added after the first release are written to the canonical document only when they differ from their defaults, so existing policy documents and identifiers are unchanged.

cryptography_suite.policy.FIPS_WRAPPING_ALGORITHMS: Final = frozenset({'aws-kms-symmetric-default', 'azure-keyvault-rsa-oaep-256-bound', 'cs4-hierarchical-hkdf-sha256-aes-256-gcm', 'cs4-hpke-mlkem1024-p384-hkdf-sha384-aes-256-gcm', 'cs4-hpke-p384-hkdf-sha384-aes-256-gcm', 'gcp-kms-google-symmetric-encryption', 'gcp-kms-ml-kem-1024-hpke-sha384-aes-256-gcm', 'gcp-kms-ml-kem-768-hpke-sha256-aes-256-gcm'})

AES-GCM, HKDF and HMAC with SHA-2, ECDH on P-384, ML-KEM (FIPS 203), and RSA-OAEP. X25519-based recipients (including X-Wing), quorum shares, and Vault Transit (whose key type the identifier does not reveal) are excluded.

Type:

Wrapping algorithms whose primitives are all FIPS-approved

class cryptography_suite.policy.Policy(profile='custom', allowed_provider_ids=None, required_context_keys=frozenset({}), max_context_bytes=65536, max_plaintext_bytes=16777216, max_stream_bytes=107374182400, chunk_size=65536, max_chunk_size=1048576, max_header_bytes=65536, max_recipients=4, max_recipient_entry_bytes=16384, record_creation_time=False, audit_required=False, allow_overwrite=False, provider_timeout_ms=30000, provider_max_attempts=3, approved_wrapping_algorithms=None, require_fips_backend=False, legacy_formats=frozenset({}), migration_deadline=None)

Frozen authority for envelope, provider, and resource decisions.

allowed_provider_ids of None permits any explicitly constructed provider and is rejected for the enterprise profile. All byte limits are bounded by the hard ceilings of RFC-0005 and may only be lowered.

Parameters:
  • profile (str)

  • allowed_provider_ids (frozenset[str] | None)

  • required_context_keys (frozenset[str])

  • max_context_bytes (int)

  • max_plaintext_bytes (int)

  • max_stream_bytes (int)

  • chunk_size (int)

  • max_chunk_size (int)

  • max_header_bytes (int)

  • max_recipients (int)

  • max_recipient_entry_bytes (int)

  • record_creation_time (bool)

  • audit_required (bool)

  • allow_overwrite (bool)

  • provider_timeout_ms (int)

  • provider_max_attempts (int)

  • approved_wrapping_algorithms (frozenset[str] | None)

  • require_fips_backend (bool)

  • legacy_formats (frozenset[str])

  • migration_deadline (datetime | None)

classmethod enterprise(*, approved_providers)

Provider-only, audited, RFC-0005 enterprise quotas, no overwrite.

Parameters:

approved_providers (Iterable[str])

Return type:

Policy

classmethod fips(*, approved_providers, approved_wrapping_algorithms=frozenset({'aws-kms-symmetric-default', 'azure-keyvault-rsa-oaep-256-bound', 'cs4-hierarchical-hkdf-sha256-aes-256-gcm', 'cs4-hpke-mlkem1024-p384-hkdf-sha384-aes-256-gcm', 'cs4-hpke-p384-hkdf-sha384-aes-256-gcm', 'gcp-kms-google-symmetric-encryption', 'gcp-kms-ml-kem-1024-hpke-sha384-aes-256-gcm', 'gcp-kms-ml-kem-768-hpke-sha256-aes-256-gcm'}))

The enterprise profile restricted to FIPS-approved algorithms.

Recipients must use a wrapping algorithm from approved_wrapping_algorithms (a subset of FIPS_WRAPPING_ALGORITHMS), and a Protector refuses to run unless the backend is in FIPS mode. This restricts algorithms; it does not by itself make a product FIPS 140-3 validated.

Parameters:
  • approved_providers (Iterable[str])

  • approved_wrapping_algorithms (Iterable[str])

Return type:

Policy

classmethod development()

Any explicit provider, lower limits, never labeled production.

Return type:

Policy

classmethod migration(*, deadline, legacy_formats, base=None)

Permit migrating the named legacy formats until deadline (RFC-0008).

Legacy input is never accepted by default or by format detection: each format is named, and the permission ends at a fixed UTC instant that no environment setting can extend. The permission is added to base (default Policy()), such as a production policy; a custom base becomes the migration profile, and an enterprise or FIPS base keeps its profile. restrict() never adds legacy permission, so restricting by a policy without it removes it.

Parameters:
  • deadline (datetime)

  • legacy_formats (Iterable[str])

  • base (Policy | None)

Return type:

Policy

restrict(overlay)

Return the intersection of self and overlay.

The result is never more permissive than either input. An empty provider intersection is rejected rather than silently denying all.

Parameters:

overlay (Policy)

Return type:

Policy

permits_legacy_format(name, *, now)

Whether migrating name is permitted at now (RFC-0008).

Parameters:
  • name (str)

  • now (datetime)

Return type:

bool

to_json()

Return the canonical UTF-8 JSON document that defines the id.

Return type:

bytes

classmethod from_json(data)

Parse a canonical policy document; unknown fields are rejected.

Parameters:

data (bytes | str)

Return type:

Policy

cryptography_suite.policy.fips_backend_active()

Whether pyca/cryptography’s OpenSSL backend runs in FIPS mode.

Return type:

bool

Encryption context

Immutable external encryption-context value model.

class cryptography_suite.context.EncryptionContext(values=None, *, purpose=None, tenant_id=None)

The application context an envelope is bound to, such as a tenant.

Sealing authenticates the context without storing it, and opening succeeds only with an equal context. Keys and text values are NFC-normalized; values are text or bytes. purpose and tenant_id are shorthands for the keys of those names:

EncryptionContext({"tenant": "acme"}, purpose="invoices")

Equality follows Mapping semantics, instances are hashable, and the repr never renders keys or values because context can be sensitive and low entropy. Construction bounds retained input storage only (128 entries, 1 MiB); the policy’s max_context_bytes bounds the encoded size when the context is used.

Parameters:
  • values (Mapping[str, ContextValue] | None)

  • purpose (str | None)

  • tenant_id (str | None)

Errors

Stable, redacted v4 error declarations.

exception cryptography_suite.errors.AuthenticationError(code=ErrorCode.AUTHENTICATION_FAILED, *, retryable=False, details=None)

Bases: CryptographySuiteError

Protected data authentication failure.

Parameters:
  • code (ErrorCode)

  • retryable (bool)

  • details (Mapping[str, JSONScalar] | None)

Return type:

None

exception cryptography_suite.errors.ContextMismatchError(code=ErrorCode.CONTEXT_MISMATCH, *, retryable=False, details=None)

Bases: CryptographySuiteError

Caller context did not match without identifying the mismatched value.

Parameters:
  • code (ErrorCode)

  • retryable (bool)

  • details (Mapping[str, JSONScalar] | None)

Return type:

None

exception cryptography_suite.errors.CryptographySuiteError(code=ErrorCode.INTERNAL_ERROR, *, retryable=False, details=None)

Bases: Exception

Base class for stable errors with immutable, redacted fields.

Parameters:
  • code (ErrorCode)

  • retryable (bool)

  • details (Mapping[str, JSONScalar] | None)

Return type:

None

exception cryptography_suite.errors.EnvelopeError(code=ErrorCode.FORMAT_INVALID, *, retryable=False, details=None)

Bases: CryptographySuiteError

Envelope structure, format, or resource-limit failure.

Parameters:
  • code (ErrorCode)

  • retryable (bool)

  • details (Mapping[str, JSONScalar] | None)

Return type:

None

class cryptography_suite.errors.ErrorCode(*values)

Bases: StrEnum

Stable machine-readable v4 error codes.

Unknown serialized codes remain representable so operational readers can preserve a code introduced by a newer compatible producer.

exception cryptography_suite.errors.MigrationError(code=ErrorCode.MIGRATION_INCOMPLETE, *, retryable=False, details=None)

Bases: CryptographySuiteError

Explicit migration transaction failure.

Parameters:
  • code (ErrorCode)

  • retryable (bool)

  • details (Mapping[str, JSONScalar] | None)

Return type:

None

exception cryptography_suite.errors.OperationalError(code=ErrorCode.INTERNAL_ERROR, *, retryable=False, details=None)

Bases: CryptographySuiteError

I/O, existing-output, cancellation, or internal operation failure.

Parameters:
  • code (ErrorCode)

  • retryable (bool)

  • details (Mapping[str, JSONScalar] | None)

Return type:

None

exception cryptography_suite.errors.PolicyError(code=ErrorCode.POLICY_INVALID, *, retryable=False, details=None)

Bases: CryptographySuiteError

Policy validation or authorization failure.

Parameters:
  • code (ErrorCode)

  • retryable (bool)

  • details (Mapping[str, JSONScalar] | None)

Return type:

None

exception cryptography_suite.errors.ProviderError(code=ErrorCode.PROVIDER_UNAVAILABLE, *, retryable=False, details=None)

Bases: CryptographySuiteError

Normalized provider failure.

Parameters:
  • code (ErrorCode)

  • retryable (bool)

  • details (Mapping[str, JSONScalar] | None)

Return type:

None

Envelope models

Public envelope value models.

class cryptography_suite.envelope.AuthenticationStatus(*values)

How much of an envelope a result vouches for.

not_verified: nothing was authenticated (inspect, and the result of sealing). verified: every byte was (open_stream). preserved_not_reverified: only the recipient section changed, and the content was copied without being decrypted again (rewrap_stream).

class cryptography_suite.envelope.Envelope(data)

An immutable byte container that makes no authentication claim.

Parameters:

data (bytes)

class cryptography_suite.envelope.EnvelopeMetadata(format_name, profile, major_version, minor_version, algorithm_suite, recipients, plaintext_size, ciphertext_size, chunk_count, context_commitment_id, created_at, critical_features, policy_id, authentication_status=AuthenticationStatus.NOT_VERIFIED)

A redacted structural view; authentication is explicit.

Parameters:
  • format_name (str)

  • profile (str)

  • major_version (int)

  • minor_version (int)

  • algorithm_suite (str)

  • recipients (tuple[KeyRef, ...])

  • plaintext_size (int | None)

  • ciphertext_size (int)

  • chunk_count (int)

  • context_commitment_id (str | None)

  • created_at (datetime | None)

  • critical_features (tuple[str, ...])

  • policy_id (str)

  • authentication_status (AuthenticationStatus)

Provider contract

Public provider-neutral protocols and models.

SecretBytes is the closable, non-serializable secret buffer that provider implementations (including separately distributed ones) return from unwrap_data_key.

class cryptography_suite.providers.KeyCapability(*values)

What a key version can do for this caller.

class cryptography_suite.providers.KeyDescription(key, capabilities, state, observed_at)

A key resolved to an immutable version, with its state and capabilities.

Parameters:
class cryptography_suite.providers.KeyProvider(*args, **kwargs)

A key service that wraps and unwraps data keys (RFC-0006).

A provider never sees plaintext, the encryption context, or any key derived from the data key. It must bind every wrap to the binding bytes it is given, the envelope’s protected header, so that a wrapped key cannot be moved to another envelope. cryptography_suite.providers.conformance.verify_provider() checks an implementation against this contract.

property provider_id: str

A stable reverse-DNS identifier, recorded in every envelope.

wrap_data_key(data_key, *, key, binding, request)

Wrap data_key under the exact version key names.

Every call must produce a fresh wrap, bound to binding.

Parameters:
Return type:

WrappedKey

unwrap_data_key(wrapped_key, *, binding, request)

Unwrap with the key and version wrapped_key names.

Raise AuthenticationError when the wrap is not bound to binding or was changed.

Parameters:
Return type:

SecretBuffer

describe_key(key, *, request)

Resolve key to an immutable version, its state and capabilities.

Parameters:
Return type:

KeyDescription

health_check(*, request)

Report whether the key service is reachable and configured.

Parameters:

request (ProviderRequest)

Return type:

ProviderHealth

class cryptography_suite.providers.KeyRef(provider_id, key_id, version=None)

A reference to a key of one provider, optionally to one version.

key_id is the provider’s name for the key, such as an AWS key ARN or alias, a Cloud KMS CryptoKey resource name, or a Vault Transit key name. Without a version, the provider’s current version is used for sealing; envelopes always record the exact version that wrapped them.

Parameters:
  • provider_id (str)

  • key_id (str)

  • version (str | None)

class cryptography_suite.providers.ProviderHealth(provider_id, status, observed_at)

A provider’s health, as observed at observed_at.

Parameters:
class cryptography_suite.providers.ProviderHealthStatus(*values)

The result of a provider health check.

class cryptography_suite.providers.ProviderKeyState(*values)

The lifecycle state of a key version at its provider.

class cryptography_suite.providers.ProviderRequest(deadline, cancel, operation_id, idempotency_key=None)

Per-call controls a Protector passes to its providers.

deadline is when the whole operation must finish; providers should give their own calls no more than the time left. cancel returns True once the caller has cancelled.

Parameters:
  • deadline (datetime | None)

  • cancel (Callable[[], bool] | None)

  • operation_id (str)

  • idempotency_key (str | None)

class cryptography_suite.providers.ReadOnlySecret(*args, **kwargs)

Borrowed secret access valid only for the owning buffer’s lifetime.

readonly_view()

Return a borrowed read-only view that must not outlive the buffer.

Return type:

memoryview

class cryptography_suite.providers.SecretBuffer(*args, **kwargs)

Closable secret storage without serialization or raw export methods.

class cryptography_suite.providers.SecretBytes(value)

A closable secret buffer satisfying the SecretBuffer protocol.

Parameters:

value (bytes | bytearray | memoryview)

classmethod adopt(buffer)

Take ownership of buffer without copying it.

Parameters:

buffer (bytearray)

Return type:

SecretBytes

readonly_view()

Return a borrowed read-only view that must not outlive the buffer.

Return type:

memoryview

class cryptography_suite.providers.WrappedKey(provider_id, key_id, version, wrapping_algorithm, opaque_bytes, metadata)

A data key wrapped by one provider, as recorded in an envelope.

opaque_bytes is meaningful only to the provider that produced it.

Parameters:
  • provider_id (str)

  • key_id (str)

  • version (str)

  • wrapping_algorithm (str)

  • opaque_bytes (bytes)

  • metadata (Mapping[str, str])

HPKE recipients

HPKE (RFC 9180) public-key recipients for envelope data keys.

An HPKE recipient wraps the envelope’s data key to a public key. Sealing needs only the public key, so producers (log shippers, edge devices, batch jobs) hold nothing that can decrypt; only the holder of the private key can open. Together with a KMS primary key this is the recommended escrow and break-glass recipient (RFC-0011, RFC-0012), and on its own it protects data for an offline or air-gapped reader with no key service at all.

Keys are grouped by a caller-chosen logical key_id. Each public key is an immutable version named by its fingerprint, so rotation means adding a new key pair under the same key_id; the most recently added version is the one describe_key resolves when no version is given.

Each wrap is bound to the recipient’s algorithm, key identifier, version, and the envelope’s protected header through the HPKE info input, so a wrapped key cannot be moved to another envelope, key, or version.

Post-quantum hybrid recipients (RFC-0017) pair ML-KEM (FIPS 203) with a classical key in one HPKE KEM, so a wrapped data key stays confidential while either component holds: data recorded today is protected against a future quantum computer (“harvest now, decrypt later”) without trusting ML-KEM alone. They need a pyca/cryptography backend that implements ML-KEM; see post_quantum_available().

The provider performs no I/O, reads no environment, and depends only on pyca/cryptography. Public keys travel as cs4hpke1-<kem>:<base64url> text; private keys are standard PKCS #8 (for example from openssl genpkey -algorithm X25519). A hybrid private key is a PEM bundle of its two PKCS #8 keys, the ML-KEM key and the classical key.

class cryptography_suite.providers.hpke.HpkeKem(*values)

Supported key-encapsulation mechanisms.

X25519 = 'x25519'

DHKEM(X25519, HKDF-SHA256) with HKDF-SHA256 and AES-256-GCM.

P384 = 'p384'

DHKEM(P-384, HKDF-SHA384) with HKDF-SHA384 and AES-256-GCM.

MLKEM768_X25519 = 'mlkem768-x25519'

Hybrid ML-KEM-768 + X25519 (X-Wing) with HKDF-SHA256 and AES-256-GCM.

MLKEM1024_P384 = 'mlkem1024-p384'

Hybrid ML-KEM-1024 + P-384 with HKDF-SHA384 and AES-256-GCM.

class cryptography_suite.providers.hpke.HpkeRecipientProvider(*, provider_id='cryptography-suite.hpke')

A thread-safe KeyProvider that wraps data keys with HPKE.

Parameters:

provider_id (str)

add_recipient(key_id, public_key)

Register a public key: this provider can wrap to it, not unwrap.

Parameters:
  • key_id (str)

  • public_key (X25519PublicKey | EllipticCurvePublicKey | HybridPublicKey)

Return type:

KeyRef

add_identity(key_id, private_key)

Register a private key: this provider can wrap to it and unwrap.

Parameters:
  • key_id (str)

  • private_key (X25519PrivateKey | EllipticCurvePrivateKey | HybridPrivateKey)

Return type:

KeyRef

class cryptography_suite.providers.hpke.HybridPrivateKey(mlkem_key, classical_key)

A post-quantum hybrid private key: an ML-KEM key and a classical key.

Parameters:
  • mlkem_key (MlKemPrivateKey)

  • classical_key (ClassicalPrivateKey)

class cryptography_suite.providers.hpke.HybridPublicKey(mlkem_key, classical_key)

A post-quantum hybrid public key: an ML-KEM key and a classical key.

The pairings are ML-KEM-768 with X25519 and ML-KEM-1024 with EC P-384.

Parameters:
  • mlkem_key (MlKemPublicKey)

  • classical_key (ClassicalPublicKey)

cryptography_suite.providers.hpke.generate_private_key(kem=HpkeKem.X25519)

Return a new private key for kem from the operating system CSPRNG.

Hybrid kems raise ProviderError(CAPABILITY_UNSUPPORTED) when the backend has no ML-KEM.

Parameters:

kem (HpkeKem)

Return type:

X25519PrivateKey | EllipticCurvePrivateKey | HybridPrivateKey

cryptography_suite.providers.hpke.key_version(public_key)

Return the immutable version identifier (fingerprint) of a public key.

Parameters:

public_key (X25519PublicKey | EllipticCurvePublicKey | HybridPublicKey)

Return type:

str

cryptography_suite.providers.hpke.load_private_key_pem(data, *, password=None)

Load a PKCS #8 PEM private key.

One X25519 or EC P-384 key is a classical identity. A bundle of exactly two keys, an ML-KEM key and its classical partner in either order, is a hybrid identity; an encrypted bundle uses one password for both keys.

Parameters:
  • data (bytes)

  • password (bytes | None)

Return type:

X25519PrivateKey | EllipticCurvePrivateKey | HybridPrivateKey

cryptography_suite.providers.hpke.load_public_key_text(text)

Decode the text produced by public_key_text().

Parameters:

text (str)

Return type:

X25519PublicKey | EllipticCurvePublicKey | HybridPublicKey

cryptography_suite.providers.hpke.post_quantum_available()

Whether the linked pyca/cryptography backend implements ML-KEM.

Hybrid keys can be generated, loaded, and used only when this is true.

Return type:

bool

cryptography_suite.providers.hpke.private_key_pem(private_key, *, password=None)

Encode private_key as PKCS #8 PEM, encrypted when password is set.

A hybrid key becomes the two-key bundle load_private_key_pem() reads. Keep the result secret: it is the decryption capability.

Parameters:
  • private_key (X25519PrivateKey | EllipticCurvePrivateKey | HybridPrivateKey)

  • password (bytes | None)

Return type:

bytes

cryptography_suite.providers.hpke.public_key_text(public_key)

Encode a public key as shareable cs4hpke1-<kem>:<base64url> text.

Parameters:

public_key (X25519PublicKey | EllipticCurvePublicKey | HybridPublicKey)

Return type:

str

Quorum recipients

Quorum recipients: k-of-n split knowledge and dual control (RFC-0021).

A quorum recipient protects the data key so that no single custodian can recover it, the “split knowledge and dual control” that key-management standards such as PCI DSS require for recovery keys. The data key is split with Shamir secret sharing over GF(2^8) into n shares; any threshold of them reconstruct it, and fewer reveal nothing about it. Each share is wrapped with HPKE (RFC-0012) to one custodian’s public key, classical or post-quantum hybrid (RFC-0017), and bound to the envelope header, the quorum version, and its own share index, so shares cannot be moved between envelopes, quorums, or positions. A tag keyed from the data key covers the whole wrapped structure, so after recovery every share, including the ones recovery did not need, is authenticated, and a wrong reconstruction is detected.

Sealing needs only the custodians’ public keys. Recovery works either way:

  • in one process, by registering at least threshold custodian private keys with QuorumRecipientProvider.add_custodian_identity(); or

  • as a distributed ceremony (RFC-0025), where no private key ever leaves its custodian: a RecoveryCeremony attached to the provider turns the first open attempt into one ShareRequest per custodian, each custodian runs release_share() on their own machine, which decrypts only their share and re-encrypts it to the ceremony’s ephemeral key, and the coordinator’s next open succeeds once threshold releases arrived.

Requests travel over channels nobody has to trust (RFC-0035). A custodian releases only to the coordinator whose RecoveryCeremony.fingerprint they received out of band, so a request that names another key, altered or forged, is refused. Each request also carries a one-time token encrypted to its custodian, and a release must carry a MAC under that token, so only the custodian can answer it: a release from anyone else is refused before it is decrypted, it never replaces an earlier one, and it cannot be blamed on a custodian who did not send it.

A released share is only as honest as its custodian. Recovery therefore searches the released shares for a combination that the integrity tag accepts, so one dishonest release cannot block recovery once enough honest ones are in, and every other release is checked against the recovered polynomial; an inconsistent one is discarded and its request listed in RecoveryCeremony.rejected (RFC-0031). A quorum version names its threshold and custodian set; changing either is a new version under the same key_id, and rewrap moves envelopes to it.

The GF(2^8) arithmetic uses table lookups; it runs only when sealing and in recovery, on secret-independent share coordinates, and is not intended for use where an attacker can time those operations at fine grain.

class cryptography_suite.providers.quorum.QuorumRecipientProvider(*, provider_id='cryptography-suite.quorum', ceremony=None)

A thread-safe KeyProvider that needs threshold of n custodians.

Parameters:
add_quorum(key_id, custodians, *, threshold)

Register a quorum version; the newest one is what key_id names.

Parameters:
  • key_id (str)

  • custodians (Sequence[X25519PublicKey | EllipticCurvePublicKey | HybridPublicKey])

  • threshold (int)

Return type:

KeyRef

add_custodian_identity(private_key)

Make one custodian’s private key available for recovery.

Returns the custodian’s fingerprint. Any quorum that includes the custodian can use it.

Parameters:

private_key (X25519PrivateKey | EllipticCurvePrivateKey | HybridPrivateKey)

Return type:

str

class cryptography_suite.providers.quorum.RecoveryCeremony

Coordinator side of a distributed recovery.

It holds an ephemeral HPKE identity (post-quantum hybrid when the backend supports ML-KEM) that custodians release shares to. Attach it to a QuorumRecipientProvider; an open that lacks shares then records the requests() to send, and succeeds once accept() has received threshold releases. Call close() afterwards.

property public_key: str

The ephemeral key custodians release to, as shareable text.

property fingerprint: str

The ceremony key’s fingerprint, for custodians to verify.

Give it to every custodian over a channel they trust; they pass it to release_share(), which refuses any other coordinator.

property rejected: tuple[ShareRequest, ...]

Requests whose released share proved inconsistent, oldest first.

Each names the custodian (by key fingerprint) whose release did not lie on the recovered polynomial: investigate them.

accept(response)

Store one custodian’s release; returns the request it answers.

Raises:
  • ValueError – The response is malformed, answers no open request, or answers one that was already released.

  • AuthenticationError – The release was not made by the request’s custodian, or was changed.

Parameters:

response (str)

Return type:

ShareRequest

close()

Wipe every released share and forget the requests.

Return type:

None

class cryptography_suite.providers.quorum.ShareRequest(request_id, provider_id, key_id, version, index, custodian, algorithm, binding_digest, coordinator_key, share_ciphertext, token_ciphertext)

What one custodian needs to release one share, and nothing secret.

binding_digest is the SHA-256 of the envelope’s protected bytes, so a custodian can record exactly which envelope a release was for. token_ciphertext is a one-time token encrypted to the custodian, which authenticates their release.

Parameters:
  • request_id (str)

  • provider_id (str)

  • key_id (str)

  • version (str)

  • index (int)

  • custodian (str)

  • algorithm (str)

  • binding_digest (str)

  • coordinator_key (str)

  • share_ciphertext (bytes)

  • token_ciphertext (bytes)

cryptography_suite.providers.quorum.combine_shares(points)

Interpolate at zero from (x, share) points with distinct nonzero x.

Parameters:

points (Sequence[tuple[int, bytes | bytearray]])

Return type:

bytearray

cryptography_suite.providers.quorum.release_share(request, identity, *, coordinator)

Custodian side: decrypt only this custodian’s share for the coordinator.

coordinator is the RecoveryCeremony.fingerprint the custodian received from the coordinator out of band, over a channel they trust (in person, a call, a signed ticket). A request that names any other coordinator key is refused, so an altered or forged request cannot collect the share.

The share is re-encrypted with HPKE to the ceremony’s key and bound to the request, so it is never in the clear outside this call, and the response carries a MAC under the request’s one-time token, which only this custodian can decrypt.

Raises:
  • ValueError – The request is for another custodian or another coordinator, or is malformed.

  • AuthenticationError – The share or the token does not authenticate: the request was altered.

Parameters:
  • request (str)

  • identity (X25519PrivateKey | EllipticCurvePrivateKey | HybridPrivateKey)

  • coordinator (str)

Return type:

str

cryptography_suite.providers.quorum.split_secret(secret, *, threshold, count)

Shamir-split secret; share i (0-based) is the polynomial at i+1.

Callers own the returned buffers and should wipe them after use.

Parameters:
  • secret (bytes)

  • threshold (int)

  • count (int)

Return type:

list[bytearray]

Hierarchical keys

Hierarchical keys: one key-service call per branch key, not per envelope.

At scale, calling a key service for every envelope costs latency, money, and quota. A HierarchicalKeyProvider (RFC-0026) puts a branch key between the root key in the key service and the envelopes:

  • A branch key is 32 random bytes, wrapped by the root KeyProvider (a cloud KMS, Vault, an HSM) and stored, wrapped, in a BranchKeyStore. Each branch (a tenant, a dataset, a region) has an active version; creating a new version is rotation.

  • The first wrap or unwrap that needs a branch key unwraps it through the root provider, once, and keeps it in a bounded in-memory cache: entries expire after cache_ttl seconds, can be limited to max_uses operations, and the least recently used are evicted beyond max_cache_entries. Evicted material is overwritten. Concurrent misses for the same branch key share one root call.

  • Each envelope’s data key is wrapped locally with AES-256-GCM under a key derived by HKDF-SHA256 from the branch key and a fresh 128-bit salt, and bound to the branch identity and the envelope’s protected header.

Envelopes record the branch identifier and the exact branch key version, so rotation never strands one. The root key service still authorizes and logs every branch-key unwrap; exposure of a cached branch key is bounded by the cache limits.

The branch-key store is untrusted for integrity: a record is used only if it was wrapped by the configured root key (its provider and key, directly or through the alias the root provider resolves, and its version when the root key pins one), so a record that another tenant wrapped under its own key is refused before the root is asked to unwrap it. A party that can both wrap under the root key and write to the store can still plant a branch key it knows; keep store writes with the key administrators, and prefer a root whose wrap needs authorization (a key service) over a public HPKE key.

class cryptography_suite.providers.hierarchical.BranchKeyRecord(branch_id, version, wrapped, created_at)

A branch key version as stored: only its root-wrapped form.

Parameters:
  • branch_id (str)

  • version (str)

  • wrapped (WrappedKey)

  • created_at (datetime)

to_json()

Serialize for a persistent store (contains no plaintext key).

Return type:

str

class cryptography_suite.providers.hierarchical.BranchKeyStore(*args, **kwargs)

Durable storage of root-wrapped branch keys.

Implementations persist BranchKeyRecord values (for example as BranchKeyRecord.to_json() text in a database). put must never replace an existing version.

class cryptography_suite.providers.hierarchical.HierarchicalKeyProvider(*, store, root, root_key, provider_id='cryptography-suite.hierarchical', cache_ttl=300.0, max_cache_entries=1024, max_uses=None, clock=<built-in function monotonic>)

A thread-safe KeyProvider that wraps data keys under branch keys.

Parameters:
  • store (BranchKeyStore)

  • root (KeyProvider)

  • root_key (KeyRef)

  • provider_id (str)

  • cache_ttl (float)

  • max_cache_entries (int)

  • max_uses (int | None)

  • clock (Callable[[], float])

property root_calls: int

How many times a branch key was unwrapped through the root.

create_branch_key(branch_id, *, request=None)

Create and activate a new version of branch_id (also rotation).

Parameters:
Return type:

KeyRef

clear_cache()

Overwrite and drop every cached branch key.

Return type:

None

class cryptography_suite.providers.hierarchical.InMemoryBranchKeyStore

A thread-safe reference store, for tests and single-process services.

Provider conformance

Executable RFC-0006 conformance checks for KeyProvider implementations.

Provider authors run verify_provider() against a test key (a real service in an integration environment, or a recorded or emulated one) to check the behaviour the envelope format relies on:

  1. describe_key resolves to an immutable, enabled version with the wrap and unwrap capabilities, under the provider’s own identifier;

  2. a wrapped data key names that exact key and version, and its opaque bytes do not contain the data key;

  3. unwrap with the same binding returns exactly the data key;

  4. unwrap with a different binding fails authentication (the binding is enforced, not just recorded);

  5. unwrap of altered opaque bytes fails authentication;

  6. two wraps of the same data key differ (no deterministic wrapping);

  7. an unknown key is reported as KEY_NOT_FOUND;

  8. health_check reports this provider.

The checks use random data keys only; they never see application data.

exception cryptography_suite.providers.conformance.ProviderConformanceError(check, reason)

A provider failed the named check.

Parameters:
  • check (str)

  • reason (str)

Return type:

None

cryptography_suite.providers.conformance.verify_provider(provider, key, *, missing_key=None, request=None)

Run every conformance check and return their names in order.

key must name a test key that can wrap and unwrap. missing_key names a key that does not exist (default: key with an unlikely identifier). Raises ProviderConformanceError naming the first check that fails.

Parameters:
Return type:

tuple[str, …]

Streaming

Public streaming declarations and the transactional file sink factory.

class cryptography_suite.streaming.SinkState(*values)

The state of a transactional sink.

class cryptography_suite.streaming.TransactionalSink(*args, **kwargs)

Output that becomes visible only when it is committed.

Streaming operations write plaintext or ciphertext to a sink and commit it only after the last record has been processed; on any failure they abort it. cryptography_suite.streaming.file_sink() is the filesystem implementation.

property max_write_size: int

The largest chunk one write accepts.

write(chunk)

Append chunk to the uncommitted output.

Parameters:

chunk (bytes)

Return type:

None

commit()

Publish everything written, atomically.

Return type:

None

abort()

Discard everything written; safe to call more than once.

Return type:

None

cryptography_suite.streaming.file_sink(*, output_root, relative_destination, policy, overwrite=False, source=None)

Return a sink that publishes relative_destination on commit.

output_root is a trusted, existing absolute directory; relative_destination is untrusted and must stay below it. Replacing an existing file requires both overwrite=True and policy.allow_overwrite. When source is an open file, a destination that is the same file (including through a hard link) is refused, so an operation can never destroy its own input. Errors are typed and never contain paths. The returned sink also supports with and aborts on exit unless committed.

Parameters:
  • output_root (PathLike[str] | str)

  • relative_destination (PathLike[str] | str)

  • policy (Policy)

  • overwrite (bool)

  • source (BinaryIO | None)

Return type:

TransactionalSink

cryptography_suite.streaming.filesystem_capabilities(output_root)

Report the atomic-output guarantees this platform gives under a root.

The result names each capability the file sink relies on (exclusive creation, no-follow opens, atomic publication, durability barriers, link detection) and the primitives used, so operators can check a deployment before writing to it. Nothing is created or written.

Parameters:

output_root (PathLike[str] | str)

Return type:

Mapping[str, str | bool]

Audit events

Public secret-free audit declarations.

class cryptography_suite.audit.AuditEvent(schema_version, event_id, occurred_at, operation_id, event_type, outcome, policy_id, error_code=None, component_id=None, provider_id=None, key_identifier_hash=None, envelope_identifier_hash=None, retry_attempt=None, transition=None, latency_bucket=None, integrity_checkpoint_ref=None)

One cs-audit/1 event: what happened, never what was protected.

Events carry identifiers, outcomes, and error codes. Key and envelope identifiers appear only as hashes, and no field can hold plaintext, context values, key material, or paths.

Parameters:
  • schema_version (str)

  • event_id (str)

  • occurred_at (datetime)

  • operation_id (str)

  • event_type (str)

  • outcome (str)

  • policy_id (str)

  • error_code (ErrorCode | None)

  • component_id (str | None)

  • provider_id (str | None)

  • key_identifier_hash (str | None)

  • envelope_identifier_hash (str | None)

  • retry_attempt (int | None)

  • transition (str | None)

  • latency_bucket (str | None)

  • integrity_checkpoint_ref (str | None)

class cryptography_suite.audit.AuditSink(*args, **kwargs)

Receives AuditEvent records as Protector operations run.

Each operation emits a started event and then a succeeded or failed one, synchronously. When the policy sets audit_required, an exception from emit fails the operation with IO_FAILED; otherwise it is ignored.

emit(event)

Record event.

Parameters:

event (AuditEvent)

Return type:

None

Audit chain

Tamper-evident audit trail: a signed hash chain of cs-audit/1 events.

AuditChain is an AuditSink that turns each event into a record line:

{"chain_id": ..., "event": {...}, "hash": ..., "previous": ...,
 "schema": "cs-audit-chain/1", "sequence": n, "signature": ...}

hash is SHA-256 over a domain label and the canonical JSON of the record without hash and signature; previous is the hash of the record before it (64 zeros for the first). signature is an Ed25519 signature over the hash. Anyone holding only the public key can therefore verify the trail with verify_audit_chain(), and cannot forge it.

A HybridSigningKey signs every record with Ed25519 and ML-DSA-65 (FIPS 204) under schema cs-audit-chain/2 (RFC-0020). Such a trail stays unforgeable while either scheme holds, including after a quantum computer breaks Ed25519. The schema is inside the signed hash, and the verifier’s key type fixes the schema it accepts, so a hybrid trail cannot be passed off as an Ed25519-only one: verify it with the HybridVerifyingKey.

A verifier detects any edited, inserted, deleted, reordered, or re-signed record. Removing records from the end is detected only against a checkpoint held somewhere the writer cannot change, such as a WORM bucket, a ticketing system, or a transparency log (decision D-008): publish AuditChain.checkpoint() there periodically and pass it to the verifier.

Records contain only the allowlisted, secret-free event fields. The signing key belongs to the audit component, not to the data path.

class cryptography_suite.audit.chain.AuditChain(writer, signing_key, *, chain_id, resume_from=None)

An AuditSink that writes signed, hash-chained record lines.

Parameters:
checkpoint()

Return the position of the last record written.

Return type:

AuditCheckpoint

exception cryptography_suite.audit.chain.AuditChainError(reason, line)

Verification failure with its reason and the 1-based line number.

Parameters:
Return type:

None

class cryptography_suite.audit.chain.AuditChainFailure(*values)
class cryptography_suite.audit.chain.AuditCheckpoint(chain_id, sequence, hash)

The position of a record: publish it somewhere the writer cannot edit.

Parameters:
  • chain_id (str)

  • sequence (int)

  • hash (str)

class cryptography_suite.audit.chain.AuditRecordWriter(*args, **kwargs)

Durable storage for record lines, such as an append-only file.

class cryptography_suite.audit.chain.HybridSigningKey(ed25519_key, mldsa_key)

Ed25519 and ML-DSA-65 (FIPS 204) signing every record together.

The signature is the Ed25519 signature followed by the ML-DSA-65 signature (with a fixed signing context), 3,373 bytes in all. ML-DSA needs a backend that implements it; generate() raises cryptography.exceptions.UnsupportedAlgorithm otherwise.

Parameters:
  • ed25519_key (ed25519.Ed25519PrivateKey)

  • mldsa_key (mldsa.MLDSA65PrivateKey)

class cryptography_suite.audit.chain.HybridVerifyingKey(ed25519_key, mldsa_key)

The public half of a HybridSigningKey.

Parameters:
  • ed25519_key (ed25519.Ed25519PublicKey)

  • mldsa_key (mldsa.MLDSA65PublicKey)

verify(signature, message)

Raise InvalidSignature unless both signatures verify.

Parameters:
  • signature (bytes)

  • message (bytes)

Return type:

None

cryptography_suite.audit.chain.verify_audit_chain(lines, public_key, *, chain_id, start=None, expected_end=None)

Verify record lines and return the checkpoint of the last one.

start verifies a segment that continues after a known checkpoint (for example after log rotation). expected_end is a checkpoint held outside the writer’s control; the trail must contain that exact record, which detects records removed from the end up to that point. Records after it are verified like any other.

The key type fixes the schema: an Ed25519 key accepts only cs-audit-chain/1 records and a HybridVerifyingKey only cs-audit-chain/2 records.

Parameters:
Return type:

AuditCheckpoint

Audit fan-out

Deliver every audit event to several sinks (RFC-0028).

A service usually wants the tamper-evident audit chain and metrics. A Protector takes one audit_sink; FanOutAuditSink passes each event to every configured sink in order. Every sink is attempted even when an earlier one fails, so a metrics outage never costs an audit record; the first failure is then re-raised, and the protector’s audit policy decides what it means (with audit_required, the operation fails).

class cryptography_suite.audit.fanout.FanOutAuditSink(*sinks)

An AuditSink that forwards each event to every given sink.

Parameters:

sinks (AuditSink)

COSE-HPKE

COSE-HPKE: HPKE encryption in COSE (draft-ietf-cose-hpke-27).

COSE (RFC 9052) is the CBOR object format of constrained and embedded systems, WebAuthn, mobile driver’s licences (ISO 18013-5), EU digital identity wallets, SUIT firmware updates, and C2PA content credentials. COSE-HPKE adds HPKE (RFC 9180) public-key encryption to it. This module reads and writes those messages with the same pyca/cryptography keys the SDK’s HPKE recipients use, so data can move between a v4 deployment and any COSE-HPKE implementation:

  • Integrated Encryption (encrypt0(), decrypt0()): one recipient, a COSE_Encrypt0 whose ciphertext is HPKE’s own, with the Enc_structure as HPKE additional data.

  • Key Encryption (encrypt(), decrypt()): a COSE_Encrypt whose content is encrypted once under a random content key, which HPKE wraps to each recipient with the Recipient_structure as HPKE info.

  • Keys (encode_key(), decode_key()): COSE_Key encoding with the section 3.4 rules.

All sixteen ciphersuites, HPKE-0 to HPKE-7 in both modes, are implemented in the base and pre-shared-key modes. The algorithm identifiers and the ek and psk_id header labels are the values the draft gives while IANA assignment is pending, the same values its examples use. Ciphertext is always attached; a detached payload is rejected as unsupported.

Errors follow the SDK: a malformed message raises EnvelopeError, a message that cannot be opened with the given key and inputs raises AuthenticationError without saying why, and invalid arguments raise TypeError or ValueError.

cryptography_suite.cose.MAX_INPUT_BYTES: Final = 65536

The longest HPKE info, recipient_extra_info, kid, or psk_id.

cryptography_suite.cose.MAX_MESSAGE_BYTES: Final = 68157440

The largest COSE message accepted for decoding.

class cryptography_suite.cose.ContentAlgorithm(*values)

Content encryption algorithms for COSE_Encrypt (RFC 9053).

class cryptography_suite.cose.CoseKey(key, algorithm, kid)

A decoded COSE_Key: the key, and its alg and kid if present.

Parameters:
  • key (EllipticCurvePublicKey | X25519PublicKey | X448PublicKey | EllipticCurvePrivateKey | X25519PrivateKey | X448PrivateKey)

  • algorithm (HpkeAlgorithm | None)

  • kid (bytes | None)

class cryptography_suite.cose.HpkeAlgorithm(*values)

COSE-HPKE ciphersuites (draft-ietf-cose-hpke-27 section 4).

HPKE_n is Integrated Encryption (COSE_Encrypt0) and HPKE_n_KE Key Encryption (a COSE_Encrypt recipient); an identifier is valid only in its own mode.

HPKE_0 = 35

DHKEM(P-256, HKDF-SHA256), HKDF-SHA256, AES-128-GCM.

HPKE_1 = 37

DHKEM(P-384, HKDF-SHA384), HKDF-SHA384, AES-256-GCM.

HPKE_2 = 39

DHKEM(P-521, HKDF-SHA512), HKDF-SHA512, AES-256-GCM.

HPKE_3 = 41

DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM.

HPKE_4 = 42

DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20-Poly1305.

HPKE_5 = 43

DHKEM(X448, HKDF-SHA512), HKDF-SHA512, AES-256-GCM.

HPKE_6 = 44

DHKEM(X448, HKDF-SHA512), HKDF-SHA512, ChaCha20-Poly1305.

HPKE_7 = 45

DHKEM(P-256, HKDF-SHA256), HKDF-SHA256, AES-256-GCM.

property key_encryption: bool

Whether this is a Key Encryption (_KE) identifier.

class cryptography_suite.cose.Recipient(public_key, algorithm, kid=None, extra_info=b'', psk=None, psk_id=None)

One HPKE Key Encryption recipient of encrypt().

algorithm must be a _KE suite matching public_key. extra_info is the Recipient_structure’s recipient_extra_info (section 3.3.4): bound into the key derivation but never transmitted, so the reader must supply the same bytes.

Parameters:
  • public_key (EllipticCurvePublicKey | X25519PublicKey | X448PublicKey)

  • algorithm (HpkeAlgorithm)

  • kid (bytes | None)

  • extra_info (bytes)

  • psk (bytes | None)

  • psk_id (bytes | None)

cryptography_suite.cose.decode_key(data)

Decode a COSE_Key for a COSE-HPKE suite and check it (section 3.4).

EC2 keys on P-256, P-384, or P-521 and OKP keys on X25519 or X448 are accepted. Any alg must be a COSE-HPKE suite for the key’s curve; any key_ops must be exactly [derive bits] on a private key and empty on a public key; and the public parts of a private key must match it. Raises ValueError for anything else.

Parameters:

data (bytes)

Return type:

CoseKey

cryptography_suite.cose.decrypt(message, private_key, *, kid=None, extra_info=b'', external_aad=b'', psk=None)

Decrypt a COSE_Encrypt with an HPKE Key Encryption recipient.

Each HPKE recipient whose suite matches the key (and, when kid is given, whose key identifier equals it) is tried in order; recipients of other content key distribution methods are skipped. psk selects the recipients written in the PSK mode.

Parameters:
  • message (bytes)

  • private_key (EllipticCurvePrivateKey | X25519PrivateKey | X448PrivateKey)

  • kid (bytes | None)

  • extra_info (bytes)

  • external_aad (bytes)

  • psk (bytes | None)

Return type:

bytes

cryptography_suite.cose.decrypt0(message, private_key, *, external_aad=b'', info=b'', psk=None)

Decrypt a COSE_Encrypt0 written with an Integrated Encryption suite.

The message must name its algorithm in the protected header. psk is required exactly when the message carries a psk_id.

Parameters:
  • message (bytes)

  • private_key (EllipticCurvePrivateKey | X25519PrivateKey | X448PrivateKey)

  • external_aad (bytes)

  • info (bytes)

  • psk (bytes | None)

Return type:

bytes

cryptography_suite.cose.encode_key(key, *, algorithm=None, kid=None)

Encode key as a COSE_Key (section 3.4 and figure 1).

A private key is encoded with its public coordinates and key_ops: [derive bits]; pass key.public_key() to share it. algorithm, when given, must match the key and restricts its use to that suite.

Parameters:
  • key (EllipticCurvePublicKey | X25519PublicKey | X448PublicKey | EllipticCurvePrivateKey | X25519PrivateKey | X448PrivateKey)

  • algorithm (HpkeAlgorithm | None)

  • kid (bytes | None)

Return type:

bytes

cryptography_suite.cose.encrypt(plaintext, recipients, *, content_algorithm=ContentAlgorithm.A256GCM, external_aad=b'', tagged=True)

Encrypt plaintext once for any number of recipients (section 3.3).

A fresh content key encrypts the content with content_algorithm; HPKE wraps it to each recipient, binding the content algorithm and the recipient’s protected header through the Recipient_structure.

Parameters:
Return type:

bytes

cryptography_suite.cose.encrypt0(plaintext, public_key, *, algorithm, kid=None, external_aad=b'', info=b'', psk=None, psk_id=None, tagged=True)

Encrypt plaintext to one recipient as a COSE_Encrypt0 (section 3.2).

algorithm must be an Integrated Encryption suite matching the key. kid and psk_id go in the protected header, so they are authenticated. info is HPKE’s info input and external_aad the COSE externally supplied data; both must be given again to decrypt. Supplying psk (at least 32 bytes) and psk_id selects the PSK mode.

Parameters:
  • plaintext (bytes)

  • public_key (EllipticCurvePublicKey | X25519PublicKey | X448PublicKey)

  • algorithm (HpkeAlgorithm)

  • kid (bytes | None)

  • external_aad (bytes)

  • info (bytes)

  • psk (bytes | None)

  • psk_id (bytes | None)

  • tagged (bool)

Return type:

bytes

Migration

Migration of v3 data and keys into v4 (RFC-0008, RFC-0033, RFC-0034).

migrate_legacy() moves one legacy file into one v4 envelope without writing plaintext anywhere:

  1. Permission. The protector’s policy must name the legacy format, and its migration deadline must not have passed.

  2. Decrypt and re-encrypt. The declared adapter decrypts the legacy file as a stream, straight into Protector.seal_stream(), which seals it under a fresh data key. The legacy tag is verified at the end of the input, before the envelope can be published.

  3. Independent verification. While the envelope is written, a second thread reads the same bytes through Protector.open_stream() and compares a keyed digest and the length of their plaintext with the legacy plaintext’s. The destination is committed only if they match.

  4. Promotion. The destination sink publishes the envelope atomically.

  5. Receipt. A MigrationReceipt (cs-migration-receipt/1) records digests, sizes, keys, the policy, and the verification, and no secret, plaintext, context value, or path.

The source is never modified or deleted. A dry run performs every step, key-service calls included, and commits nothing.

v3 key material is handled by two more functions (RFC-0034). inventory_keystore() describes a v3 local keystore without decrypting any key, and reports keys left unencrypted, passwords that 3.0.0 stored next to their keys, and weak key-file encryption. import_legacy_key() registers one v3 key file with an HPKE provider, the only v4 provider that holds local keys, if the policy permits it and the provider can use the key; it never exports key material.

cryptography_suite.migration.INVENTORY_SCHEMA: Final = 'cs-key-inventory/1'

Schema of KeystoreInventory.to_json().

cryptography_suite.migration.KEY_IMPORT_SCHEMA: Final = 'cs-key-import-receipt/1'

Schema of KeyImportReceipt.to_json().

cryptography_suite.migration.UNENCRYPTED_KEY_GRANT: Final = 'pem-der-unencrypted'

The policy grant, beside pem-der, that admits an unencrypted private key: RFC-0008’s “exceptional migration policy”.

class cryptography_suite.migration.KeyImportReceipt(operation_id, purpose, source_sha256, source_bytes, encoding, private, encrypted, algorithm, fingerprint_sha256, key, wrapping_algorithm, public_key_text, policy_id, started_at, completed_at, warnings, schema_version='cs-key-import-receipt/1')

What import_legacy_key() did, with nothing secret in it.

Parameters:
  • operation_id (str)

  • purpose (str)

  • source_sha256 (str)

  • source_bytes (int)

  • encoding (str)

  • private (bool)

  • encrypted (bool)

  • algorithm (str)

  • fingerprint_sha256 (str)

  • key (KeyRef)

  • wrapping_algorithm (str)

  • public_key_text (str)

  • policy_id (str)

  • started_at (datetime)

  • completed_at (datetime)

  • warnings (tuple[str, ...])

  • schema_version (str)

to_json()

The receipt as canonical cs-key-import-receipt/1 JSON.

Return type:

str

class cryptography_suite.migration.KeyPurpose(*values)

What an imported v3 key becomes in v4 (RFC-0034).

HPKE_RECIPIENT = 'hpke-recipient'

an identity for a private key, a sealing-only recipient for a public key. Declare it only for a key that was used for key agreement or decryption, never for one that signed.

Type:

An HPKE recipient

class cryptography_suite.migration.KeystoreEntry(key_id, status, reason=None, name_sha256=None, file_sha256=None, file_bytes=None, encrypted=None, algorithm=None, fingerprint_sha256=None, verified=False, v3_type=None, created=None, name=None, v4_use=None, findings=())

One key of a v3 local keystore, as the inventory found it.

status is listed or quarantined; a quarantined entry has a reason and nothing else read from it. algorithm and fingerprint_sha256 are verified when they come from an unencrypted key itself; otherwise the fingerprint is the metadata’s claim. v4_use is hpke-recipient, none, or unknown (an encrypted key whose metadata does not say). findings are stable codes (RFC-0034). key_id is the file name without .pem; an entry whose name is not an allowed identifier is reported by name_sha256 instead, so an untrusted name is never echoed.

Parameters:
  • key_id (str | None)

  • status (str)

  • reason (str | None)

  • name_sha256 (str | None)

  • file_sha256 (str | None)

  • file_bytes (int | None)

  • encrypted (bool | None)

  • algorithm (str | None)

  • fingerprint_sha256 (str | None)

  • verified (bool)

  • v3_type (str | None)

  • created (str | None)

  • name (str | None)

  • v4_use (str | None)

  • findings (tuple[str, ...])

class cryptography_suite.migration.KeystoreInventory(operation_id, policy_id, started_at, completed_at, entries, ignored_entries, schema_version='cs-key-inventory/1')

What inventory_keystore() found, with nothing secret in it.

Parameters:
  • operation_id (str)

  • policy_id (str)

  • started_at (datetime)

  • completed_at (datetime)

  • entries (tuple[KeystoreEntry, ...])

  • ignored_entries (int)

  • schema_version (str)

to_json()

The inventory as canonical cs-key-inventory/1 JSON.

Return type:

str

class cryptography_suite.migration.MigrationReceipt(operation_id, dry_run, legacy_format, kdf, source_sha256, source_bytes, plaintext_bytes, envelope_sha256, envelope_bytes, recipients, policy_id, context_commitment_id, started_at, completed_at, verification, warnings, schema_version='cs-migration-receipt/1')

What a migration did, with nothing secret in it.

Parameters:
  • operation_id (str)

  • dry_run (bool)

  • legacy_format (str)

  • kdf (str)

  • source_sha256 (str)

  • source_bytes (int)

  • plaintext_bytes (int)

  • envelope_sha256 (str)

  • envelope_bytes (int)

  • recipients (tuple[KeyRef, ...])

  • policy_id (str)

  • context_commitment_id (str | None)

  • started_at (datetime)

  • completed_at (datetime)

  • verification (str)

  • warnings (tuple[str, ...])

  • schema_version (str)

to_json()

The receipt as canonical cs-migration-receipt/1 JSON.

Return type:

str

cryptography_suite.migration.import_legacy_key(provider, key_id, source, *, policy, purpose, password=None)

Register one v3 key file with an HPKE provider (RFC-0034).

The file is a pem-der key: a PKCS #8 private key, encrypted or not, or a SubjectPublicKeyInfo public key, in PEM or DER. A private key becomes an identity (HpkeRecipientProvider.add_identity()), a public key a recipient that can only be sealed to. Nothing is detected or retried: the structure comes from the PEM label or the DER shape, and the password is required exactly when the key is encrypted.

Parameters:
  • provider (HpkeRecipientProvider) – The provider to register the key with.

  • key_id (str) – The logical key name in that provider.

  • source (bytes | bytearray) – The key file, at most 64 KiB. It is never modified.

  • policy (Policy) – Must permit pem-der; an unencrypted private key also needs the pem-der-unencrypted grant. The provider and the key’s wrapping algorithm must be ones the policy allows.

  • purpose (KeyPurpose | str) – KeyPurpose.HPKE_RECIPIENT, the caller’s declaration that the key was used for key agreement or decryption.

  • password (bytes | bytearray | None) – The key file’s password, for an encrypted private key only.

Returns:

The receipt, with the key’s v4 reference and public key text.

Raises:
  • PolicyError – The policy does not permit the import now (LEGACY_DENIED), or forbids the provider or the algorithm (POLICY_DENIED).

  • AuthenticationError – The password does not decrypt the key.

  • EnvelopeError – The file is malformed, of an unsupported structure or encryption scheme, or too large.

  • ProviderError – An HPKE recipient cannot use this key type (CAPABILITY_UNSUPPORTED): only X25519 and EC P-384 can.

  • ValueError – A password is missing for an encrypted key or given for one that is not encrypted, or key_id or purpose is not valid.

Return type:

KeyImportReceipt

cryptography_suite.migration.inventory_keystore(directory, *, policy, include_names=False)

Describe a v3 local keystore without decrypting any key (RFC-0034).

Each <key id>.pem and its <key id>.json metadata become one KeystoreEntry. Unencrypted keys are parsed to verify their type and fingerprint; encrypted keys are described by their metadata, marked unverified. Links, other non-regular files, oversized files, and malformed keys are quarantined. Nothing is written, and a password found in metadata is reported, never read.

Parameters:
  • directory (str | PathLike[str]) – The keystore directory.

  • policy (Policy) – Must permit local-keystore (Policy.migration()).

  • include_names (bool) – Also report the names v3 stored in the metadata, which can identify people or systems; omitted by default.

Raises:
  • PolicyError – The policy does not permit local-keystore now (LEGACY_DENIED).

  • EnvelopeError – The directory has more than 10,000 entries (LIMIT_EXCEEDED).

  • OperationalError – The directory cannot be listed (IO_FAILED).

Return type:

KeystoreInventory

cryptography_suite.migration.migrate_legacy(protector, source, destination, *, legacy_format, password, context, kdf=None, backup_confirmed=False, cancel=None)

Move one v3 file into one verified v4 envelope (RFC-0008).

Parameters:
  • protector (Protector) – Seals the envelope. Its policy must permit the format (Policy.migration()) and its deadline must not have passed.

  • source (BinaryIO) – The legacy file. It is read once and never modified.

  • destination (TransactionalSink | None) – Where the envelope is published, such as a file_sink(); None for a dry run, which performs every step and publishes nothing.

  • legacy_format (LegacyFormat | str) – The format the caller declares; nothing is detected.

  • password (bytes) – The v3 password, as UTF-8 bytes.

  • context (EncryptionContext) – The encryption context of the new envelope.

  • kdf (LegacyKdf | None) – The key derivation; required for raw-aes and password-aes-v3, whose files do not record it.

  • backup_confirmed (bool) – The caller confirms a recoverable backup of the source exists; required unless this is a dry run.

  • cancel (Callable[[], bool] | None) – Polled while the file is processed.

Returns:

The receipt. Store it with the envelope.

Raises:
  • PolicyError – The policy does not permit the format now (LEGACY_DENIED), or no backup was confirmed (POLICY_DENIED).

  • AuthenticationError – The password is wrong, or the legacy file was changed.

  • EnvelopeError – The legacy file is malformed or too large.

  • MigrationError – The new envelope did not reopen to the same plaintext (MIGRATION_VERIFY_FAILED); nothing is published.

  • OperationalError – Writing failed, or the operation was cancelled.

  • ProviderError – A key service failed.

Return type:

MigrationReceipt

Lifecycle

Public key-lifecycle declarations.

class cryptography_suite.lifecycle.KeyRecord(logical_key_id, key, state, generation)

A key version’s lifecycle state within a logical key.

Parameters:
class cryptography_suite.lifecycle.KeyState(*values)

Lifecycle states of a key version (RFC-0006).

Legacy readers

Explicit readers for the retired v3 file formats (RFC-0008).

Nothing here is imported by the package root, and nothing is detected: each reader parses only the format the caller names. Use cryptography_suite.migration.migrate_legacy() to move a file into a v4 envelope; it verifies the result before publishing it. v3 key material has no public reader here: cryptography_suite.migration inventories keystores and imports key files under a policy (RFC-0034).

class cryptography_suite.legacy.LegacyAdapter(*args, **kwargs)

A migration adapter for one legacy format (RFC-0008).

property format: LegacyFormat

The format this adapter reads.

class cryptography_suite.legacy.LegacyFormat(*values)

Legacy formats named by RFC-0008.

csf-v2, csf-v1, raw-aes, and password-aes-v3 are encrypted content, read by open_legacy(). local-keystore and pem-der are key material, which open_legacy() refuses; they are handled by cryptography_suite.migration.inventory_keystore() and cryptography_suite.migration.import_legacy_key() (RFC-0034).

class cryptography_suite.legacy.LegacyKdf(algorithm, scrypt_n=16384, scrypt_r=8, scrypt_p=1, pbkdf2_iterations=100000, argon2_memory_kib=65536, argon2_iterations=3, argon2_lanes=1)

The password-based key derivation a v3 file was written with.

The defaults are v3’s. v3 read the Argon2 parameters from CRYPTOSUITE_ARGON2_* environment variables and never recorded them, so a deployment that changed them must declare its values here.

Parameters:
  • algorithm (str)

  • scrypt_n (int)

  • scrypt_r (int)

  • scrypt_p (int)

  • pbkdf2_iterations (int)

  • argon2_memory_kib (int)

  • argon2_iterations (int)

  • argon2_lanes (int)

derive(password, salt)

Derive the 32-byte AES key, exactly as v3 did.

Parameters:
  • password (bytes)

  • salt (bytes)

Return type:

bytearray

class cryptography_suite.legacy.LegacyReader(source, *, legacy_format, password, kdf, max_plaintext_bytes)

A readable stream of a legacy file’s plaintext, authenticated at EOF.

After read returns b"", the GCM tag has verified and source_sha256, source_bytes, and plaintext_bytes describe the input. Until then the plaintext is unauthenticated.

Parameters:
  • source (BinaryIO)

  • legacy_format (LegacyFormat)

  • password (bytes)

  • kdf (LegacyKdf | None)

  • max_plaintext_bytes (int)

read(size=-1)

Return up to size plaintext bytes (all of them for -1).

Parameters:

size (int)

Return type:

bytes

property finished: bool

Whether the input ended and its tag verified.

cryptography_suite.legacy.open_legacy(source, *, legacy_format, password, kdf=None, max_plaintext_bytes=17179869184)

Open a v3 file of the named format for reading its plaintext.

Parameters:
  • source (BinaryIO) – The legacy file, read once from its current position.

  • legacy_format (LegacyFormat | str) – The format the caller declares. Nothing is detected.

  • password (bytes) – The password, as the UTF-8 bytes v3 derived its key from.

  • kdf (LegacyKdf | None) – The key derivation. CSF files record the algorithm, and the argument may only add parameters to it; raw-aes and password-aes-v3 require it.

  • max_plaintext_bytes (int) – Refuse longer plaintext with LIMIT_EXCEEDED.

Raises:
  • AuthenticationError – The password is wrong, or the file was changed; raised by read at the end of the input.

  • EnvelopeError – The file is malformed (FORMAT_INVALID), of an unknown CSF version or a format without an adapter (FORMAT_UNSUPPORTED), or too large (LIMIT_EXCEEDED).

Return type:

LegacyReader