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_keyfirst, then each ofadditional_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 ofproviderandproviders.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_requiredis 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
Protectoris immutable after construction and safe to share between threads.- seal(plaintext, *, context)¶
Encrypt
plaintextinto a new envelope bound tocontext.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_bytesbytes. Useseal_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:
- open(envelope, *, context)¶
Verify
envelopecompletely 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
Envelopeor 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
envelopewithout 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:
- rewrap(envelope, *, destination_key, replace=None)¶
Move
envelopetodestination_keywithout re-encrypting it.A trusted key unwraps the data key, which is wrapped again for the destination, replacing one recipient:
the recipient
replacenames, 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
replacewhenever 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
Envelopeor 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 onereplacenames (KEY_NOT_FOUND), or a key service failed.
- Return type:
- 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(), includingreplace. 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:
source (BinaryIO)
destination (TransactionalSink)
destination_key (KeyRef)
replace (KeyRef | None)
cancel (Callable[[], bool] | None)
- Return type:
- seal_stream(source, destination, *, context, cancel=None)¶
Encrypt
sourceintodestinationin bounded memory.The plaintext is read in
policy.chunk_sizerecords, up topolicy.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:
source (BinaryIO) – A readable binary stream.
destination (TransactionalSink) – A
TransactionalSink, such asfile_sink().context (EncryptionContext) – Authenticated, never stored.
cancel (Callable[[], bool] | None) – Polled between records; returning
Truestops the operation withCANCELLED.
- 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:
- open_stream(source, destination, *, context, cancel=None)¶
Verify and decrypt
sourceintodestination.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
Truestops the operation withCANCELLED.
- Returns:
Metadata of the envelope, marked
verified.- Raises:
ProviderError – As for
open().OperationalError – Reading, writing, or committing failed, or the operation was cancelled.
- Return type:
- open_range(source, *, offset, length, context)¶
Return up to
lengthauthenticated plaintext bytes fromoffset.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;
openandopen_streamverify everything.- Parameters:
source (Envelope | bytes | bytearray | memoryview | BinaryIO)
offset (int)
length (int)
context (EncryptionContext)
- 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.sourcemay 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 (defaultPolicy()) bounds what is parsed.- Parameters:
- Return type:
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_idsofNonepermits any explicitly constructed provider and is rejected for theenterpriseprofile. 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:
- 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 ofFIPS_WRAPPING_ALGORITHMS), and aProtectorrefuses 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:
- classmethod development()¶
Any explicit provider, lower limits, never labeled production.
- Return type:
- 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(defaultPolicy()), such as a production policy; acustombase becomes themigrationprofile, and an enterprise or FIPS base keeps its profile.restrict()never adds legacy permission, so restricting by a policy without it removes it.
- restrict(overlay)¶
Return the intersection of
selfandoverlay.The result is never more permissive than either input. An empty provider intersection is rejected rather than silently denying all.
- permits_legacy_format(name, *, now)¶
Whether migrating
nameis permitted atnow(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
- 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.
purposeandtenant_idare shorthands for the keys of those names:EncryptionContext({"tenant": "acme"}, purpose="invoices")
Equality follows
Mappingsemantics, 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’smax_context_bytesbounds 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:
CryptographySuiteErrorProtected 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:
CryptographySuiteErrorCaller 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:
ExceptionBase 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:
CryptographySuiteErrorEnvelope 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:
StrEnumStable 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:
CryptographySuiteErrorExplicit 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:
CryptographySuiteErrorI/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:
CryptographySuiteErrorPolicy 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:
CryptographySuiteErrorNormalized 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:
key (KeyRef)
capabilities (frozenset[KeyCapability])
state (ProviderKeyState)
observed_at (datetime)
- 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
bindingbytes 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_keyunder the exact versionkeynames.Every call must produce a fresh wrap, bound to
binding.- Parameters:
data_key (ReadOnlySecret)
key (KeyRef)
binding (bytes)
request (ProviderRequest)
- Return type:
- unwrap_data_key(wrapped_key, *, binding, request)¶
Unwrap with the key and version
wrapped_keynames.Raise
AuthenticationErrorwhen the wrap is not bound tobindingor was changed.- Parameters:
wrapped_key (WrappedKey)
binding (bytes)
request (ProviderRequest)
- Return type:
- describe_key(key, *, request)¶
Resolve
keyto an immutable version, its state and capabilities.- Parameters:
key (KeyRef)
request (ProviderRequest)
- Return type:
- health_check(*, request)¶
Report whether the key service is reachable and configured.
- Parameters:
request (ProviderRequest)
- Return type:
- class cryptography_suite.providers.KeyRef(provider_id, key_id, version=None)¶
A reference to a key of one provider, optionally to one version.
key_idis 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 aversion, 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:
provider_id (str)
status (ProviderHealthStatus)
observed_at (datetime)
- 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
Protectorpasses to its providers.deadlineis when the whole operation must finish; providers should give their own calls no more than the time left.cancelreturnsTrueonce 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
SecretBufferprotocol.- Parameters:
value (bytes | bytearray | memoryview)
- classmethod adopt(buffer)¶
Take ownership of
bufferwithout copying it.- Parameters:
buffer (bytearray)
- Return type:
- 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_bytesis 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
KeyProviderthat 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:
- 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:
- 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
kemfrom 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_keyas PKCS #8 PEM, encrypted whenpasswordis 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
thresholdcustodian private keys withQuorumRecipientProvider.add_custodian_identity(); oras a distributed ceremony (RFC-0025), where no private key ever leaves its custodian: a
RecoveryCeremonyattached to the provider turns the first open attempt into oneShareRequestper custodian, each custodian runsrelease_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 oncethresholdreleases 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
KeyProviderthat needsthresholdofncustodians.- Parameters:
provider_id (str)
ceremony (RecoveryCeremony | None)
- add_quorum(key_id, custodians, *, threshold)¶
Register a quorum version; the newest one is what
key_idnames.- Parameters:
key_id (str)
custodians (Sequence[X25519PublicKey | EllipticCurvePublicKey | HybridPublicKey])
threshold (int)
- Return type:
- 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 therequests()to send, and succeeds onceaccept()has receivedthresholdreleases. Callclose()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:
- close()¶
Wipe every released share and forget the requests.
- Return type:
None
What one custodian needs to release one share, and nothing secret.
binding_digestis the SHA-256 of the envelope’s protected bytes, so a custodian can record exactly which envelope a release was for.token_ciphertextis 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)
Interpolate at zero from
(x, share)points with distinct nonzerox.- Parameters:
points (Sequence[tuple[int, bytes | bytearray]])
- Return type:
bytearray
Custodian side: decrypt only this custodian’s share for the coordinator.
coordinatoris theRecoveryCeremony.fingerprintthe 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; sharei(0-based) is the polynomial ati+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 aBranchKeyStore. 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_ttlseconds, can be limited tomax_usesoperations, and the least recently used are evicted beyondmax_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
BranchKeyRecordvalues (for example asBranchKeyRecord.to_json()text in a database).putmust 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
KeyProviderthat 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:
branch_id (str)
request (ProviderRequest | None)
- Return type:
- 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:
describe_keyresolves to an immutable, enabled version with the wrap and unwrap capabilities, under the provider’s own identifier;a wrapped data key names that exact key and version, and its opaque bytes do not contain the data key;
unwrap with the same binding returns exactly the data key;
unwrap with a different binding fails authentication (the binding is enforced, not just recorded);
unwrap of altered opaque bytes fails authentication;
two wraps of the same data key differ (no deterministic wrapping);
an unknown key is reported as
KEY_NOT_FOUND;health_checkreports 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.
keymust name a test key that can wrap and unwrap.missing_keynames a key that does not exist (default:keywith an unlikely identifier). RaisesProviderConformanceErrornaming the first check that fails.- Parameters:
provider (KeyProvider)
key (KeyRef)
missing_key (KeyRef | None)
request (ProviderRequest | None)
- 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
writeaccepts.
- write(chunk)¶
Append
chunkto 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_destinationon commit.output_rootis a trusted, existing absolute directory;relative_destinationis untrusted and must stay below it. Replacing an existing file requires bothoverwrite=Trueandpolicy.allow_overwrite. Whensourceis 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 supportswithand 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:
- 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/1event: 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
AuditEventrecords asProtectoroperations run.Each operation emits a
startedevent and then asucceededorfailedone, synchronously. When the policy setsaudit_required, an exception fromemitfails the operation withIO_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
AuditSinkthat writes signed, hash-chained record lines.- Parameters:
writer (AuditRecordWriter)
signing_key (ed25519.Ed25519PrivateKey | HybridSigningKey)
chain_id (str)
resume_from (AuditCheckpoint | None)
- checkpoint()¶
Return the position of the last record written.
- Return type:
- exception cryptography_suite.audit.chain.AuditChainError(reason, line)¶
Verification failure with its reason and the 1-based line number.
- Parameters:
reason (AuditChainFailure)
line (int)
- 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()raisescryptography.exceptions.UnsupportedAlgorithmotherwise.- 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
InvalidSignatureunless 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.
startverifies a segment that continues after a known checkpoint (for example after log rotation).expected_endis 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/1records and aHybridVerifyingKeyonlycs-audit-chain/2records.- Parameters:
lines (Iterable[str | bytes])
public_key (Ed25519PublicKey | HybridVerifyingKey)
chain_id (str)
start (AuditCheckpoint | None)
expected_end (AuditCheckpoint | None)
- Return type:
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).
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 theEnc_structureas 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 theRecipient_structureas HPKEinfo.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, orpsk_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
algandkidif 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_nis Integrated Encryption (COSE_Encrypt0) andHPKE_n_KEKey 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().algorithmmust be a_KEsuite matchingpublic_key.extra_infois the Recipient_structure’srecipient_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
algmust be a COSE-HPKE suite for the key’s curve; anykey_opsmust 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. RaisesValueErrorfor anything else.- Parameters:
data (bytes)
- Return type:
- 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
kidis given, whose key identifier equals it) is tried in order; recipients of other content key distribution methods are skipped.pskselects 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.
pskis required exactly when the message carries apsk_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
keyas a COSE_Key (section 3.4 and figure 1).A private key is encoded with its public coordinates and
key_ops: [derive bits]; passkey.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
plaintextonce 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:
plaintext (bytes)
recipients (Iterable[Recipient])
content_algorithm (ContentAlgorithm)
external_aad (bytes)
tagged (bool)
- 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
plaintextto one recipient as a COSE_Encrypt0 (section 3.2).algorithmmust be an Integrated Encryption suite matching the key.kidandpsk_idgo in the protected header, so they are authenticated.infois HPKE’s info input andexternal_aadthe COSE externally supplied data; both must be given again to decrypt. Supplyingpsk(at least 32 bytes) andpsk_idselects 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:
Permission. The protector’s policy must name the legacy format, and its migration deadline must not have passed.
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.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.Promotion. The destination sink publishes the envelope atomically.
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/1JSON.- 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.
statusislistedorquarantined; a quarantined entry has areasonand nothing else read from it.algorithmandfingerprint_sha256areverifiedwhen they come from an unencrypted key itself; otherwise the fingerprint is the metadata’s claim.v4_useishpke-recipient,none, orunknown(an encrypted key whose metadata does not say).findingsare stable codes (RFC-0034).key_idis the file name without.pem; an entry whose name is not an allowed identifier is reported byname_sha256instead, 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/1JSON.- 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/1JSON.- 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-derkey: 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 thepem-der-unencryptedgrant. 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_idorpurposeis not valid.
- Return type:
- cryptography_suite.migration.inventory_keystore(directory, *, policy, include_names=False)¶
Describe a v3 local keystore without decrypting any key (RFC-0034).
Each
<key id>.pemand its<key id>.jsonmetadata become oneKeystoreEntry. 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-keystorenow (LEGACY_DENIED).EnvelopeError – The directory has more than 10,000 entries (
LIMIT_EXCEEDED).OperationalError – The directory cannot be listed (
IO_FAILED).
- Return type:
- 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();Nonefor 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-aesandpassword-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:
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.
- 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, andpassword-aes-v3are encrypted content, read byopen_legacy().local-keystoreandpem-derare key material, whichopen_legacy()refuses; they are handled bycryptography_suite.migration.inventory_keystore()andcryptography_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
readreturnsb"", the GCM tag has verified andsource_sha256,source_bytes, andplaintext_bytesdescribe 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
sizeplaintext 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-aesandpassword-aes-v3require it.max_plaintext_bytes (int) – Refuse longer plaintext with
LIMIT_EXCEEDED.
- Raises:
AuthenticationError – The password is wrong, or the file was changed; raised by
readat 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: