Custom providers

Any key service, HSM, or in-house key manager can protect envelopes once it is wrapped in a KeyProvider: four methods and an identifier. This page builds one around a local key-encryption key, then checks it with the conformance kit. A real provider replaces the AES-GCM calls with calls to its service.

The contract

Method

Must

provider_id

Return a stable reverse-DNS identifier. It is recorded in every envelope, so it never changes.

describe_key(key)

Resolve key to an immutable version, with its state (enabled, disabled, …) and capabilities (wrap, unwrap).

wrap_data_key(data_key, key, binding)

Wrap under exactly the version key names, freshly randomized each time, bound to binding.

unwrap_data_key(wrapped_key, binding)

Unwrap with exactly the key and version the wrapped key names; raise AuthenticationError when the binding differs or the bytes were changed.

health_check()

Report whether the service is reachable and configured.

binding is the envelope’s protected header. Binding the wrap to it, as authenticated data, an encryption context, or an authenticated digest, stops a wrapped key from being moved into another envelope. A provider never receives plaintext, the encryption context, or any key derived from the data key.

Each call receives a ProviderRequest with the operation’s deadline: give your own network calls no more than the time left, and do not retry inside the provider, since the Protector already retries transient failures within the policy’s budget.

An example

import os
from datetime import UTC, datetime

from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

from cryptography_suite import AuthenticationError, ErrorCode, KeyRef, ProviderError
from cryptography_suite.providers import (
    KeyCapability,
    KeyDescription,
    ProviderHealth,
    ProviderHealthStatus,
    ProviderKeyState,
    ProviderRequest,
    ReadOnlySecret,
    SecretBuffer,
    SecretBytes,
    WrappedKey,
)

ALGORITHM = "example-aes256gcm-bound"


class LocalKekProvider:
    """Wraps data keys under local 256-bit key-encryption keys, by version."""

    def __init__(self) -> None:
        self._keys: dict[str, dict[str, bytes]] = {}  # key_id -> version -> KEK

    @property
    def provider_id(self) -> str:
        return "com.example.local-kek"

    def add_version(self, key_id: str) -> KeyRef:
        versions = self._keys.setdefault(key_id, {})
        version = str(len(versions) + 1)
        versions[version] = AESGCM.generate_key(bit_length=256)
        return KeyRef(self.provider_id, key_id, version)

    def _kek(self, key_id: str, version: str | None) -> tuple[str, bytes]:
        versions = self._keys.get(key_id)
        if not versions:
            raise ProviderError(ErrorCode.KEY_NOT_FOUND)
        version = version or max(versions, key=int)  # the current version
        if version not in versions:
            raise ProviderError(ErrorCode.KEY_NOT_FOUND)
        return version, versions[version]

    def describe_key(self, key: KeyRef, *, request: ProviderRequest) -> KeyDescription:
        version, _ = self._kek(key.key_id, key.version)
        return KeyDescription(
            key=KeyRef(self.provider_id, key.key_id, version),
            capabilities=frozenset({KeyCapability.WRAP, KeyCapability.UNWRAP}),
            state=ProviderKeyState.ENABLED,
            observed_at=datetime.now(UTC),
        )

    def wrap_data_key(
        self, data_key: ReadOnlySecret, *, key: KeyRef, binding: bytes, request: ProviderRequest
    ) -> WrappedKey:
        version, kek = self._kek(key.key_id, key.version)
        nonce = os.urandom(12)
        view = data_key.readonly_view()
        try:
            ciphertext = AESGCM(kek).encrypt(nonce, bytes(view), binding)
        finally:
            view.release()
        return WrappedKey(
            provider_id=self.provider_id,
            key_id=key.key_id,
            version=version,
            wrapping_algorithm=ALGORITHM,
            opaque_bytes=nonce + ciphertext,
            metadata={},
        )

    def unwrap_data_key(
        self, wrapped_key: WrappedKey, *, binding: bytes, request: ProviderRequest
    ) -> SecretBuffer:
        if wrapped_key.wrapping_algorithm != ALGORITHM:
            raise ProviderError(ErrorCode.CAPABILITY_UNSUPPORTED)
        _, kek = self._kek(wrapped_key.key_id, wrapped_key.version)
        blob = wrapped_key.opaque_bytes
        try:
            data_key = AESGCM(kek).decrypt(blob[:12], blob[12:], binding)
        except InvalidTag:
            raise AuthenticationError() from None
        return SecretBytes(data_key)

    def health_check(self, *, request: ProviderRequest) -> ProviderHealth:
        return ProviderHealth(
            provider_id=self.provider_id,
            status=ProviderHealthStatus.HEALTHY,
            observed_at=datetime.now(UTC),
        )

Check it

verify_provider runs the checks the envelope format relies on against a test key: the version is immutable, the binding is enforced, altered bytes are rejected, wraps are randomized, unknown keys are reported as KEY_NOT_FOUND, and the health check names the provider.

from cryptography_suite.providers.conformance import verify_provider

provider = LocalKekProvider()
test_key = provider.add_version("conformance")
print(len(verify_provider(provider, test_key)))  # 9 checks passed

Run it in CI against a test key in every environment the provider supports. Then use the provider like any other:

from cryptography_suite import EncryptionContext, Policy, Protector

protector = Protector(
    provider=provider,
    policy=Policy(),
    primary_key=KeyRef(provider.provider_id, "conformance"),
)
context = EncryptionContext({"tenant": "acme"})
assert protector.open(protector.seal(b"hello", context=context), context=context) == b"hello"

Errors

Translate every failure of the service into a typed error, and never let SDK exceptions, messages, or payloads escape (raise ... from None):

Service condition

Raise

Throttled

ProviderError(ErrorCode.PROVIDER_RATE_LIMITED, retryable=True)

Timeout, or the operation’s deadline has passed

ProviderError(ErrorCode.PROVIDER_TIMEOUT, retryable=True)

Unreachable or a server error

ProviderError(ErrorCode.PROVIDER_UNAVAILABLE, retryable=True)

Credentials or permissions refused

ProviderError(ErrorCode.PROVIDER_AUTH_FAILED)

No such key or version

ProviderError(ErrorCode.KEY_NOT_FOUND)

Key version disabled or destroyed

PolicyError(ErrorCode.KEY_STATE_DENIED)

Wrong binding, altered wrapped key

AuthenticationError()

Only retryable=True errors with the three transient codes are retried. An exception that is not a typed error is treated as PROVIDER_UNAVAILABLE and is not retried.