← Back to section · Tutorials & Labs
Serializing PQC Keys and Ciphertexts: Design a Storage Format That Won't Bite You
liboqs hands you raw byte strings; the on-disk format is yours to design. This tutorial builds a self-describing container with an algorithm identifier and length prefixes, and covers versioning, permissions and cross-parameter-set discipline.
In the previous two tutorials, public keys, secret keys, ciphertexts and shared secrets flowed around in memory as byte strings. The moment you need to save them to disk, store them in a database or send them across a network, a problem appears: liboqs only computes the bytes — it defines no official file format. There is no PEM, no DER; the public key returned by generate_keypair is a fixed-length raw byte string. Responsibility for the format lies entirely with the application. This tutorial does exactly one thing: design a simple container format for a KEM key pair that does not plant landmines, and explain the discipline behind every choice.
First, what goes wrong with raw bytes written straight to disk
The laziest approach — write the public-key bytes to a file, read the whole file back later — works fine in a lab, but it plants three landmines. First, no algorithm identifier: faced with 1184 bytes a year from now, you cannot tell whether they are an ML-KEM-768 public key or something else; after a parameter-set upgrade, new code will decapsulate old files with the wrong parameters and — because of implicit rejection — produce a wrong result with no error. Second, no length information: multiple fields concatenated in one file cannot be split apart. Third, no version slot: change any byte of the layout and every existing file is invalidated at once. A self-describing container spends a few dozen header bytes to defuse all three.
The container format
The format has three parts: a fixed header (a 4-byte magic PQK1, whose last character doubles as the major version), the algorithm name (a 1-byte length followed by UTF-8 bytes, e.g. ML-KEM-768), and then a sequence of fields, each encoded as a 4-byte big-endian length prefix plus the raw bytes. On reading, verify the magic first, then read the algorithm name and compare it against the algorithm you intend to use, then slice out the fields by their length prefixes. The code below writes and reads back a key pair:
import oqs
import struct
MAGIC = b"PQK1" # magic number; the last character is the format major version
def pack_field(data: bytes) -> bytes:
"""Prefix a field with its 4-byte big-endian length."""
return struct.pack(">I", len(data)) + data
def save_keypair(path: str, alg: str, public_key: bytes, secret_key: bytes) -> None:
alg_bytes = alg.encode("utf-8")
blob = b"".join([
MAGIC,
struct.pack(">B", len(alg_bytes)), alg_bytes,
pack_field(public_key),
pack_field(secret_key),
])
# The file contains a secret key: tighten permissions to owner-only
import os
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as f:
f.write(blob)
def load_keypair(path: str, expected_alg: str):
with open(path, "rb") as f:
blob = f.read()
if blob[:4] != MAGIC:
raise ValueError("bad magic: not this format, or a newer version")
pos = 4
(alg_len,) = struct.unpack_from(">B", blob, pos); pos += 1
alg = blob[pos:pos + alg_len].decode("utf-8"); pos += alg_len
if alg != expected_alg:
raise ValueError(f"algorithm mismatch: file holds {alg}, expected {expected_alg}")
fields = []
while pos < len(blob):
(n,) = struct.unpack_from(">I", blob, pos); pos += 4
fields.append(blob[pos:pos + n]); pos += n
if len(fields) != 2:
raise ValueError("wrong field count: file is corrupt or truncated")
return fields[0], fields[1] # public_key, secret_key
Restoring a secret key relies on the secret_key parameter of the liboqs-python constructors: pass the secret-key bytes in and the object is back in a working state. The oqs.Signature constructor accepts the same parameter:
# Restore a KEM secret key: decap_secret works right away
with oqs.KeyEncapsulation(alg, secret_key=secret_key) as decapsulator:
shared_secret = decapsulator.decap_secret(ciphertext)
# Restore a signing key: sign works right away
with oqs.Signature(alg, secret_key=secret_key) as signer:
signature = signer.sign(message)
After loading, always cross-check the public- and secret-key lengths against the object’s details and refuse to proceed on any mismatch — for raw byte formats, length is the last line of defence; a wrong length means the file is corrupt, truncated, or belongs to a different algorithm.
Storing ciphertexts and signatures
Ciphertexts and signatures are a different class of object: they need no confidentiality, but they do need integrity and association management. Store ciphertexts with the same algorithm identifier and length prefixes, for the same reason — a system may hold ciphertexts from several parameter sets at once, and feeding an ML-KEM-768 ciphertext to an ML-KEM-1024 secret key yields a wrong shared secret with no error whatsoever. Signatures must be stored as a triple with the signed message and the signer’s public key, in the same database row or a linked set of fields, with the algorithm name as its own column so you can migrate by algorithm in bulk later.
When byte strings travel through text channels (JSON, config files, environment variables), encode them in Base64 and say so in the field name; hexadecimal doubles the size and is fit only for debug output. Whatever the encoding, after decoding always verify the length equals the expected value from details for that field, and fail loudly on mismatch instead of hoping the library will catch it for you.
Extra notes for database storage
If the storage medium is a database rather than files, the principles stay the same, but a few database-specific traps need avoiding. First, store raw bytes in a binary column type (such as BLOB), never in a text column: text columns pass through charset encodings and collation rules, and some byte sequences get rewritten or compared as equivalent — key material cannot survive that kind of “helpful” processing. Second, if you already have a container format, do not invent a second field-splitting scheme inside the database: store the whole container blob in one column, keep the algorithm name in a separate column purely for lookup and statistics, and always parse through the single container code path, so the file and database parsers can never drift apart. Third, think about backups separately: the secret-key column is the most sensitive data in the entire database, and backup files deserve no less protection than the key files themselves — the 0600 and encryption-at-rest requirements apply to backups equally. Together with the container discipline above, these three points give your key data one consistent, auditable set of rules whether it lives in files or in a database.
Common mistakes checklist
- Raw bytes with no algorithm identifier. The most dangerous failure mode of naive formats: after an upgrade, old data is silently misinterpreted.
- Assuming lengths never change. The three ML-KEM parameter sets have public keys of 800, 1184 and 1568 bytes; any hardcoded length in your code is a future bug — read them from
detailsor the C-sidelength_fields. - Secret-key files with default permissions. Default file creation often leaves files group- or world-readable; set 0600 explicitly and tighten the containing directory too.
- Persisting shared secrets long-term. A shared secret is session material: run it through a KDF and discard it. What deserves persistent storage is the secret key, not each negotiated secret.
- Promoting the lab format to production. This container has no encryption and no integrity protection; it is for local experiments. Real systems need mature key management and encryption of secret keys at rest.
Summary
Serialization boils down to one sentence: the library gives you bytes, and you are responsible for the identity of those bytes. A magic number with a version, an algorithm identifier, length prefixes, length validation and file permissions together take under a hundred lines of code, yet they decide whether your data can still be read back correctly a year from now. As a follow-up exercise, extend the same container discipline to signatures: design and implement pack/unpack functions for the triple of message digest, signature and public key.
Tags: liboqsSerializationKey ManagementProgramming