Streaming and range reads¶
seal and open work on bytes in memory, up to the policy’s
max_plaintext_bytes (16 MiB by default). Files, backups, and objects of any
size up to max_stream_bytes (100 GiB by default, 1 TiB at most) go through
the streaming methods instead, in bounded memory.
Setup¶
from pathlib import Path
from cryptography_suite import EncryptionContext, Policy, Protector
from cryptography_suite.providers.hpke import HpkeRecipientProvider, generate_private_key
from cryptography_suite.streaming import file_sink
provider = HpkeRecipientProvider()
key = provider.add_identity("ledger", generate_private_key())
policy = Policy(chunk_size=1024 * 1024)
protector = Protector(provider=provider, policy=policy, primary_key=key)
context = EncryptionContext({"tenant": "acme"}, purpose="ledger")
root = Path("data").resolve()
root.mkdir()
(root / "ledger.csv").write_bytes(b"date,amount\n" + b"2026-11-30,1200\n" * 200_000)
chunk_size is the plaintext size of each record. Larger records cost
fewer bytes of overhead (21 per record) and make range reads coarser; 64 KiB
to 1 MiB suits most data.
Seal a file¶
with open(root / "ledger.csv", "rb") as source:
sealed = protector.seal_stream(
source,
file_sink(
output_root=root,
relative_destination="ledger.csv.cse",
policy=policy,
source=source,
),
context=context,
)
print(sealed.chunk_count, sealed.plaintext_size)
A sink is output that becomes visible only when it is committed.
file_sink writes to an owned temporary file in the destination directory
and publishes it atomically, under its final name, after the last record.
If anything fails, including a crash, a full disk, or cancellation, no file
appears at the destination.
file_sink also refuses:
a destination outside
output_root(relative_destinationis treated as untrusted, and links are not followed);replacing an existing file, unless both
overwrite=Trueand the policy’sallow_overwriteare set;writing over its own input, when
sourceis given, even through a hard link.
Open a file¶
with open(root / "ledger.csv.cse", "rb") as sealed_file:
opened = protector.open_stream(
sealed_file,
file_sink(
output_root=root,
relative_destination="ledger-restored.csv",
policy=policy,
source=sealed_file,
),
context=context,
)
assert (root / "ledger-restored.csv").read_bytes() == (root / "ledger.csv").read_bytes()
print(opened.authentication_status) # verified
Each record is authenticated before its plaintext is written, and the output is committed only after the final record and the end of the input verify. Truncated, extended, reordered, or modified envelopes abort the sink, so a consumer never sees unauthenticated plaintext, not even a prefix of it.
Pipes, sockets, and standard output cannot be committed or rolled back, so they are not sinks: write to a file, or implement a sink for your storage (below).
Read a range¶
open_range decrypts any byte range while reading only the records that
cover it. A 64 KiB read from a 50 GiB object reads about one record, not the
whole object.
with open(root / "ledger.csv.cse", "rb") as sealed_file:
page = protector.open_range(sealed_file, offset=1_000_000, length=65_536, context=context)
assert page == (root / "ledger.csv").read_bytes()[1_000_000 : 1_000_000 + 65_536]
The source can be bytes, an Envelope, or any seekable binary file object,
including the file objects of object-store libraries that turn reads into
ranged requests.
Every returned byte is authenticated together with its position, and a range
that reaches the end authenticates the final record, so truncation cannot
pass as a short read. Records outside the range are not read, so a range
read does not prove that the rest of the envelope is intact; use open or
open_stream when you need that.
Rewrap a large envelope¶
rewrap_stream moves an envelope of any size to another key. It rewrites the
recipient section and copies every record unchanged while checking its
framing.
new_key = provider.add_identity("ledger", generate_private_key()) # a new version
with open(root / "ledger.csv.cse", "rb") as sealed_file:
protector.rewrap_stream(
sealed_file,
file_sink(
output_root=root,
relative_destination="ledger-rotated.csv.cse",
policy=policy,
source=sealed_file,
),
destination_key=new_key,
)
Cancel¶
Every streaming method takes cancel, a function polled between records.
When it returns True, the operation stops with
OperationalError(CANCELLED) and the sink is aborted.
import threading
from cryptography_suite.errors import OperationalError
stop = threading.Event()
stop.set() # for example, from a signal handler or a deadline
try:
with open(root / "ledger.csv", "rb") as source:
protector.seal_stream(
source,
file_sink(output_root=root, relative_destination="cancelled.cse", policy=policy),
context=context,
cancel=stop.is_set,
)
except OperationalError as error:
print(error.code) # CANCELLED
assert not (root / "cancelled.cse").exists()
Your own sink¶
Any object with max_write_size, write, commit, and abort is a
TransactionalSink. For an object store, stage the parts and publish only in
commit, for example by completing a multipart upload; abort discards
them.
import io
class MemorySink:
max_write_size = 4 * 1024 * 1024
def __init__(self) -> None:
self._parts = io.BytesIO()
self.published: bytes | None = None
def write(self, chunk: bytes) -> None:
self._parts.write(chunk)
def commit(self) -> None:
self.published = self._parts.getvalue()
def abort(self) -> None:
self._parts = io.BytesIO()
sink = MemorySink()
with open(root / "ledger.csv", "rb") as source:
protector.seal_stream(source, sink, context=context)
assert sink.published is not None
commit must make the whole output visible at once, or not at all;
abort must be safe to call more than once. If write or commit raises a
CryptographySuiteError, it reaches you unchanged; any other exception
becomes an OperationalError with code IO_FAILED, without its message,
so log the details inside your sink if you need them.