Using QuantAegis
QuantAegis is a Rust toolkit for post-quantum key establishment and digital signatures. The SDK combines key encapsulation with authenticated encryption so you can send a message to someone who has published a recipient key.
| What do you want to do? | Start here |
|---|---|
| Add encryption and signing to an application and plan a key or algorithm change | Use the SDK |
| Encrypt an order for a recipient and recover its contents | Send an encrypted message |
| Check the publisher and contents of a release manifest | Sign a release manifest |
| Understand how key establishment, encryption, and signatures work | Cryptographic foundations |
| Choose a binding and look up its public types | Binding support |
| Look up a term or API name | Search the guide |
| Inspect the envelope format and the scope of testing | Architecture · Verification |
This version is a pre-1.0 evaluation release. Its public APIs may change, and an independent cryptographic audit is pending. See the security policy for the current maturity stage and verification coverage. Security policy
Search the guide
Search the English chapters for a term or API name, or browse binding support.
Use the SDK
The Rust quantaegis-sdk crate and the Python quantaegis package provide application APIs for envelope encryption, signing, algorithm policies, and key rotation. Use them when your application needs to keep data readable across a change in keys or algorithms.
| What do you want to do? | API to use |
|---|---|
| Encrypt a message or stored record for a recipient and bind it to an order ID | Use Envelope.seal and Envelope.open for authenticated encryption and associated data (AAD) |
| Switch to a new key or algorithm while keeping existing data readable | Use Envelope.open_with_keyring and SecurityPolicy to control the transition and cutover |
| Replace a release signing key and verify signatures from both periods | Use Python’s AgileSignature or Rust’s AgileSigningKey and AgileVerifyingKey |
| Import a public key from an existing tool | Decode its SPKI with the codec for that algorithm and convert the result to an SDK key |
| Handle capsules or signatures in a format defined by an existing protocol | Use that protocol’s implementation and the raw-key or raw-signature APIs for the required algorithm |
The high-level envelope and keyring APIs are available in Rust and Python. See binding support for the individual algorithms exposed through C and JS/WASM and the supported standard key formats.
Basic workflow
For encryption, the recipient generates a key pair and shares the public key through a trusted channel. The sender passes the public key, plaintext, and optional AAD to seal. The recipient uses their private key and the same AAD to open the result. For example, a different order ID causes the receiver to reject the message. The application keeps track of the AAD. Basic encryption example
Envelope uses QuantAegis’s QAEN v1 format. Use it where both sides can handle this format. inspect reads the algorithm from the envelope header. Use header metadata for routing and use the plaintext only after authenticated decryption succeeds. Python errors and policies · Envelope format in Rustdoc
Migrate stored envelopes to X-Wing
Suppose your service has existing orders encrypted with ML-KEM-768. By choosing policies separately for reads and writes, you can switch new writes to X-Wing while continuing to read stored data.
- Deploy both recipient keys to the readers first. During the transition, use
CRYPTREC_CATEGORY3_PLUSto allow both ML-KEM-768 and X-Wing. - Write new records with the X-Wing public key and
HYBRID_REQUIRED. - Authenticate and decrypt each stored record with its original AAD, then re-encrypt it with X-Wing. Check that you can open the replacement before writing it in place.
- Once you have accounted for the records and any backups you need, switch reads to
HYBRID_REQUIRED. The original ML-KEM envelope now raisesPolicyViolationError, even if its key is still in the ring.
Set up Python, then run the example from the repository root. It creates records in memory. Your application handles writes and replacement in its own data store.
python docs/examples/migrate_envelopes.py
from quantaegis import Envelope, PolicyViolationError, SecurityPolicy
transition = SecurityPolicy.CRYPTREC_CATEGORY3_PLUS
hybrid_only = SecurityPolicy.HYBRID_REQUIRED
# Stand in for an existing stored record and its recipient key.
old_public, old_secret = Envelope.generate_keypair("ml-kem-768", policy=transition)
old_aad = b"order=42"
old_packet = Envelope.seal(old_public, b"ship on Friday", aad=old_aad, policy=transition)
# Write new records with X-Wing. Keep both keys available for reads.
new_public, new_secret = Envelope.generate_keypair("x-wing", policy=hybrid_only)
keyring = [new_secret, old_secret]
new_aad = b"order=43"
new_packet = Envelope.seal(
new_public, b"ship on Monday", aad=new_aad, policy=hybrid_only
)
old_plaintext = Envelope.open_with_keyring(
keyring, old_packet, aad=old_aad, policy=transition
)
assert old_plaintext == b"ship on Friday"
assert Envelope.open_with_keyring(
keyring, new_packet, aad=new_aad, policy=transition
) == b"ship on Monday"
print("Read both records during migration")
# Re-encrypt the authenticated old record and check the replacement before saving it.
replacement = Envelope.seal(new_public, old_plaintext, aad=old_aad, policy=hybrid_only)
assert Envelope.open(
new_secret, replacement, aad=old_aad, policy=hybrid_only
) == old_plaintext
print("Re-encrypted the old record with X-Wing")
try:
Envelope.open_with_keyring(keyring, old_packet, aad=old_aad, policy=hybrid_only)
except PolicyViolationError:
print("Rejected the original ML-KEM envelope after cutover")
else:
raise AssertionError("Expected the hybrid-only policy to reject the old envelope")
Run the same migration in Rust
The Rust example uses AgileKeyPair, SecurityPolicy, and quantaegis_core::Error.
cargo run --locked -p quantaegis-sdk --example envelope_migration
//! Migrate an existing ML-KEM envelope to X-Wing and enforce the new policy.
use quantaegis_core::{Error, Result};
use quantaegis_sdk::{AeadAlgorithm, AgileKeyPair, Envelope, KemAlgorithm, SecurityPolicy};
fn main() -> Result<()> {
let transition = SecurityPolicy::CryptrecCategory3Plus;
let hybrid_only = SecurityPolicy::HybridRequired;
let old = AgileKeyPair::generate(transition, KemAlgorithm::MlKem768)?;
let new = AgileKeyPair::generate(hybrid_only, KemAlgorithm::XWing)?;
let aad = b"order=42";
let old_packet = Envelope::seal(
transition,
&old.public,
AeadAlgorithm::Aes256Gcm,
b"ship on Friday",
aad,
)?;
let keyring = [&new.secret, &old.secret];
let plaintext = Envelope::open_with_keyring(transition, &keyring, &old_packet, aad)?;
assert_eq!(plaintext, b"ship on Friday");
let replacement = Envelope::seal(
hybrid_only,
&new.public,
AeadAlgorithm::Aes256Gcm,
&plaintext,
aad,
)?;
assert_eq!(
Envelope::open_with_keyring(hybrid_only, &keyring, &replacement, aad)?,
plaintext
);
assert_eq!(
Envelope::open_with_keyring(hybrid_only, &keyring, &old_packet, aad),
Err(Error::PolicyViolation)
);
println!("Opened the X-Wing replacement and rejected the old envelope");
Ok(())
}
Rotate a release signing key
This example switches a publisher from ML-DSA-65 to MLDSA65-Ed25519-SHA512. Distribute the new verification key through a trusted channel before publishing releases signed with it. During the transition, verifiers keep both verification keys and pass the same ctx when checking either signature. When signing an actual file, the publisher and verifier use the same file bytes.
python docs/examples/rotate_signing_keys.py
from quantaegis import AgileSignature, PolicyViolationError, SecurityPolicy
transition = SecurityPolicy.CRYPTREC_CATEGORY3_PLUS
hybrid_only = SecurityPolicy.HYBRID_REQUIRED
context = b"release-manifest-v1"
old_verify, old_sign = AgileSignature.generate_keypair("ml-dsa-65", policy=transition)
old_manifest = b"release=1.0"
old_signature = AgileSignature.sign(
old_sign, old_manifest, ctx=context, policy=transition
)
new_verify, new_sign = AgileSignature.generate_keypair(
"mldsa65-ed25519-sha512", policy=hybrid_only
)
new_manifest = b"release=2.0"
new_signature = AgileSignature.sign(
new_sign, new_manifest, ctx=context, policy=hybrid_only
)
# Distribute the updated set of trusted verification keys before the cutover.
trusted_keys = [new_verify, old_verify]
for manifest, signature in (
(old_manifest, old_signature),
(new_manifest, new_signature),
):
algorithm = AgileSignature.verify_with_keyring(
trusted_keys, manifest, signature, ctx=context, policy=transition
)
print(f"Verified with {algorithm}")
AgileSignature.verify_with_keyring(
trusted_keys, new_manifest, new_signature, ctx=context, policy=hybrid_only
)
try:
AgileSignature.verify_with_keyring(
trusted_keys, old_manifest, old_signature, ctx=context, policy=hybrid_only
)
except PolicyViolationError:
print("Rejected the earlier ML-DSA-only signature after cutover")
else:
raise AssertionError("Expected the hybrid-only policy to reject the old signature")
HYBRID_REQUIRED restricts algorithms. To retire an earlier key for the same algorithm, remove it from the trusted keyring. If you still need to verify archived releases, retain the appropriate verification keys and policy for those releases. In this example, AgileSignature.sign returns a QuantAegis signature with an algorithm identifier. For raw ML-DSA signatures, see the individual signing API example. Rust signing API
Import an existing public key
When you receive an ML-KEM recipient key in SPKI PEM, first decode it into an algorithm name and raw public key. Then use AgileKem.public_from_raw to create the key representation accepted by Envelope.seal. This example generates a sample recipient key locally and exports the PEM that the sender would receive.
python docs/examples/import_recipient_key.py
from quantaegis import (
AgileKem,
Envelope,
MlKem768,
ml_kem_public_from_spki_pem,
ml_kem_public_to_spki_pem,
)
# The recipient exports a raw public key for distribution as SPKI PEM.
raw_public, raw_secret = MlKem768.keygen()
recipient_pem = ml_kem_public_to_spki_pem("ml-kem-768", raw_public)
# The sender loads a trusted copy of the PEM and adapts the key for Envelope.
algorithm, raw_public = ml_kem_public_from_spki_pem(recipient_pem)
recipient = AgileKem.public_from_raw(algorithm, raw_public)
packet = Envelope.seal(recipient, b"ship on Friday", aad=b"order=42")
# The recipient adapts the private key locally and recovers the message.
secret = AgileKem.secret_from_raw("ml-kem-768", raw_secret)
assert Envelope.open(secret, packet, aad=b"order=42") == b"ship on Friday"
print("Opened an envelope addressed to an imported SPKI key")
This example exchanges a public key. For private-key migration and the ML-DSA and SLH-DSA codecs, see supported algorithms and key formats.
This version is a pre-1.0 evaluation release. See the security policy for API maturity, independent audit status, and verification coverage.
Send an encrypted message
A sender wants to send shipping instructions to the recipient for order 42. The recipient keeps the secret key and gives the sender the public key through a channel that establishes whose key it is. The tutorial plays both roles in one process.
Setup
From a checkout of this repository, use Rust 1.88 or later and Python 3.10 or later. Create a virtual environment:
python -m venv .venv
Activate it with .\.venv\Scripts\Activate.ps1 in PowerShell or source .venv/bin/activate in bash. Then build the Python binding for this checkout and run the example.
python -m pip install .
python docs/examples/encrypt.py
Seal and open the order
from quantaegis import DecryptionError, Envelope
# Recipient
public_key, secret_key = Envelope.generate_keypair("ml-kem-768")
# Sender
order_id = b"order=42"
packet = Envelope.seal(public_key, b"ship on Friday", aad=order_id)
# Recipient
message = Envelope.open(secret_key, packet, aad=order_id)
assert message == b"ship on Friday"
print(message.decode())
# This check demonstrates the wrong-AAD case for a locally generated packet.
try:
Envelope.open(secret_key, packet, aad=b"order=99")
except DecryptionError:
print("Rejected a different order ID")
else:
raise AssertionError("Unexpected success with different AAD")
The first call to open recovers ship on Friday. The second raises DecryptionError because order 99 has different associated data. Both parties supply the order ID as exactly the same bytes. AAD is authenticated and managed separately from the packet. Put confidential values in the encrypted body. The example catches DecryptionError specifically to demonstrate an AAD mismatch. Incoming packets can also fail the earlier policy or key-algorithm checks. Receiver error handling
ML-KEM-768 establishes a shared secret. The SDK derives an encryption key and nonce, then protects the body with AES-256-GCM by default. Anyone with the recipient’s public key can create a new packet for them. To verify a publisher’s identity, use a signature. Signing tutorial · Python API
Sign a release manifest
A publisher signs a file containing release information. A user can check the file with the publisher’s verification key. Distribute that key through a trusted channel so the user can detect someone replacing both the file and its signature.
After setting up the Python environment, run this command from the repository root.
python docs/examples/sign.py
from quantaegis import MlDsa65, VerificationError
verify_key, signing_key = MlDsa65.keygen()
manifest = b"release=1.0"
context = b"release-manifest-v1"
signature = MlDsa65.sign(signing_key, manifest, ctx=context)
# Recipient
MlDsa65.verify(verify_key, manifest, signature, ctx=context)
print("Verified signature")
try:
MlDsa65.verify(verify_key, b"release=2.0", signature, ctx=context)
except VerificationError:
print("Rejected modified manifest")
else:
raise AssertionError("Unexpected success with a different message")
The first verification succeeds. The next call verifies a different version number with the original signature and raises VerificationError. The context identifies the intended use of the signature. Both parties must use the same context and exactly the same message bytes. For files, read the content in binary mode to preserve encodings and line endings. Python API
The Roles of Keys, Encryption, and Signatures
When choosing cryptographic technology, decide who should be able to read the data and how to verify who created it. For example, only the recipient needs to read an order’s delivery address. Anyone may read a published price list, but you may still want to verify who issued it.
| Goal | What is obtained from the input | QuantAegis example |
|---|---|---|
| Share key material with a remote party | The sender uses the recipient’s public key to generate a KEM ciphertext and a shared secret. The recipient derives the same secret from the private key and KEM ciphertext. | ML-KEM, X-Wing |
| Hide a message and detect changes | Encrypt the message with a shared key and nonce; the recipient checks the authentication tag before decrypting. | AEAD in Envelope |
| Verify the issuer of public data | Sign the message with a signing key; a verifier checks the public key, message, and signature together. | ML-DSA, SLH-DSA, composite signatures |
| Compute a short identifier for data | Anyone can compute the same digest from the same input. | SHA-3 |
When sending an envelope, the sender creates a shared secret with a KEM (key encapsulation mechanism), and the SDK derives an AEAD (authenticated encryption with associated data) key and nonce from it. The sender transmits the KEM ciphertext, encrypted message, and information needed for authentication. The recipient recovers the key material with the private key, checks associated data such as an order number, and opens the message.
Post-quantum cryptography is designed with attacks by large-scale quantum computers in mind. QuantAegis ML-KEM and ML-DSA are based on lattice problems; SLH-DSA is based on the security of hash functions. Users can generate keys and encrypt or sign data on ordinary computers.
Derive a shared secret with ML-KEM
ML-KEM is the key encapsulation mechanism defined in FIPS 203. The recipient generates an encapsulation key ek to share and a decapsulation key dk to keep private. The sender encapsulates with ek, sends the resulting ciphertext ct, and keeps the shared secret. The recipient decapsulates ct with dk to obtain the same 32-byte shared secret. The scheme’s security rests on the difficulty of recovering a secret from noisy equations over a lattice.
How it works · ML-KEM key and ciphertext flow
| Parameter set | Public key (bytes) | Ciphertext (bytes) | Python class |
|---|---|---|---|
| ML-KEM-512 | 800 | 768 | MlKem512 |
| ML-KEM-768 | 1184 | 1088 | MlKem768 |
| ML-KEM-1024 | 1568 | 1568 | MlKem1024 |
from quantaegis import MlKem768
ek, dk = MlKem768.keygen()
ct, sender_secret = MlKem768.encaps(ek)
assert MlKem768.decaps(dk, ct) == sender_secret
If a ciphertext of the correct length fails the internal consistency check, decapsulation returns an alternative 32-byte value derived from the private key and the ciphertext. This is called implicit rejection. The return value is 32 bytes in either case, with no separate indication of whether the check passed. When receiving encrypted application data, use the SDK’s Envelope.open, which also verifies the authentication tag. Encryption example · Rust API · FIPS 203
How does ML-KEM produce the same shared secret on both sides?
Alice wants to send Bob an invoice. How can they establish a key that only they know, even if someone can see everything they send? The arrows show what travels between them.
- Bob — Generate a public key and a private key. Keep the private key.
- Alice — Use Bob’s public key to create a ciphertext and a shared secret. Keep the shared secret.
- Bob — Use the private key to decode the expected-length ciphertext. Derive a candidate shared secret and re-encrypt the decoded value.
- Bob — Compare the received and regenerated ciphertexts in constant time. Select the candidate if they match, or a fallback derived from a private value and the received ciphertext otherwise. The result of the check stays with Bob.
- With an unaltered ciphertext and the corresponding key, Alice and Bob obtain the same 32-byte shared secret.
Alice can now encrypt the invoice with a key derived from their shared secret. Envelope example
Why introduce errors on purpose?
Given enough exact linear equations, you can solve for the unknowns by elimination. Suppose you add a small secret error to the result of each multiplication and publish only the remainder modulo a fixed number. Producing these equations is easy, but recovering the original secret is believed to be hard at suitable parameter sizes, even with many equations. This is the idea behind Learning with Errors (LWE). To keep keys and ciphertexts practical in size while accounting for quantum computers, Kyber’s designers used Module-LWE, which performs these calculations on vectors of polynomials. ML-KEM is the standardized scheme based on Kyber. Kyber design background · FIPS 203
Why can a slightly different value decode to the same bit?
Imagine a clock face numbered from 0 to 15. Place bit 0 at mark 0 and bit 1 at mark 8, on the opposite side of the clock. A reading of 7 or 9 is closest to 8, so it decodes to 1. A reading of 15 is one step around the clock from 0, so it decodes to 0. The two parties can compute different intermediate values as long as they round to the same mark at the end.
What cancels out when Bob uses the private key?
Set aside rounding from compression and call the internal message encoded on the clock face E. A is a public matrix, s is Bob’s secret, and r is a value Alice uses just this once. The superscript ᵀ denotes transposition, which swaps rows and columns.
| Operation | Main equation |
|---|---|
| Bob creates his public key | t = A·s + e, where e is a small error |
| Alice computes the two ciphertext components | u = Aᵀ·r + e₁ and v = tᵀ·r + e₂ + E |
| Bob computes the value to decode | v − sᵀ·u = E + eᵀ·r + e₂ − sᵀ·e₁ |
Try that subtraction on the clock face. Use a single number in place of the matrix and let all values wrap around at 16. With A = 5, Bob’s secret s = 2, and error e = 1, the public value t is 5 × 2 + 1 = 11. Alice puts a 1 bit at mark 8 and chooses r = 1, e₁ = 1, and e₂ = 0. She gets u = 6. For v, 11 + 8 = 19 wraps around to 3. Bob receives 6 and 3. He starts at mark 3, takes 2 × 6 steps backward, and lands at 7, which decodes to the original bit 1. This small example shows how cancellation and rounding work together.
In the last row, (A·s)ᵀ·r from v equals sᵀ·Aᵀ·r from the term being subtracted, so the two cancel. If the remaining error is small, Bob can recover the bits encoded in E. ML-KEM uses polynomials with 256 coefficients and works modulo 3329. The number-theoretic transform (NTT) changes the representation to speed up polynomial multiplication. ML-KEM-512, ML-KEM-768, and ML-KEM-1024 use vectors of 2, 3, and 4 polynomials respectively, with error distributions and compression tuned to each parameter set.
Why encrypt again after decoding?
Alice derives the shared secret and the randomness for the internal encryption from a fresh random value and the hash of Bob’s public key. Bob repeats the derivation using the value he decoded. He also derives a fallback from a separate secret value stored in the private key and the received ciphertext. He regenerates the ciphertext and compares it with the one he received in constant time. For a ciphertext of the expected length, a match selects the candidate shared secret, and a mismatch selects the fallback. In the usage example, decaps returns only the selected 32-byte value in either case. The comparison result stays private. Key generation and encapsulation example · FIPS 203 §§4–7
Combine two key establishment schemes with X-Wing
X-Wing is a hybrid KEM that combines ML-KEM-768 with the X25519 elliptic-curve key agreement function. The sender uses the recipient’s combined public key to produce an ML-KEM ciphertext and an ephemeral X25519 public key. Both parties use the combiner defined in the specification to derive the same 32-byte secret from the two shared values and the relevant public keys.
How it works · X-Wing key combination
QuantAegis implements revision 11 of the Internet-Draft. The public key is 1,216 bytes, the private key is 32 bytes, and the ciphertext is 1,120 bytes. When checking interoperability, confirm that the other implementation targets the same revision.
from quantaegis import XWing
ek, dk = XWing.keygen()
ct, shared = XWing.encaps(ek)
assert XWing.decaps(dk, ct) == shared
To encrypt application data, use Envelope.generate_keypair("x-wing") in the encryption tutorial’s key generation step. The SDK’s hybrid_required policy restricts KEMs to X-Wing. Encryption example · Rust API · X-Wing draft-11
How does X-Wing combine two key establishment schemes?
The recipient shares one public key and the sender sends back one ciphertext. X-Wing keeps that interface while pairing established elliptic-curve key agreement with lattice-based key establishment designed to resist quantum attacks. The goal is to protect the shared secret with two different computations so that it can remain secure if the security assumptions for one component fail. X-Wing draft-11
- Bob — Generate and keep a private seed.
- Bob — Derive both key pairs from the seed using SHAKE256. For X25519, b is the private scalar and bG is the public key.
- Alice — Split the received public key into its two components.
- Alice — Encapsulate with Bob’s ML-KEM-768 key to produce a ciphertext and shared value M.
- Alice — Generate an ephemeral X25519 key pair with private scalar a and public key aG.
- Alice — Compute shared value X with X25519(a, bG).
- Alice — Derive the shared secret with SHA3-256(M || X || aG || bG || XWingLabel). XWingLabel is a fixed public byte string.
- Bob — Expand the private seed again to recover both key pairs.
- Bob — Split the ciphertext into the ML-KEM ciphertext and aG.
- Bob — Decapsulate with the ML-KEM-768 private key. The output M′ is the fallback on implicit rejection.
- Bob — Compute shared value X with X25519(b, aG).
- Bob — Decapsulation returns only SHA3-256(M′ || X || aG || bG || XWingLabel). The ML-KEM comparison result stays private.
- With an unaltered ciphertext and the corresponding key, Alice and Bob obtain the same 32-byte shared secret.
What does each party send?
| ML-KEM-768 | X25519 | |
|---|---|---|
| What the recipient publishes | Encapsulation key | Recipient’s elliptic-curve public key |
| What the sender sends back | ML-KEM ciphertext | Ephemeral elliptic-curve public key |
| What the recipient computes | Output M′ by decapsulating with the private key | Shared value X from the recipient’s private scalar and the sender’s public key |
The first 1,088 bytes and the last 32 bytes of the 1,120-byte X-Wing ciphertext serve different purposes. The recipient decapsulates the first part with ML-KEM and passes its output M′ to the combiner, including the fallback if ML-KEM implicitly rejects. The second part encodes the public key used as input to the scalar multiplication below. How ML-KEM works
Why do both sides compute the same X25519 value?
Start with a fixed point G on the curve. Repeatedly adding that point to itself is called scalar multiplication. If the recipient’s private scalar is b, the public key is bG. If the sender’s ephemeral private scalar is a, the ephemeral public key is aG. The sender computes a(bG) and the recipient computes b(aG). Both routes reach the same point, and both parties derive the same X from its coordinate. The secrecy of this component relies on the difficulty of recovering a private scalar from the corresponding public point. X25519 uses the u-coordinate on Curve25519 for this calculation. RFC 7748 §6.1
What determines the final 32 bytes?
Both parties compute SHA3-256(ML-KEM output || X || ephemeral public key || recipient's curve public key || XWingLabel). The || operator concatenates the byte strings in order from left to right. The hash binds both component outputs to the selected curve public keys and to X-Wing through its dedicated label. The shared secret returned by XWing.encaps and XWing.decaps is the output of this hash. The input order and label follow draft-11. X-Wing API example · Combiner specification
Protect the message body with AES-256-GCM and ChaCha20-Poly1305
Authenticated encryption with associated data (AEAD) protects the message body so that only key holders can decrypt it. It also detects changes to the received data. In QuantAegis, Envelope derives the AEAD key and nonce from the KEM shared secret. You supply the body, the recipient, and any additional authenticated data (AAD), such as an order number.
How it works · AES-256-GCM encryption and tags · The ChaCha20 keystream and Poly1305
| SDK identifier | How it encrypts the body | How it detects changes |
|---|---|---|
aes-256-gcm | Uses AES with a 256-bit key in counter mode | Computes an authentication tag using GHASH |
chacha20-poly1305 | Combines the body with a keystream generated by ChaCha20 | Computes an authentication tag using Poly1305 |
Both algorithms use a 12-byte nonce and a 16-byte authentication tag in envelope v1. Both parties exchanging packets must support QuantAegis’s QAEN v1 format, including the header, key derivation, and AAD construction. The sender and recipient must supply matching AAD. Put confidential values in the body.
from quantaegis import Envelope
public_key, secret_key = Envelope.generate_keypair("x-wing")
packet = Envelope.seal(public_key, b"invoice", aead="chacha20-poly1305")
assert Envelope.open(secret_key, packet) == b"invoice"
Envelope format · NIST SP 800-38D (GCM) · RFC 8439 (ChaCha20-Poly1305)
How does AES-256-GCM protect an invoice and its tracking number together?
You want to keep the amount on an invoice private. The shipping system needs to see the tracking number, and that number needs to stay associated with the right invoice. With GCM, you can put the amount in the message body and the tracking number in the additional authenticated data (AAD). Before accepting the decrypted amount, the recipient uses the key to verify a short value called an authentication tag that covers both the ciphertext and the AAD. GCM specification
- Shared inputs Both parties hold the secret key. The protocol provides both with the public 96-bit nonce (unique per key) and tracking number (AAD).
-
Sender encrypts the amount Form
J₀by appending 1 as 32 bits to the nonce. Frominc32(J₀)onward, encrypt counter blocks with AES and XOR the output with the amount to get ciphertextC.Sender prepares tag inputs Encrypt the zero block with AES to get the GHASH keyH. EncryptJ₀to get the tag mask. - Sender makes the tag Run GHASH with
Hover the formatted AAD andC. XOR the result with the tag mask. - To the recipient The sender sends
Cand the tag. - Recipient checks the tag Rebuild
J₀,H, and the mask. Recompute the tag from the AAD andCand compare it with the received tag in constant time. -
Tags match Reproduce the keystream from
inc32(J₀)onward. XOR it withCand return the amount.Tags differ Return an authentication error.
Using a block cipher for a long message
AES-256 is a block cipher that uses a 256-bit key to map a 16-byte block to another 16-byte block. It arranges the bytes in a four-by-four grid and XORs in the first round key. It then runs 14 rounds that combine byte substitution, row shifts, mixing within columns, and XOR with another round key. The final round skips column mixing. AES derives all the round keys from the original key. FIPS 197
GCM uses a per-packet value called a nonce and a counter that increments for each block. For a 96-bit nonce (IV), GCM appends the 32-bit value 1 to the IV to form the initial counter block J₀. It reserves J₀ for masking the tag and encrypts the first message block using inc32(J₀), which increments the low 32 bits of J₀ to 2. Encrypting the message counter blocks with AES produces a byte sequence that only a key holder can reproduce. XOR combines this sequence with the message body to produce ciphertext. XOR gives 0 when two bits match and 1 when they differ. With four bits, for example, 1010 XOR 0110 = 1100. The recipient XORs the result with 0110 again to recover 1010. Each block uses a different counter value, so the blocks can be processed in parallel.
What happens if one ciphertext bit changes?
With XOR alone, flipping one bit of ciphertext flips the same bit in the decrypted message. GCM therefore feeds the AAD and ciphertext into GHASH, padding each separately with zeros to a block boundary and appending both original bit lengths. It processes each 128-bit block X using Y ← (Y XOR X) · H. Y starts at zero, and H is the AES encryption of an all-zero block. The multiplication takes place in a finite field where the product also fits in 128 bits.
To produce the tag, GCM XORs the final Y with the AES output for J₀. If someone swaps in a tracking number from a different order, the recipient’s tag calculation uses different AAD. Reusing a nonce with the same key repeats both the encryption keystream and the tag mask, so GCM requires a unique nonce for each use of a given key. QuantAegis runs a fresh encapsulation on each call to Envelope.seal and derives the key and nonce from the shared secret and header. Using authenticated encryption · Envelope format
How does ChaCha20-Poly1305 protect messages with addition and rotation?
For a short message or a long attachment, a sender and recipient who can produce the same secret byte sequence can combine it with the message body to encrypt it and apply it again to decrypt. ChaCha20 generates this sequence using integer operations that general-purpose CPUs handle efficiently. Poly1305 produces a tag that lets the recipient check that the ciphertext and the public associated data match the pair the sender sent. RFC 8439
- Shared inputs Both parties hold the secret key. The protocol provides both with the public 96-bit nonce (unique per key) and AAD.
-
Sender encrypts the body XOR the first 64 bytes with ChaCha20 block 1 and the final byte with the first byte of block 2 to get ciphertext
C.Sender derives a one-time key Read the first 32 bytes of ChaCha20 block 0 as two 16-byte little-endian integersrands. Clamprby clearing the specified bits. - Sender makes the tag Run Poly1305 over the formatted AAD and
Cwith the one-time key. - To the recipient The sender sends
Cand the tag. - Recipient checks the tag Reproduce the one-time key from block 0. Recompute the tag from the AAD and
Cand compare it with the received tag in constant time. -
Tags match Reproduce the keystream from counter 1. XOR it with
Cand return the body.Tags differ Return an authentication error.
Why identical plaintext blocks produce different ciphertext
ChaCha20 arranges sixteen 32-bit words in a four-by-four grid. The state holds constants, a 256-bit key, a block counter, and a 96-bit nonce. It mixes four words at a time with repeated additions that wrap on overflow, XORs, and bit rotations. A rotation wraps bits that move past one end of a word around to the other end. ChaCha20 alternates column and diagonal rounds for a total of 20 rounds, adds the initial state word by word, and produces 64 bytes.
For a 65-byte message, XOR the first 64 bytes with the output for block counter 1 and the final byte with the first output byte for counter 2. The recipient can reproduce the same keystream with the same key, nonce, and counter values. The first 32 output bytes for counter 0 become the one-time Poly1305 key for the packet. RFC 8439 §§2.3–2.6
What Poly1305 computes
Poly1305 authenticates the AAD, its padding to a 16-byte boundary, the ciphertext, its padding, and the original byte lengths of the AAD and ciphertext, in that order. Read the input in 16-byte blocks as little-endian integers and set a bit just above the 128 bits of each block to obtain n. Start the accumulator at zero and use the secret coefficient r to update it as accumulator ← (accumulator + n) × r mod (2¹³⁰ − 5). For two blocks, for example, the first value is multiplied by r twice and the second value once, so the order affects the result.
Poly1305 masks specific bits of r before using it. At the end, it adds s, the other half of the key, and takes the low 128 bits as the tag. The recipient runs the same calculation to verify the tag. Reusing a nonce with the same key repeats both the message keystream and the one-time values r and s. In the SDK, specify aead="chacha20-poly1305" to create an envelope with this algorithm. The SDK derives the key and nonce as part of the operation. Authenticated encryption API example · RFC 8439 §2.8
Sign data with ML-DSA
ML-DSA is the lattice-based signature scheme defined in FIPS 204. The signer uses the private key to produce a response tied to the message and its intended use, which is identified by the context. The verifier uses the public key to check that the response matches the message. For example, if you sign an update before distributing it, anyone with the corresponding public key can verify it independently.
How it works · ML-DSA challenge and response
| Parameter set | Public key (bytes) | Signature (bytes) | Python class |
|---|---|---|---|
| ML-DSA-44 | 1312 | 2420 | MlDsa44 |
| ML-DSA-65 | 1952 | 3309 | MlDsa65 |
| ML-DSA-87 | 2592 | 4627 | MlDsa87 |
The standard sign operation uses fresh randomness for each signature. Signatures for the same message can differ, so use verify to check validity. The context can be 0 to 255 bytes long and must match between signing and verification. Sign and verify a file · Rust API · FIPS 204
What can ML-DSA verify without revealing the private key?
A software publisher signs an update file once, and everyone who downloads it can verify it independently. Each verifier has the publisher’s public key, the file, and the signature. The ML-DSA signature carries a response that someone who knows the secret can produce for that message. Dilithium, the scheme on which ML-DSA is based, uses lattices to construct this response and puts the challenge and the response together in one signature. Dilithium design background
Creating a challenge without a verifier present
- The signer samples a mask y for this signature and uses it to compute a commitment w. The mask hides the secret in the response.
- The signer hashes a value that incorporates the message and its context together with the high bits of w. The result is the seed for a challenge c. The verifier can reconstruct this challenge later.
- The signer combines c, the secret, and y to form the response z. The verifier uses z, the public key, and a hint in the signature to reconstruct the high bits of w and check that the challenge seed matches.
Suppose someone changes a signed message from “version 7” to “version 8.” The verifier’s hash now incorporates “version 8,” so it no longer matches the challenge seed the signer derived from “version 7.” Changing the context likewise changes the verifier’s input.
Why the public key is enough to check the response
In a simplified form with rounding omitted, the public key is based on t = A·s₁ + s₂, the commitment is w = A·y, and the response is z = y + c·s₁. A is a public matrix, and s₁ and s₂ are short secret vectors, meaning their polynomial coefficients are small. Expanding the verifier’s expression A·z − c·t cancels the terms involving s₁ and leaves w − c·s₂.
The public key stores the high bits of t. The hint in the signature lets the verifier correct the high bits of coefficients that cross a rounding boundary. The signer also samples a new mask whenever checks such as the bound on the size of the response fail. This rejection step helps keep biases in published responses from leaking information about the secret. The verifier checks the bounds on z and the format of the hint before comparing hashes.
- Signer · Hash the message and contextCompute μ using the public-key hash stored in the signing key and the formatted message.
- Sample a mask yUse a seed derived from the signing key, signing randomness, and μ.
- Compute the commitmentw = A·y
- Generate the challenge seed c̃Hash μ with the encoded high bits of w.
- Derive the challenge cSample c from c̃.
- Compute the responsez = y + c·s₁
- Check the response and the low bitsIf z or the low bits of w − c·s₂ are out of bounds, return to mask sampling with a fresh y.
- Make the rounding hint hMark the high bits that change when subtracting c·t₀ from w − c·s₂ + c·t₀. Here t₀ is the low part of t.
-
Correction or hint check failsIf c·t₀ is out of bounds or h has too many set bits, return to mask sampling with a fresh y.Checks passPublish the encoded signature (c̃, z, h) for verification.
-
Verifier · Message and public keyRecompute μ from the message formatted with its context and the hash of the trusted public key.Verifier · Received signatureDecode c̃, z, and h. Reject an invalid hint encoding or an out-of-bounds response.
- Regenerate the challenge cSample it again from the received c̃.
- Recover the high bits w₁′Apply h to A·z − c·(t₁·213). The public key provides the seed for A and the high part t₁ of t.
- Recompute the challenge seed c̃′Hash μ with the encoding of w₁′.
- Compare challenge seedsAccept if c̃′ equals the received c̃. Otherwise reject.
ML-DSA-44, ML-DSA-65, and ML-DSA-87 all follow this verification process. Changes in the matrix dimensions and other parameters affect how many coefficients the scheme handles, how long the signatures are, and the estimated security. Parameter sets and usage · FIPS 204 key generation, signing, and verification
Use hash-based signatures with SLH-DSA
SLH-DSA links small hash-based signatures in a tree structure. The verifier reconstructs the root from the signature and message and checks it against the public key. Signers can use a signature scheme independent of lattices without keeping a persistent record of how many times they have used the key.
How it works · SLH-DSA hash chains and trees
QuantAegis implements the SHAKE parameter sets from FIPS 205. Each security level offers an s variant with shorter signatures and an f variant with faster signing. Choose based on the amount of data you can store or transmit and the processing time available to the signer.
| Family | s signature (bytes) | f signature (bytes) |
|---|---|---|
| SHAKE-128 | 7856 | 17088 |
| SHAKE-192 | 16224 | 35664 |
| SHAKE-256 | 29792 | 49856 |
In Python, try the same steps from the signing tutorial with SlhDsaShake128f in place of MlDsa65. In Rust, if stack space is limited, use sign_into with a caller-provided signature buffer. Signing example · Support by language · Rust API · FIPS 205
How does SLH-DSA sign using only hashes?
To prove later that you know a value, you can publish its hash first and reveal the original value when asked. The verifier only needs to compute the hash once. After you reveal the value, anyone can present it. SPHINCS+, the predecessor of SLH-DSA, combines many small signatures with limited uses so that a verifier can check them all with one public key. FIPS 205
Combining four leaves into one root
Consider a tree with leaves A, B, C, and D in that order. Hash adjacent leaves in pairs to form their parents. The left parent is H(A || B) and the right parent is H(C || D). Hash the two parents together to get the root. To show that B belongs to the tree for a published root, send A and the right parent along with B. The verifier can then recompute the root. Those sibling values form the authentication path. Even as the tree grows, the path carries just one value per level.
Three components link the message to the root
| Component | What the signature contains | What the verifier obtains |
|---|---|---|
| FORS (several small trees) | Secret values for the leaves selected by the message digest and the authentication path for each leaf | A FORS public key derived from the roots of those trees |
| WOTS+ (a signature based on hash chains) | An intermediate value from each chain, selected by a digit of the value being signed or of its checksum | A WOTS+ public key derived by advancing each chain to its endpoint |
| Hypertree (layers of XMSS trees) | A WOTS+ signature and authentication path at each layer | The bottom layer authenticates the FORS public key. Each higher layer authenticates the root directly below it until the verifier reaches the top root. |
WOTS+ chains rely on hashes being easy to compute in one direction and hard to reverse. For a chain with 15 steps, if the signature contains the value at step 6, the verifier applies 9 more steps to reach the endpoint. The verification includes checksum chains, which make it hard to adapt a signature to different content by advancing only some of the chains. The hash inputs also include addresses that distinguish positions in the trees and other parts of the computation.
Why the signer can work without a record of used leaves
The signature includes a per-message value R. In pure SLH-DSA, the message is formatted with its context under FIPS 205 §10.2.1. The signer computes a digest from R, the public key, and that formatted message. R is transmitted so the verifier can reconstruct the same digest. Bits of the digest select the FORS leaves and a position in the hypertree. The signer can regenerate the required secret values from a secret seed and their positions, avoiding the need to store entire trees or a record of used leaf indices. The tree sizes and other parameters account for the possibility that positions will repeat. Verification ends by checking the reconstructed root against the root in the trusted public key.
FORS, WOTS+, and XMSS hashes use the public seed and an address that identifies the operation and its position.
- Signer · Generate RApply PRFmsg to the secret SK.prf, fresh randomness (public seed for deterministic signing), and the message formatted with its context.
- Compute the digest and select positionsHash R, the public seed and root, and the formatted message with Hmsg to select the FORS leaves and the hypertree position.
- Create the FORS signatureRecord the selected leaf secrets derived from the secret seed and their authentication paths. Compute the FORS public key.
- Create the hypertree signatureSign the FORS public key at the bottom layer and the root below at each higher layer. Include a WOTS+ signature and an authentication path per layer.
- Assemble the signatureR || FORS signature || hypertree signature
-
Verifier · Message and contextFormat the message for pure SLH-DSA.Verifier · Received signatureReject a signature of the wrong length. Otherwise read R, the FORS signature, and the hypertree signature.
- Recompute the digestHash R, the trusted public key’s seed and root, and the formatted message with Hmsg.
-
FORS leaf indicesUse the first part of the digest to select one leaf in each FORS tree.Hypertree positionRead the tree and leaf indices from the rest of the digest to locate the bottom XMSS leaf and the associated FORS trees.
- Reconstruct the selected FORS leavesHash the leaf secrets carried in the FORS signature.
- Rebuild each FORS rootAt each level, the low bit of the node index puts the node first (0) or its path sibling first (1) in the hash input.
- Derive the FORS public keyHash the FORS roots together. Use the resulting key as the bottom layer’s WOTS+ input.
- Complete the layer’s WOTS+ hash chainsUse the digits of the current input and its checksum to advance the signature values to their endpoints.
-
XMSS leafHash the WOTS+ endpoints into the public key for this leaf.XMSS authentication pathTake one sibling per level from this layer’s signature.
- Rebuild the XMSS rootStart at the leaf. At each level, the low bit of the node index determines the left and right inputs to the hash.
- Move up the hypertreeAt each higher position, repeat WOTS+ recovery and path hashing with the root from the layer below as the new WOTS+ input.
- Compare the top rootAccept if the reconstructed root equals the root in the trusted public key. Otherwise reject.
QuantAegis’s SHAKE parameter sets vary in how they allocate tree height across layers, even at the same security level. The s variants prioritize smaller signatures, while the f variants prioritize faster signing. The sizes in the usage table reflect how many chain values and authentication path nodes appear in each signature. Supported parameter sets and usage · FIPS 205 §11, Table 2
Verify composite signatures with MLDSA65-Ed25519-SHA512
During a transition, you may want verification to require both ML-DSA-65 and Ed25519. RFC 10073 defines composite signatures for this purpose. QuantAegis supports the MLDSA65-Ed25519-SHA512 combination.
How it works · composite signatures bind two algorithms
The signing inputs are the message, the context, and the composite private key. The signer binds the SHA-512 hash of the message to a scheme-specific label and the context, then signs with both algorithms. The result is a 3,373-byte composite signature. The verifier uses the two corresponding public key components and accepts the signature only if both component signatures are valid.
In Python, generate a key pair with MlDsa65Ed25519.keygen(), then call sign and verify as in the signing tutorial. Use fresh keys dedicated to this composite scheme for both components. Reusing standalone signing keys or their seeds as component keys breaks key separation between schemes. When storing public keys or signatures, keep the composite algorithm identifier with them. Signing example · Rust API · RFC 10073
How are two signatures bound to the same software update?
Suppose you want to verify a software update’s publisher using both the established Ed25519 scheme and the post-quantum ML-DSA-65 scheme. MLDSA65-Ed25519-SHA512 defines a composite scheme with a dedicated pair of component keys, a shared procedure for preparing the message to sign, and a single rule for accepting the result. The verifier starts with one composite public key already associated with the publisher. RFC 10073
Giving both schemes the same message to sign
Suppose you use the same file for a test build and a production release. The file’s contents alone cannot distinguish those uses. The signer reduces the message to a 64-byte SHA-512 digest and prefixes it with information identifying the scheme and the intended use. The result is the message M′ passed to both signing algorithms.
M′ = common prefix || algorithm label || context length (1 byte) || context || SHA-512(message)
The || operator concatenates the byte strings. Changing the context from “test” to “release” changes M′ even when the file hash stays the same. ML-DSA-65 signs M′ with the algorithm label as its internal context. Ed25519 also signs M′. SHA-512 is a SHA-2 hash function that processes 1,024-bit blocks using 64-bit words. Even for a large file, the part of the input derived from the message has a fixed length for both signing operations. The SHA-2 structure in SHA-256 · FIPS 180-4
What Ed25519 checks
Start with the base point B. The public key is the point A obtained by multiplying B by the secret scalar a. The signer derives a nonce r from secret material and M′, then computes the point R = rB. The signer hashes R, A, and M′ to obtain a scalar k and computes S = r + k·a modulo the order of the group generated by B. Verification relies on the relation SB = R + kA. Expanding the left-hand side yields the same point as the right-hand side, so the verifier can check that the signature matches the message without knowing a. RFC 8032 §5.1
When the composite signature is accepted
Of the 3,373 bytes received, the first 3,309 are the ML-DSA-65 signature and the last 64 are the Ed25519 signature. The verifier reconstructs M′ from the message and context it has and verifies each signature with its corresponding public key component. Acceptance requires both checks to pass, so a forgery must satisfy both checks for the same signing input. Generate component keys specifically for this combination to keep standalone and composite signing separate. How to use composite signatures · How ML-DSA verifies signatures
- Signer · Hash the messageCompute the 64-byte SHA-512 digest.
- Bind the algorithm and contextM′ = fixed prefix || algorithm label || context length (1 byte) || context || SHA-512(message)
-
Sign with the ML-DSA-65 keySign M′ with the ML-DSA-65 private key and the algorithm label as the internal context.Sign with the Ed25519 keySign M′ with the Ed25519 private key.
- Publish the message and composite signatureThe 3,373-byte signature is the ML-DSA-65 signature (3,309 bytes) followed by the Ed25519 signature (64 bytes).
-
Verifier · Rebuild M′Hash the received message with SHA-512 and bind the same prefix, algorithm label, and expected context.Verifier · Read the two componentsSplit the received signature and the trusted composite public key into their ML-DSA-65 and Ed25519 components.
-
Check the ML-DSA-65 signatureVerify against M′ with the ML-DSA-65 public key and the algorithm label as the internal context.Check the Ed25519 signatureVerify against M′ with the Ed25519 public key.
- Accept only if both checks passReject if either signature fails verification.
Compute digests with SHA-3 and generate variable-length output with SHAKE
A hash function computes a digest from an input of arbitrary length. If a publisher provides a signed digest, you can recompute the digest from your local copy to check that you received the same contents. To establish that the digest came from the publisher, verify the signature or obtain it through a trusted channel.
How it works · The SHA-3 sponge · How SHAKE produces more output
SHA-3 and SHAKE use the Keccak sponge construction. They absorb input into an internal state and read output from it. SHA3-256 and SHA3-512 produce 32 and 64 bytes, respectively. SHAKE128 and SHAKE256 are extendable-output functions (XOFs), so the caller chooses the output length independently of the numbers in the names.
from quantaegis import sha3_256, shake256
digest = sha3_256(b"release manifest")
assert len(digest) == 32
assert len(shake256(b"release manifest", 48)) == 48
The SDK also uses SHAKE256 to derive a key from the envelope’s shared secret. In Rust, you can process a long input in chunks with update. Envelope format · Rust API · FIPS 202
How does SHA-3 turn a large file into a fixed-length digest?
Suppose you want to compare a digest authenticated by the publisher’s signature with one you compute as you read your local copy of a file. With SHA3-256, you compare 32 bytes whether the file is one byte or 1 GB. The algorithm is public, so anyone can recompute the digest. Deliberately producing another file with the same digest is believed to be hard. Using hashes
- Start with zero stateKeccak-f[1600] state: 200 bytes; rate (input/output area): 136 bytes; capacity (hidden mixing area): 64 bytes.
- Absorb block 1XOR message bytes 0–135 into the rate; permute the entire state.
- Absorb block 2Append SHA-3 domain-separation bits and final padding to the remaining 4 message bytes; XOR this padded rate block into state; permute again.
- Read digestRead 32 bytes from the rate. Output: the SHA3-256 digest; capacity is never read directly.
What does the sponge do when it absorbs data?
Keccak keeps a fixed-size internal state. It takes input through one part of the state and repeatedly mixes the entire state. This is called a sponge construction because it absorbs input and then squeezes out output. The SHA3-256 state is 200 bytes. It uses 136 bytes for input and output (the rate) and reserves the other 64 bytes for internal mixing (the capacity). The capacity is never read or written directly by the absorb or squeeze operations. FIPS 202 §§3–6
For a 140-byte file, XOR the first 136 bytes into the rate portion of the initially zero state and mix the entire state. Append the SHA-3 domain-separation bits and final padding to the remaining four bytes, then XOR and mix again. Read the first 32 bytes from the resulting state to get the digest. Reading the file in two 70-byte chunks gives the same result as long as you absorb the bytes in order and add the domain-separation bits and padding only once at the end.
What does mixing the state involve?
The Keccak-f[1600] permutation arranges twenty-five 64-bit words in a five-by-five grid and updates them over 24 rounds. In each round it XORs the words in each column and uses the result to update neighboring columns. It rotates the words and moves them to new positions, applies a nonlinear operation using neighboring words within each row, and XORs in a round constant. A change introduced through the rate spreads to the capacity, which remains hidden from direct input and output.
SHA3-512 uses the same permutation. Its rate is 72 bytes, its capacity is 128 bytes, and its output is 64 bytes. SHA3-512 and SHA3-256 therefore absorb input at different block boundaries starting with the first block. QuantAegis uses both functions in ML-KEM. Rust SHA-3 API · SHAKE and variable-length output
How does SHAKE produce as many bytes as you need?
You can send a short seed and have both parties generate the same public matrix, saving them from having to exchange the matrix itself. If they need more coefficients as they go, they can keep reading from the same byte stream. SHAKE is an extendable-output function (XOF) that defines a reproducible byte sequence for each input and lets the caller read as many bytes as needed. ML-KEM reads candidate values from SHAKE128 output and accepts those in range as matrix coefficients. How ML-KEM works · FIPS 203
- Start at zeroInitialize all 200 state bytes to zero. SHAKE256 rate: 136 bytes; the other 64 bytes are capacity.
- Pad the inputAppend the SHAKE domain suffix, then apply pad10*1 so the input ends on a 136-byte block boundary.
- Absorb each blockXOR each padded 136-byte block into the rate, then permute the full 200-byte state after every block, including the last. Only then begin squeezing.
- Squeeze first rate blockRead bytes 0–135 from the rate: 136 output bytes.
- Squeeze the next blockPermute the full state, then read 4 bytes from the new rate. Total output: 136 + 4 = 140 bytes.
What comes after the first 32 bytes?
If you request 32 bytes and 48 bytes from SHAKE256 in separate calls with the same input, the first 32 bytes of the longer output match the shorter output. SHAKE absorbs the entire input, then advances the read position through the resulting byte sequence. With the streaming API, reading 32 bytes and then another 16 bytes from the same reader gives you those same 48 bytes.
SHAKE256 has the same 200-byte state size as SHA-3, with 136 bytes available to read at a time. If you request 140 bytes, SHAKE256 reads 136 bytes from the state left after absorption, applies the permutation to the entire state again, and reads another four bytes from the new state. During squeezing, each additional permutation makes more output available from the same input. SHA-3 absorption and permutation
What do 128 and 256 mean?
SHAKE128 has a rate of 168 bytes and a capacity of 32 bytes. For SHAKE256, those sizes are 136 bytes and 64 bytes, respectively. The number in each name gives the target security strength in bits when the output is long enough. Choose the output length separately for your application. A one-byte output, for example, has only 256 possible values. SHA3-256 and SHAKE256 share the same rate and use different domain-separation bits during absorption. FIPS 202 §6 and Appendix A, Table 4
The QuantAegis envelope takes the key and nonce from SHAKE256 output computed using a purpose-specific label, the header, and the KEM shared secret. The shared secret is what keeps the derived values confidential. When generating a matrix from a public seed, anyone can reproduce the computation. SHAKE API example · Envelope key derivation
The roles of SHA-256, HMAC, and random bit generation
Key generation needs unpredictable random bytes. The Rust crate quantaegis-drbg exposes SHA-256, HMAC-SHA-256, and HMAC_DRBG, a deterministic random bit generator that uses HMAC-SHA-256 internally. When the tutorials generate keys through the SDK, the SDK uses the operating system’s randomness source.
How it works · SHA-256 block processing · The two hashes in HMAC-SHA-256 · HMAC_DRBG generation and reseeding
| Type | Inputs | Output |
|---|---|---|
Sha256 | Up to 2⁶¹ − 1 bytes of data | A 32-byte digest computed with SHA-256, a separate hash function from SHA-3 |
HmacSha256 | A shared key and data | An authentication code that another holder of the shared key can verify |
HmacDrbgSha256 | Entropy and other initialization inputs | A sequence of pseudorandom bytes generated while updating a secret internal state |
With HMAC, anyone holding the same secret key can generate and verify tags. To let third parties verify something you distribute with a public key, use digital signatures. The unpredictability of HMAC_DRBG output depends on the entropy supplied at initialization and reseeding. The Rust API documents initialization requirements, output limits, and reseed conditions. Digital signatures · Random bit generator crate API · NIST SP 800-90A Rev. 1
When using Sha256 or HmacSha256 incrementally, check the Result returned by try_update and try_finalize_into for state or input errors. HmacSha256::verify returns a Choice. Use .into_bool() when you need to act on a verification result that may be made public.
To pass HmacDrbgSha256 to a primitive as its CryptoRng, use an adapter. The adapter handles DrbgReseedRequired and supplies fresh entropy when a reseed is required, for example when cumulative output reaches the 16 KiB threshold.
What does SHA-256 compute at the end of a file?
If you want to hash a large file as you download it, rereading the file from the beginning for each chunk would be costly. SHA-256, a member of the SHA-2 family, keeps the result so far in eight 32-bit words and updates them with each new 64-byte block. The final eight words form the 32-byte digest. FIPS 180-4 §§5–6
- Pad the message
abc(3 bytes, 24 bits) +0x80(the 1 bit and seven following zero bits) + 52 zero bytes +00 00 00 00 00 00 00 18(length in bits) = one 64-byte block. - Prepare the blockRead 16 big-endian 32-bit words; expand them to 64 words.
- CompressRun 64 rounds on eight working words, starting from the initial eight-word state.
- Carry forwardAdd working words to the starting state word by word. That eight-word result becomes the starting state for the next 64-byte block.
- OutputAfter the final block, serialize the eight state words as the 32-byte SHA-256 digest of
abc.
Why even three bytes take up a block
The ASCII input abc is 24 bits long. Append a single 1 bit after the three bytes, pad with zeros, and store the original bit length, 24, in the final eight bytes. The result is exactly 64 bytes. With abcd, both the contents and the length change. If the current block has too little room for the length field, the padding extends into another block. In Rust, feed input to Sha256 with try_update and call try_finalize_into to apply the final padding and write the digest. QuantAegis hash API
How one block changes the eight-word state
Split each block into 16 words and expand them to 64 words using bit rotations, shifts, and additions. Copy the fixed initial state, or the previous state for later blocks, into eight working words. Mix them over 64 rounds, using one expanded word per round. The rounds combine a function that uses the bits of one word to choose between the corresponding bits of two others, a function that takes the majority bit across three words, rotations, constants, and 32-bit additions. After the rounds, add the eight working words to the starting state word by word. The result becomes the state for the next block.
Chaining blocks this way lets SHA-256 process a file without storing the whole thing. Because computing a digest requires no secret, anyone who can replace the file can also compute a new digest. If you share a secret with the sender and want to authenticate the file, you can use SHA-256 as a building block for an authentication tag. How HMAC-SHA-256 works
Why does HMAC use a key and hash twice?
Suppose two services exchange a message saying “Order 42 has shipped.” With a plain SHA-256 digest, anyone can create a replacement message and compute its digest. HMAC uses an existing hash function to produce an authentication tag tied to the message and to a secret key that the services share. Only a key holder can reliably generate a valid tag. The recipient computes the tag independently and compares it with the one received. RFC 2104
- Prepare the shared keyIf the key is longer than 64 bytes, hash it. Pad the resulting key with zeros to 64 bytes if needed. Call this block K.
- Sender · Inner hashXOR each byte of K with
0x36. Append the message and hash with SHA-256 to get the 32-byte inner digest. - Sender · Outer hashXOR each byte of K with
0x5c. Append the inner digest and hash with SHA-256. Send the message and this 32-byte tag. - Recipient · VerifyRepeat inner then outer hash with K and the received message. Compare all 32 tag bytes in constant time; accept only on a match.
The inner hash reads the message and the outer hash wraps the result
- Bring the secret key to the SHA-256 block size of 64 bytes. If it is longer than a block, first hash it with SHA-256. Pad any shorter value with trailing zeros. Call the resulting block K.
- XOR each byte of K with
0x36, append the message, and hash the result with SHA-256. For a long message, you can process it in chunks as it arrives to compute the inner digest. - XOR each byte of K with
0x5c, append the 32-byte inner digest, and hash the result again with SHA-256. Send this outer digest as the tag.
The two constants give the inner and outer hashes different starting blocks derived from the same key. Regardless of the message length, the outer hash receives a key-derived block followed by a fixed-length digest. A length-extension calculation that treats the public tag as a SHA-256 intermediate state produces a hash of a different input form. A valid HMAC for the extended message requires a new inner digest under the key. SHA-256 internal state · RFC 2104 §2
Who can verify the tag?
If the received message says “Order 43,” the recipient’s inner hash processes a different order number, and the tag check fails. The recipient holds the same key and can also create valid messages. Giving the key to more people lets more people verify tags and also lets them create tags. Use a digital signature when you want people to verify something you distribute using a public key. In the QuantAegis Rust API, HmacSha256::verify checks the tag. Using HMAC · Digital signature example
How can a deterministic calculation produce hard-to-predict bytes?
Key generation needs bytes that are hard for an outsider to predict. On initialization, HMAC_DRBG incorporates unpredictable input (entropy) into a secret state, then uses that state to generate pseudorandom bytes on request. The same state and inputs give the same output, so known test inputs can help verify the implementation. The entropy source provides the initial unpredictability. NIST SP 800-90A Rev. 1 §10.1.2
How many HMAC calls produce 48 bytes of output?
HMAC_DRBG(SHA-256) keeps a secret key K and a secret value V, each 32 bytes long. At initialization, it starts with K filled with zeros and V filled with 0x01 bytes, then updates both using seed material that includes entropy.
-
Secret state The 32-byte
KandVfrom initialization.Request 48 bytes with no additional input or reseed. - Generate the first block
V₁ = HMAC(K, V) - Generate the second block
V₂ = HMAC(K, V₁) -
Take 48 output bytes Join all 32 bytes of
V₁and the first 16 bytes ofV₂.Advance the secret state Use all 32 bytes ofV₂.- Update the key.
K′ = HMAC(K, V₂ || 0x00) - Update the value with the new key.
V′ = HMAC(K′, V₂)
- Update the key.
- Advance the counters Count one more request. QuantAegis also adds 48 to the byte count since initialization or the last reseed.
- Return 48 bytes The caller gets the selected bytes, and the generator retains
K′andV′for the next request.
This request uses four HMAC calls in total. Two generate the output, one updates K, and one updates V.
The second HMAC computation requires both the preceding output and the secret K. Predicting the rest of the sequence from the returned bytes alone is therefore difficult. How HMAC works
How does reseeding differ from updating the state?
An update computes the new K by applying HMAC under the current K to V || 0x00 || input material. It then uses the new K to update V. If there is input material, it performs another pair of updates using 0x01 as the separator. The generator also advances its state at the end of each request. Requesting 32 bytes and then 16 bytes introduces an intervening state update that changes the final 16 bytes compared with a single 48-byte request.
Reseeding incorporates fresh entropy from an external source. Someone who knows the current state can compute the future sequence through ordinary deterministic updates. Once the total output of HmacDrbgSha256 since initialization or the most recent reseed reaches or exceeds 16 KiB, the next generation request requires a reseed. Ordinary SDK key generation uses the operating system’s randomness source. The Rust API for using this generator directly provides operations to initialize it, generate bytes, and reseed it. Using the random bit generator and its limits · Rust API
Binding support
| Feature | Rust | Python | C ABI | JS/WASM |
|---|---|---|---|---|
| ML-KEM-512 / 768 / 1024 and X-Wing | All | All | All | All |
| ML-DSA-44 / 65 / 87 and MLDSA65-Ed25519-SHA512 | All | All | All | All |
| SLH-DSA-SHAKE (128 / 192 / 256) | s and f | s and f | s and f | f |
| SHA3-256 / 512 and SHAKE128 / 256 | All four | All four | All four | SHA3-256 and SHAKE256 |
| Envelope, policy checks and key rotation | SDK | SDK | — | — |
| SPKI / PKCS#8 DER and PEM for ML-KEM, ML-DSA and SLH-DSA | SDK | SDK | — | — |
| Direct SHA-256, HMAC-SHA-256 and HMAC_DRBG calls | drbg crate | — | — | — |
Choose your interface: Rust crates · Python classes and exceptions · C functions and buffers · JS/WASM initialization and types.
Key representations depend on the entry point. For example, Python’s MlKem768.keygen() returns raw keys, while Envelope.generate_keypair() returns keys with algorithm-identifying headers. Use the matching reader when loading saved keys.
Rust SDK and Python share QuantAegis-specific formats for QAEN v1 envelopes and Agile keys and signatures. C and JS/WASM work with the individual algorithms’ raw keys, KEM ciphertexts and signatures. The standard key codecs cover the three non-hybrid families in the table. Python’s ML-KEM and ML-DSA PKCS#8 encoders take a 64-byte or 32-byte seed respectively. The expanded private key returned by keygen() cannot be passed to these encoders.
| Operation | Available interfaces |
|---|---|
| Streaming ML-DSA External-μ | Rust primitives and Python |
| Standalone KEM key validation | Rust typed parsing, Python and C. JS/WASM checks inputs during operations |
| Deterministic KEM test interfaces | Rust, C and Python support ML-KEM and X-Wing. JS/WASM exposes X-Wing in qa.hazmat |
| Streaming SHA-3 / SHAKE | Rust. The bindings provide one-shot calls. Python caps SHAKE output at 16 MiB per call |
Rust crates
Use quantaegis-sdk to encrypt data for a recipient. From the repository root, run cargo run --locked -p quantaegis-sdk --example envelope. The example uses OS randomness for key generation and encapsulation and checks the recovered bytes before it exits.
//! Encrypt and open an order message with authenticated associated data.
use quantaegis_core::Result;
use quantaegis_sdk::{AeadAlgorithm, AgileKeyPair, Envelope, KemAlgorithm, SecurityPolicy};
fn main() -> Result<()> {
let policy = SecurityPolicy::CryptrecCategory3Plus;
let recipient = AgileKeyPair::generate(policy, KemAlgorithm::MlKem768)?;
let aad = b"order=42";
let packet = Envelope::seal(
policy,
&recipient.public,
AeadAlgorithm::Aes256Gcm,
b"ship on Friday",
aad,
)?;
let message = Envelope::open(policy, &recipient.secret, &packet, aad)?;
assert_eq!(message, b"ship on Friday");
Ok(())
}
Envelope::seal returns Result<Vec<u8>>. The example propagates errors from key generation, encryption and decryption with ?. Envelope methods · Error variants
See the Rust SDK migration example for how to switch stored data to X-Wing and enforce the cutover policy.
For lower-level operations, consult the crate documentation built from this checkout. ML-KEM · ML-DSA · SLH-DSA · Hybrid schemes · SHA-3 · DRBG
Envelope::open checks the header’s KEM against the policy and the recipient key before authenticating the body. A packet can therefore produce Error::PolicyViolation or Error::InvalidDecapsulationKey before AEAD verification. When calling primitives directly, provide your own CryptoRng implementation. For SLH-DSA on a small stack, use sign_into with a caller-supplied signature buffer.
Python classes and exceptions
Import names from the public quantaegis module. Keys, packets, messages and signatures in the tutorials are Python bytes. Keep secret keys and their copies out of logs. Type declarations · Public exports and SecurityPolicy
| Operation | Result |
|---|---|
Envelope.generate_keypair("ml-kem-768") | A tuple containing the serialized public key and secret key, in that order |
Envelope.seal(public_key, plaintext, aad=..., aead=..., policy=...) | Packet bytes for transmission |
Envelope.open(secret_key, packet, aad=...) | Authenticated plaintext. Failed authentication raises DecryptionError |
Envelope.inspect(packet) | KEM name, AEAD name and KEM ciphertext length from the unauthenticated header |
MlDsa65.sign(signing_key, message, ctx=...) | Signature bytes |
MlDsa65.verify(verify_key, message, signature, ctx=...) | None on success. A mismatched signature raises VerificationError |
See the SDK examples for migrating stored envelopes, rotating signing keys, and importing recipient keys from PEM.
Receiving packets and rotating keys
Before checking the authentication tag, open checks the KEM declared in the header against the policy and recipient key. A forbidden KEM raises PolicyViolationError. An allowed KEM that differs from the key’s algorithm raises InvalidKeyError. An AAD mismatch or failed tag check raises DecryptionError. Even inspect can raise DecryptionError for an unreadable header. After validating local keys and arguments, a receiver can catch the common base QuantAegisError to reject an incoming packet.
Envelope.open_with_keyring accepts a sequence of bytes keys from different algorithms. It reads every key header and parses every matching key before trying decryption. An unreadable key header or malformed matching key raises InvalidKeyError, even when the ring contains a working key. Migrate archived envelopes before tightening the policy to exclude their KEM. Use AgileSignature.verify_with_keyring to verify signatures across a key rotation.
SDK policies
policy | Algorithms admitted by this version |
|---|---|
cryptrec_category3_plus | Default for key generation, decryption and key decoding. Category 3 and above. Excludes ML-KEM-512, ML-DSA-44 and SLH-DSA-SHAKE-128s/f |
permissive | All implemented algorithms |
nist_post_2030 | Currently all implemented algorithms, including Category 1 and 2. Selecting it admits more algorithms than the default |
hybrid_required | X-Wing for KEMs and MLDSA65-Ed25519-SHA512 for signatures |
Python DER/PEM encoders use the permissive policy. For example, exporting an ML-KEM-512 public key to PEM succeeds, but loading it under the default policy raises PolicyViolationError. Pass an explicit policy to the decoder when your application accepts that algorithm. The public-key inspection helpers on AgileKem and AgileSignature default to permissive.
Signing and verification accept a context of up to 255 bytes. An overlong context raises QuantAegisError, and a malformed verification key raises InvalidKeyError. Python owns immutable bytes and str objects holding keys, shared secrets, decrypted plaintext or private-key PEM. The library cannot wipe these objects. Minimize their lifetime and copies. Encryption tutorial · Signing tutorial
Python type declarations
The following type stub documents the native binding. Import public classes from quantaegis. Names beginning with an underscore describe implementation details. Import deterministic KEM test helpers from the public quantaegis.hazmat module. Using the Python API
"""PEP 484 type stubs for the native Rust extension module ``quantaegis._native``.
Secret memory hygiene: the native layer zeroizes its own Rust-side copies of secret material
(keys, seeds, derandomization inputs, shared secrets, decrypted plaintexts, PKCS#8 DER/PEM
buffers) on every exit path, including errors, and borrows secret arguments instead of copying
them where it can. Python ``bytes`` and ``str`` objects that hold
secrets -- arguments you pass in and values returned to you (secret keys, seeds, shared secrets,
plaintexts, private-key PEM text) -- are immutable and owned by the Python allocator, so this
library cannot zeroize them; they may remain in process memory until the interpreter reuses it.
Keep their lifetime short and avoid making extra copies.
"""
from collections.abc import Sequence
from typing import Final, final
__all__ = [
"AgileKem",
"AgileSignature",
"DecryptionError",
"Envelope",
"InvalidCiphertextError",
"InvalidKeyError",
"MlDsa44",
"MlDsa65",
"MlDsa65Ed25519",
"MlDsa87",
"MlDsaMuHasher",
"MlKem1024",
"MlKem512",
"MlKem768",
"PolicyViolationError",
"QuantAegisError",
"SerializationError",
"SlhDsaShake128f",
"SlhDsaShake128s",
"SlhDsaShake192f",
"SlhDsaShake192s",
"SlhDsaShake256f",
"SlhDsaShake256s",
"UnsupportedAlgorithmError",
"VerificationError",
"XWing",
"_HazmatMlKem1024",
"_HazmatMlKem512",
"_HazmatMlKem768",
"_HazmatXWing",
"__version__",
"ml_dsa_private_from_pkcs8_der",
"ml_dsa_private_from_pkcs8_pem",
"ml_dsa_public_from_spki_der",
"ml_dsa_public_from_spki_pem",
"ml_dsa_public_to_spki_der",
"ml_dsa_public_to_spki_pem",
"ml_dsa_seed_to_pkcs8_der",
"ml_dsa_seed_to_pkcs8_pem",
"ml_kem_private_from_pkcs8_der",
"ml_kem_private_from_pkcs8_pem",
"ml_kem_public_from_spki_der",
"ml_kem_public_from_spki_pem",
"ml_kem_public_to_spki_der",
"ml_kem_public_to_spki_pem",
"ml_kem_seed_to_pkcs8_der",
"ml_kem_seed_to_pkcs8_pem",
"sha3_256",
"sha3_512",
"shake128",
"shake256",
"slh_dsa_private_from_pkcs8_der",
"slh_dsa_private_from_pkcs8_pem",
"slh_dsa_private_to_pkcs8_der",
"slh_dsa_private_to_pkcs8_pem",
"slh_dsa_public_from_spki_der",
"slh_dsa_public_from_spki_pem",
"slh_dsa_public_to_spki_der",
"slh_dsa_public_to_spki_pem",
]
__version__: Final[str]
class QuantAegisError(ValueError):
"""Base exception raised when a QuantAegis cryptographic, policy, or serialization operation fails."""
class VerificationError(QuantAegisError):
"""Raised when digital signature verification fails or a signature is malformed or has an invalid length."""
class InvalidKeyError(QuantAegisError):
"""Raised when an encapsulation, decapsulation, verifying, or signing key (or key seed) is malformed, has an invalid length, or fails validation."""
class InvalidCiphertextError(QuantAegisError):
"""Raised when a KEM ciphertext is malformed or has an invalid length."""
class DecryptionError(QuantAegisError):
"""Raised on envelope format/length errors and failed AEAD authentication.
Before authentication, a declared KEM can also cause PolicyViolationError
or InvalidKeyError during single-key open.
"""
class PolicyViolationError(QuantAegisError):
"""Raised when a requested algorithm or key violates the active SecurityPolicy."""
class SerializationError(QuantAegisError):
"""Raised when PEM, DER, SPKI, or PKCS#8 encoding/decoding fails."""
class UnsupportedAlgorithmError(QuantAegisError):
"""Raised when an unknown or unsupported algorithm or security policy name is requested."""
def sha3_256(data: bytes) -> bytes: ...
def sha3_512(data: bytes) -> bytes: ...
def shake128(data: bytes, output_len: int) -> bytes:
"""Computes ``SHAKE128(data)`` with an ``output_len``-byte output.
``output_len`` must be at most 16 MiB (``16 * 1024 * 1024`` bytes); larger values raise
``QuantAegisError`` (a ``ValueError``). Raises ``MemoryError`` if the output buffer cannot
be allocated.
"""
def shake256(data: bytes, output_len: int) -> bytes:
"""Computes ``SHAKE256(data)`` with an ``output_len``-byte output.
``output_len`` must be at most 16 MiB (``16 * 1024 * 1024`` bytes); larger values raise
``QuantAegisError`` (a ``ValueError``). Raises ``MemoryError`` if the output buffer cannot
be allocated.
"""
def ml_kem_public_to_spki_pem(algorithm: str, raw_ek: bytes) -> str: ...
def ml_kem_public_from_spki_pem(
pem: str, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def ml_kem_public_to_spki_der(algorithm: str, raw_ek: bytes) -> bytes: ...
def ml_kem_public_from_spki_der(
der: bytes, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def ml_kem_seed_to_pkcs8_pem(algorithm: str, seed: bytes) -> str: ...
def ml_kem_private_from_pkcs8_pem(
pem: str, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def ml_kem_seed_to_pkcs8_der(algorithm: str, seed: bytes) -> bytes: ...
def ml_kem_private_from_pkcs8_der(
der: bytes, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def ml_dsa_public_to_spki_pem(algorithm: str, raw_pk: bytes) -> str: ...
def ml_dsa_public_from_spki_pem(
pem: str, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def ml_dsa_public_to_spki_der(algorithm: str, raw_pk: bytes) -> bytes: ...
def ml_dsa_public_from_spki_der(
der: bytes, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def ml_dsa_seed_to_pkcs8_pem(algorithm: str, seed: bytes) -> str: ...
def ml_dsa_private_from_pkcs8_pem(
pem: str, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def ml_dsa_seed_to_pkcs8_der(algorithm: str, seed: bytes) -> bytes: ...
def ml_dsa_private_from_pkcs8_der(
der: bytes, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def slh_dsa_public_to_spki_pem(algorithm: str, raw_pk: bytes) -> str: ...
def slh_dsa_public_from_spki_pem(
pem: str, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def slh_dsa_public_to_spki_der(algorithm: str, raw_pk: bytes) -> bytes: ...
def slh_dsa_public_from_spki_der(
der: bytes, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def slh_dsa_private_to_pkcs8_pem(algorithm: str, raw_sk: bytes) -> str: ...
def slh_dsa_private_from_pkcs8_pem(
pem: str, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
def slh_dsa_private_to_pkcs8_der(algorithm: str, raw_sk: bytes) -> bytes: ...
def slh_dsa_private_from_pkcs8_der(
der: bytes, *, policy: str = "cryptrec_category3_plus"
) -> tuple[str, bytes]: ...
@final
class MlKem512:
EK_LEN: Final[int]
DK_LEN: Final[int]
CT_LEN: Final[int]
SHARED_SECRET_LEN: Final[int]
SEED_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def encaps(ek: bytes) -> tuple[bytes, bytes]: ...
@staticmethod
def decaps(dk: bytes, ct: bytes) -> bytes: ...
@staticmethod
def validate_ek(ek: bytes) -> None: ...
@staticmethod
def validate_dk(dk: bytes) -> None: ...
@final
class MlKem768:
EK_LEN: Final[int]
DK_LEN: Final[int]
CT_LEN: Final[int]
SHARED_SECRET_LEN: Final[int]
SEED_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def encaps(ek: bytes) -> tuple[bytes, bytes]: ...
@staticmethod
def decaps(dk: bytes, ct: bytes) -> bytes: ...
@staticmethod
def validate_ek(ek: bytes) -> None: ...
@staticmethod
def validate_dk(dk: bytes) -> None: ...
@final
class MlKem1024:
EK_LEN: Final[int]
DK_LEN: Final[int]
CT_LEN: Final[int]
SHARED_SECRET_LEN: Final[int]
SEED_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def encaps(ek: bytes) -> tuple[bytes, bytes]: ...
@staticmethod
def decaps(dk: bytes, ct: bytes) -> bytes: ...
@staticmethod
def validate_ek(ek: bytes) -> None: ...
@staticmethod
def validate_dk(dk: bytes) -> None: ...
@final
class XWing:
EK_LEN: Final[int]
DK_LEN: Final[int]
CT_LEN: Final[int]
SHARED_SECRET_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def encaps(ek: bytes) -> tuple[bytes, bytes]: ...
@staticmethod
def decaps(dk: bytes, ct: bytes) -> bytes: ...
@staticmethod
def validate_ek(ek: bytes) -> None: ...
@final
class _HazmatMlKem512:
SEED_LEN: Final[int]
@staticmethod
def keygen_derand(d: bytes, z: bytes) -> tuple[bytes, bytes]:
"""Deterministic key generation for known-answer tests. Use ``MlKem512.keygen()`` in production.
Hazardous: ``d`` and ``z`` must come from a CSPRNG and be kept secret. Pass the same
values again only to re-derive the same key pair.
"""
@staticmethod
def encaps_derand(ek: bytes, m: bytes) -> tuple[bytes, bytes]:
"""Deterministic encapsulation for known-answer tests. Use ``MlKem512.encaps()`` in production.
Hazardous: ``m`` must come from a CSPRNG, be kept secret and be fresh for every call.
Reusing ``m`` yields the same ciphertext and shared secret.
"""
@final
class _HazmatMlKem768:
SEED_LEN: Final[int]
@staticmethod
def keygen_derand(d: bytes, z: bytes) -> tuple[bytes, bytes]:
"""Deterministic key generation for known-answer tests. Use ``MlKem768.keygen()`` in production.
Hazardous: ``d`` and ``z`` must come from a CSPRNG and be kept secret. Pass the same
values again only to re-derive the same key pair.
"""
@staticmethod
def encaps_derand(ek: bytes, m: bytes) -> tuple[bytes, bytes]:
"""Deterministic encapsulation for known-answer tests. Use ``MlKem768.encaps()`` in production.
Hazardous: ``m`` must come from a CSPRNG, be kept secret and be fresh for every call.
Reusing ``m`` yields the same ciphertext and shared secret.
"""
@final
class _HazmatMlKem1024:
SEED_LEN: Final[int]
@staticmethod
def keygen_derand(d: bytes, z: bytes) -> tuple[bytes, bytes]:
"""Deterministic key generation for known-answer tests. Use ``MlKem1024.keygen()`` in production.
Hazardous: ``d`` and ``z`` must come from a CSPRNG and be kept secret. Pass the same
values again only to re-derive the same key pair.
"""
@staticmethod
def encaps_derand(ek: bytes, m: bytes) -> tuple[bytes, bytes]:
"""Deterministic encapsulation for known-answer tests. Use ``MlKem1024.encaps()`` in production.
Hazardous: ``m`` must come from a CSPRNG, be kept secret and be fresh for every call.
Reusing ``m`` yields the same ciphertext and shared secret.
"""
@final
class _HazmatXWing:
ENCAPS_SEED_LEN: Final[int]
@staticmethod
def keygen_derand(sk: bytes) -> tuple[bytes, bytes]:
"""Deterministic key generation for known-answer tests. Use ``XWing.keygen()`` in production.
Hazardous: ``sk`` (the 32-byte seed) must come from a CSPRNG and be kept secret. Pass
the same value again only to re-derive the same key pair.
"""
@staticmethod
def encaps_derand(ek: bytes, eseed: bytes) -> tuple[bytes, bytes]:
"""Deterministic encapsulation for known-answer tests. Use ``XWing.encaps()`` in production.
Hazardous: ``eseed`` must come from a CSPRNG, be kept secret and be fresh for every
call. Reusing ``eseed`` yields the same ciphertext and shared secret.
"""
@final
class MlDsaMuHasher:
MU_LEN: Final[int]
@staticmethod
def from_verifying_key(
algorithm: str, pk: bytes, *, ctx: bytes | None = None
) -> MlDsaMuHasher: ...
@staticmethod
def from_signing_key(
algorithm: str, sk: bytes, *, ctx: bytes | None = None
) -> MlDsaMuHasher: ...
def update(self, chunk: bytes) -> None: ...
def finalize(self) -> bytes: ...
@final
class MlDsa44:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
SEED_LEN: Final[int]
MAX_CTX_LEN: Final[int]
MU_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def from_seed(seed: bytes) -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@staticmethod
def mu_hasher(pk: bytes, *, ctx: bytes | None = None) -> MlDsaMuHasher: ...
@staticmethod
def mu_hasher_from_sk(sk: bytes, *, ctx: bytes | None = None) -> MlDsaMuHasher: ...
@staticmethod
def sign_mu(sk: bytes, mu: bytes) -> bytes: ...
@staticmethod
def sign_mu_deterministic(sk: bytes, mu: bytes) -> bytes: ...
@staticmethod
def verify_mu(pk: bytes, mu: bytes, sig: bytes) -> None: ...
@final
class MlDsa65:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
SEED_LEN: Final[int]
MAX_CTX_LEN: Final[int]
MU_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def from_seed(seed: bytes) -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@staticmethod
def mu_hasher(pk: bytes, *, ctx: bytes | None = None) -> MlDsaMuHasher: ...
@staticmethod
def mu_hasher_from_sk(sk: bytes, *, ctx: bytes | None = None) -> MlDsaMuHasher: ...
@staticmethod
def sign_mu(sk: bytes, mu: bytes) -> bytes: ...
@staticmethod
def sign_mu_deterministic(sk: bytes, mu: bytes) -> bytes: ...
@staticmethod
def verify_mu(pk: bytes, mu: bytes, sig: bytes) -> None: ...
@final
class MlDsa87:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
SEED_LEN: Final[int]
MAX_CTX_LEN: Final[int]
MU_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def from_seed(seed: bytes) -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@staticmethod
def mu_hasher(pk: bytes, *, ctx: bytes | None = None) -> MlDsaMuHasher: ...
@staticmethod
def mu_hasher_from_sk(sk: bytes, *, ctx: bytes | None = None) -> MlDsaMuHasher: ...
@staticmethod
def sign_mu(sk: bytes, mu: bytes) -> bytes: ...
@staticmethod
def sign_mu_deterministic(sk: bytes, mu: bytes) -> bytes: ...
@staticmethod
def verify_mu(pk: bytes, mu: bytes, sig: bytes) -> None: ...
@final
class MlDsa65Ed25519:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
MAX_CTX_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def from_seed(seed: bytes) -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@final
class SlhDsaShake128s:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
MAX_CTX_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@final
class SlhDsaShake128f:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
MAX_CTX_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@final
class SlhDsaShake192s:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
MAX_CTX_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@final
class SlhDsaShake192f:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
MAX_CTX_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@final
class SlhDsaShake256s:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
MAX_CTX_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@final
class SlhDsaShake256f:
PK_LEN: Final[int]
SK_LEN: Final[int]
SIG_LEN: Final[int]
MAX_CTX_LEN: Final[int]
@staticmethod
def keygen() -> tuple[bytes, bytes]: ...
@staticmethod
def sign(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def sign_deterministic(sk: bytes, msg: bytes, *, ctx: bytes | None = None) -> bytes: ...
@staticmethod
def verify(pk: bytes, msg: bytes, sig: bytes, *, ctx: bytes | None = None) -> None: ...
@final
class Envelope:
@staticmethod
def generate_keypair(
algorithm: str = "x-wing",
policy: str = "cryptrec_category3_plus",
) -> tuple[bytes, bytes]: ...
@staticmethod
def seal(
public_key: bytes,
plaintext: bytes,
*,
aad: bytes | None = None,
aead: str = "aes-256-gcm",
policy: str = "cryptrec_category3_plus",
) -> bytes: ...
@staticmethod
def open(
secret_key: bytes,
envelope: bytes,
*,
aad: bytes | None = None,
policy: str = "cryptrec_category3_plus",
) -> bytes: ...
@staticmethod
def open_with_keyring(
secret_keys: Sequence[bytes],
envelope: bytes,
*,
aad: bytes | None = None,
policy: str = "cryptrec_category3_plus",
) -> bytes:
"""Decrypts ``envelope`` with the first matching key of a rotation keyring.
The envelope's KEM algorithm is checked against ``policy`` first
(``PolicyViolationError`` if forbidden). Only keys declaring that algorithm are parsed
and tried, so legacy keys of other algorithms may remain in the ring during a migration.
Every key's 7-byte wire header must be readable (``InvalidKeyError`` otherwise); the rest
of a key of another algorithm is not examined. A key of the envelope's algorithm that
fails to parse raises ``InvalidKeyError`` even if another key in the ring would decrypt.
``secret_keys`` must contain ``bytes`` objects.
"""
@staticmethod
def inspect(envelope: bytes) -> tuple[str, str, int]: ...
@final
class AgileKem:
@staticmethod
def generate_keypair(
algorithm: str = "x-wing",
policy: str = "cryptrec_category3_plus",
) -> tuple[bytes, bytes]: ...
@staticmethod
def encaps(
public_key: bytes,
*,
policy: str = "cryptrec_category3_plus",
) -> tuple[bytes, bytes]: ...
@staticmethod
def decaps(
secret_key: bytes,
ciphertext: bytes,
*,
policy: str = "cryptrec_category3_plus",
) -> bytes: ...
@staticmethod
def inspect_public_key(
public_key: bytes,
*,
policy: str = "permissive",
) -> str: ...
@staticmethod
def public_from_raw(
algorithm: str,
raw_ek: bytes,
*,
policy: str = "cryptrec_category3_plus",
) -> bytes: ...
@staticmethod
def secret_from_raw(
algorithm: str,
raw_dk: bytes,
*,
policy: str = "cryptrec_category3_plus",
) -> bytes: ...
@final
class AgileSignature:
@staticmethod
def generate_keypair(
algorithm: str = "ml-dsa-65",
policy: str = "cryptrec_category3_plus",
) -> tuple[bytes, bytes]: ...
@staticmethod
def sign(
signing_key: bytes,
msg: bytes,
*,
ctx: bytes | None = None,
policy: str = "cryptrec_category3_plus",
) -> bytes: ...
@staticmethod
def sign_deterministic(
signing_key: bytes,
msg: bytes,
*,
ctx: bytes | None = None,
policy: str = "cryptrec_category3_plus",
) -> bytes: ...
@staticmethod
def verify(
verifying_key: bytes,
msg: bytes,
signature: bytes,
*,
ctx: bytes | None = None,
policy: str = "cryptrec_category3_plus",
) -> None: ...
@staticmethod
def verify_with_keyring(
verifying_keys: Sequence[bytes],
msg: bytes,
signature: bytes,
*,
ctx: bytes | None = None,
policy: str = "cryptrec_category3_plus",
) -> str:
"""Verifies ``signature`` against a keyring and returns the matched algorithm name.
The signature's algorithm is checked against ``policy`` first
(``PolicyViolationError`` if forbidden). Only keys declaring that algorithm are parsed
and tried, so legacy keys of other algorithms may remain in the ring during a migration.
Every key's wire frame (11-byte header and declared length) must be well-formed
(``InvalidKeyError`` otherwise); the key material of a key of another algorithm is not
examined. A key of the signature's algorithm that fails to parse raises
``InvalidKeyError`` even if another key in the ring would verify. A ``ctx`` longer than
255 bytes raises ``QuantAegisError``, as in ``verify``.
"""
@staticmethod
def inspect_verifying_key(
verifying_key: bytes,
*,
policy: str = "permissive",
) -> str: ...
@staticmethod
def inspect_signature(signature: bytes) -> str: ...
C functions and buffers
Build the library with cargo build --locked -p quantaegis-ffi --release and include quantaegis.h in the calling program. The caller supplies buffers and byte lengths. The header specifies the required sizes and rules for overlapping buffers. Functions and constants
Check the returned quantaegis_status_t against QUANTAEGIS_OK before using the output. Pass an error code to quantaegis_status_message for a description. Wipe caller-owned secret buffers with quantaegis_zeroize when finished.
On Linux, after building the release library, compile and run the C11 example from the repository root.
cc -std=c11 -I crates/quantaegis-ffi/include crates/quantaegis-ffi/examples/smoke.c \
-L target/release -lquantaegis_ffi -Wl,-rpath,target/release -o target/quantaegis-smoke
./target/quantaegis-smoke
C functions and constants
This header defines the ABI, status codes, key sizes, buffer requirements and function signatures. Calling from C · Download the header
/*
* QuantAegis (quantaegis-ffi) C ABI Header
*
* Licensed under the Apache License, Version 2.0.
*
* NOTE: Pre-1.0.0 software — an independent third-party cryptographic audit has
* not yet been completed; please take this into account when using this header.
* The maturity stage is tracked in SECURITY.md.
*/
#ifndef QUANTAEGIS_FFI_H
#define QUANTAEGIS_FFI_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ============================================================================
* ABI Version & Status Codes
* ========================================================================== */
#define QUANTAEGIS_ABI_VERSION 1u
typedef int32_t quantaegis_status_t;
#define QUANTAEGIS_OK ((quantaegis_status_t)0)
#define QUANTAEGIS_ERR_NULL_POINTER ((quantaegis_status_t)-1)
#define QUANTAEGIS_ERR_INVALID_LENGTH ((quantaegis_status_t)-2)
#define QUANTAEGIS_ERR_INVALID_ENCAPSULATION_KEY ((quantaegis_status_t)-3)
#define QUANTAEGIS_ERR_INVALID_DECAPSULATION_KEY ((quantaegis_status_t)-4)
#define QUANTAEGIS_ERR_INVALID_CIPHERTEXT ((quantaegis_status_t)-5)
#define QUANTAEGIS_ERR_RNG_FAILURE ((quantaegis_status_t)-6)
#define QUANTAEGIS_ERR_INVALID_VERIFYING_KEY ((quantaegis_status_t)-7)
#define QUANTAEGIS_ERR_INVALID_SIGNING_KEY ((quantaegis_status_t)-8)
#define QUANTAEGIS_ERR_INVALID_SIGNATURE ((quantaegis_status_t)-9)
#define QUANTAEGIS_ERR_BUFFER_OVERLAP ((quantaegis_status_t)-10)
#define QUANTAEGIS_ERR_INTERNAL ((quantaegis_status_t)-99)
/* ============================================================================
* Buffer Contract (applies to every function in this header)
*
* Every buffer is passed as a (pointer, length in bytes) pair.
*
* [B1] Validity: a non-NULL pointer must be valid for reads (const inputs) or
* writes (outputs) of `len` bytes for the duration of the call, and no
* other thread may write an input or access an output during the call.
* This is the only precondition the library cannot check; violating it is
* undefined behavior. B2-B4 are checked and reported as status codes.
* [B2] NULL: a pointer may be NULL only where its function says "NULL allowed
* if len == 0". Any other NULL returns QUANTAEGIS_ERR_NULL_POINTER.
* [B3] Lengths: key, seed, ciphertext, shared-secret, signature and digest
* buffers must be exactly the documented QUANTAEGIS_*_LEN size. Any length
* above PTRDIFF_MAX is rejected. Both return QUANTAEGIS_ERR_INVALID_LENGTH.
* [B4] No overlap: an output buffer must not overlap any input buffer or any
* other output buffer of the same call; this is detected before any buffer
* is read or written and returns QUANTAEGIS_ERR_BUFFER_OVERLAP. Input
* buffers may overlap each other, and zero-length buffers never overlap.
* Exception: the SHA-3 and SHAKE functions allow the output to overlap the
* input, including fully in-place hashing.
* ========================================================================== */
/* ============================================================================
* Caller-Supplied Randomness and Deterministic Signing (*_keygen_derand,
* *_encaps_derand, *_keygen_from_seed, *_sign_deterministic)
*
* *_keygen_derand, *_encaps_derand and *_keygen_from_seed take their randomness
* from the caller instead of the OS CSPRNG. The *_keygen_derand and
* *_encaps_derand declarations are hidden by default and require defining
* `#define QUANTAEGIS_HAZMAT` before `#include "quantaegis.h"`. They exist for
* known-answer tests and for re-deriving a key pair from a seed the caller
* already stores securely. Their security rests entirely on the caller:
* - Every value (d, z, seed, the X-Wing sk seed, m, eseed) MUST come from a
* CSPRNG and MUST be kept secret.
* - A key seed (d and z, seed, the X-Wing sk seed) may be passed again only
* to re-derive the same key pair. Never use it for anything else.
* - Encapsulation randomness (m, eseed) MUST be fresh for every call: reusing
* it yields the same ciphertext and shared secret every time.
* Prefer the randomized functions (keygen, encaps) in production.
*
* *_sign_deterministic takes no randomness: the same key, message and context
* always give the same signature. The ML-DSA and SLH-DSA variants are the
* deterministic modes of FIPS 204 / FIPS 205. All of them, including the
* MLDSA65-Ed25519 composite, give up the per-signature randomness that hardens
* signing against fault and side-channel attacks. Prefer sign in production.
* ========================================================================== */
/* ============================================================================
* Algorithm Byte Size Constants (NIST FIPS 202 / 203 / 204 / 205 & IETF Hybrids)
* ========================================================================== */
#define QUANTAEGIS_SHA3_256_DIGEST_LEN 32u
#define QUANTAEGIS_SHA3_512_DIGEST_LEN 64u
#define QUANTAEGIS_ML_KEM_SEED_LEN 32u
#define QUANTAEGIS_ML_KEM_SHARED_SECRET_LEN 32u
#define QUANTAEGIS_ML_KEM_512_EK_LEN 800u
#define QUANTAEGIS_ML_KEM_512_DK_LEN 1632u
#define QUANTAEGIS_ML_KEM_512_CT_LEN 768u
#define QUANTAEGIS_ML_KEM_768_EK_LEN 1184u
#define QUANTAEGIS_ML_KEM_768_DK_LEN 2400u
#define QUANTAEGIS_ML_KEM_768_CT_LEN 1088u
#define QUANTAEGIS_ML_KEM_1024_EK_LEN 1568u
#define QUANTAEGIS_ML_KEM_1024_DK_LEN 3168u
#define QUANTAEGIS_ML_KEM_1024_CT_LEN 1568u
#define QUANTAEGIS_XWING_EK_LEN 1216u
#define QUANTAEGIS_XWING_DK_LEN 32u
#define QUANTAEGIS_XWING_CT_LEN 1120u
#define QUANTAEGIS_XWING_ENCAPS_SEED_LEN 64u
#define QUANTAEGIS_XWING_SHARED_SECRET_LEN 32u
#define QUANTAEGIS_ML_DSA_SEED_LEN 32u
#define QUANTAEGIS_ML_DSA_MAX_CTX_LEN 255u
#define QUANTAEGIS_ML_DSA_44_PK_LEN 1312u
#define QUANTAEGIS_ML_DSA_44_SK_LEN 2560u
#define QUANTAEGIS_ML_DSA_44_SIG_LEN 2420u
#define QUANTAEGIS_ML_DSA_65_PK_LEN 1952u
#define QUANTAEGIS_ML_DSA_65_SK_LEN 4032u
#define QUANTAEGIS_ML_DSA_65_SIG_LEN 3309u
#define QUANTAEGIS_ML_DSA_87_PK_LEN 2592u
#define QUANTAEGIS_ML_DSA_87_SK_LEN 4896u
#define QUANTAEGIS_ML_DSA_87_SIG_LEN 4627u
#define QUANTAEGIS_MLDSA65_ED25519_PK_LEN 1984u
#define QUANTAEGIS_MLDSA65_ED25519_SK_LEN 64u
#define QUANTAEGIS_MLDSA65_ED25519_SIG_LEN 3373u
#define QUANTAEGIS_SLH_DSA_SHAKE_128S_PK_LEN 32u
#define QUANTAEGIS_SLH_DSA_SHAKE_128S_SK_LEN 64u
#define QUANTAEGIS_SLH_DSA_SHAKE_128S_SIG_LEN 7856u
#define QUANTAEGIS_SLH_DSA_SHAKE_128F_PK_LEN 32u
#define QUANTAEGIS_SLH_DSA_SHAKE_128F_SK_LEN 64u
#define QUANTAEGIS_SLH_DSA_SHAKE_128F_SIG_LEN 17088u
#define QUANTAEGIS_SLH_DSA_SHAKE_192S_PK_LEN 48u
#define QUANTAEGIS_SLH_DSA_SHAKE_192S_SK_LEN 96u
#define QUANTAEGIS_SLH_DSA_SHAKE_192S_SIG_LEN 16224u
#define QUANTAEGIS_SLH_DSA_SHAKE_192F_PK_LEN 48u
#define QUANTAEGIS_SLH_DSA_SHAKE_192F_SK_LEN 96u
#define QUANTAEGIS_SLH_DSA_SHAKE_192F_SIG_LEN 35664u
#define QUANTAEGIS_SLH_DSA_SHAKE_256S_PK_LEN 64u
#define QUANTAEGIS_SLH_DSA_SHAKE_256S_SK_LEN 128u
#define QUANTAEGIS_SLH_DSA_SHAKE_256S_SIG_LEN 29792u
#define QUANTAEGIS_SLH_DSA_SHAKE_256F_PK_LEN 64u
#define QUANTAEGIS_SLH_DSA_SHAKE_256F_SK_LEN 128u
#define QUANTAEGIS_SLH_DSA_SHAKE_256F_SIG_LEN 49856u
/* ============================================================================
* Runtime Metadata & Memory Hygiene
* ========================================================================== */
uint32_t quantaegis_abi_version(void);
const char *quantaegis_version_string(void);
const char *quantaegis_status_message(quantaegis_status_t status);
/* Securely zeroes ptr[0..len). No-op if ptr is NULL, len == 0, or len > PTRDIFF_MAX. */
void quantaegis_zeroize(uint8_t *ptr, size_t len);
/* ============================================================================
* FIPS 202: SHA-3 & SHAKE XOF
*
* input: NULL allowed if input_len == 0.
* out may overlap input, including fully in-place use such as
* quantaegis_sha3_256(buf, buf_len, buf, 32): the input is read completely
* before the output is written (exception to Buffer Contract B4).
* ========================================================================== */
/* out_len must be QUANTAEGIS_SHA3_256_DIGEST_LEN (32). */
quantaegis_status_t quantaegis_sha3_256(
const uint8_t *input, size_t input_len,
uint8_t *out, size_t out_len
);
/* out_len must be QUANTAEGIS_SHA3_512_DIGEST_LEN (64). */
quantaegis_status_t quantaegis_sha3_512(
const uint8_t *input, size_t input_len,
uint8_t *out, size_t out_len
);
/* Writes out_len bytes of SHAKE128 output. out: NULL allowed if out_len == 0. */
quantaegis_status_t quantaegis_shake128(
const uint8_t *input, size_t input_len,
uint8_t *out, size_t out_len
);
/* Writes out_len bytes of SHAKE256 output. out: NULL allowed if out_len == 0. */
quantaegis_status_t quantaegis_shake256(
const uint8_t *input, size_t input_len,
uint8_t *out, size_t out_len
);
/* ============================================================================
* FIPS 203: ML-KEM-512 (NIST Security Category 1)
* ========================================================================== */
/*
* Buffer rules (see Buffer Contract above). No pointer may be NULL.
* Exact lengths: ek = QUANTAEGIS_ML_KEM_512_EK_LEN, dk = QUANTAEGIS_ML_KEM_512_DK_LEN,
* ct = QUANTAEGIS_ML_KEM_512_CT_LEN, ss = QUANTAEGIS_ML_KEM_SHARED_SECRET_LEN,
* d / z / m = QUANTAEGIS_ML_KEM_SEED_LEN.
* keygen: outputs ek_out, dk_out
* keygen_derand: inputs d, z; outputs ek_out, dk_out
* encaps: input ek; outputs ct_out, ss_out
* encaps_derand: inputs ek, m; outputs ct_out, ss_out
* decaps: inputs dk, ct; output ss_out
* validate_ek, validate_dk: input only
* No output may overlap an input or another output of the same call
* (QUANTAEGIS_ERR_BUFFER_OVERLAP).
*/
quantaegis_status_t quantaegis_ml_kem_512_keygen(
uint8_t *ek_out, size_t ek_len,
uint8_t *dk_out, size_t dk_len
);
#ifdef QUANTAEGIS_HAZMAT
quantaegis_status_t quantaegis_ml_kem_512_keygen_derand(
const uint8_t *d, size_t d_len,
const uint8_t *z, size_t z_len,
uint8_t *ek_out, size_t ek_len,
uint8_t *dk_out, size_t dk_len
);
#endif
quantaegis_status_t quantaegis_ml_kem_512_encaps(
const uint8_t *ek, size_t ek_len,
uint8_t *ct_out, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
#ifdef QUANTAEGIS_HAZMAT
quantaegis_status_t quantaegis_ml_kem_512_encaps_derand(
const uint8_t *ek, size_t ek_len,
const uint8_t *m, size_t m_len,
uint8_t *ct_out, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
#endif
quantaegis_status_t quantaegis_ml_kem_512_decaps(
const uint8_t *dk, size_t dk_len,
const uint8_t *ct, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
quantaegis_status_t quantaegis_ml_kem_512_validate_ek(const uint8_t *ek, size_t ek_len);
quantaegis_status_t quantaegis_ml_kem_512_validate_dk(const uint8_t *dk, size_t dk_len);
/* ============================================================================
* FIPS 203: ML-KEM-768 (NIST Security Category 3)
* ========================================================================== */
/*
* Same buffer rules as ML-KEM-512 above, with the QUANTAEGIS_ML_KEM_768_* lengths.
*/
quantaegis_status_t quantaegis_ml_kem_768_keygen(
uint8_t *ek_out, size_t ek_len,
uint8_t *dk_out, size_t dk_len
);
#ifdef QUANTAEGIS_HAZMAT
quantaegis_status_t quantaegis_ml_kem_768_keygen_derand(
const uint8_t *d, size_t d_len,
const uint8_t *z, size_t z_len,
uint8_t *ek_out, size_t ek_len,
uint8_t *dk_out, size_t dk_len
);
#endif
quantaegis_status_t quantaegis_ml_kem_768_encaps(
const uint8_t *ek, size_t ek_len,
uint8_t *ct_out, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
#ifdef QUANTAEGIS_HAZMAT
quantaegis_status_t quantaegis_ml_kem_768_encaps_derand(
const uint8_t *ek, size_t ek_len,
const uint8_t *m, size_t m_len,
uint8_t *ct_out, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
#endif
quantaegis_status_t quantaegis_ml_kem_768_decaps(
const uint8_t *dk, size_t dk_len,
const uint8_t *ct, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
quantaegis_status_t quantaegis_ml_kem_768_validate_ek(const uint8_t *ek, size_t ek_len);
quantaegis_status_t quantaegis_ml_kem_768_validate_dk(const uint8_t *dk, size_t dk_len);
/* ============================================================================
* FIPS 203: ML-KEM-1024 (NIST Security Category 5)
* ========================================================================== */
/*
* Same buffer rules as ML-KEM-512 above, with the QUANTAEGIS_ML_KEM_1024_* lengths.
*/
quantaegis_status_t quantaegis_ml_kem_1024_keygen(
uint8_t *ek_out, size_t ek_len,
uint8_t *dk_out, size_t dk_len
);
#ifdef QUANTAEGIS_HAZMAT
quantaegis_status_t quantaegis_ml_kem_1024_keygen_derand(
const uint8_t *d, size_t d_len,
const uint8_t *z, size_t z_len,
uint8_t *ek_out, size_t ek_len,
uint8_t *dk_out, size_t dk_len
);
#endif
quantaegis_status_t quantaegis_ml_kem_1024_encaps(
const uint8_t *ek, size_t ek_len,
uint8_t *ct_out, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
#ifdef QUANTAEGIS_HAZMAT
quantaegis_status_t quantaegis_ml_kem_1024_encaps_derand(
const uint8_t *ek, size_t ek_len,
const uint8_t *m, size_t m_len,
uint8_t *ct_out, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
#endif
quantaegis_status_t quantaegis_ml_kem_1024_decaps(
const uint8_t *dk, size_t dk_len,
const uint8_t *ct, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
quantaegis_status_t quantaegis_ml_kem_1024_validate_ek(const uint8_t *ek, size_t ek_len);
quantaegis_status_t quantaegis_ml_kem_1024_validate_dk(const uint8_t *dk, size_t dk_len);
/* ============================================================================
* CFRG X-Wing Hybrid KEM (ML-KEM-768 + X25519)
* ========================================================================== */
/*
* Buffer rules (see Buffer Contract above). No pointer may be NULL.
* Exact lengths: ek = QUANTAEGIS_XWING_EK_LEN, dk and keygen_derand sk =
* QUANTAEGIS_XWING_DK_LEN, ct = QUANTAEGIS_XWING_CT_LEN,
* ss = QUANTAEGIS_XWING_SHARED_SECRET_LEN, eseed = QUANTAEGIS_XWING_ENCAPS_SEED_LEN.
* keygen: outputs ek_out, dk_out
* keygen_derand: input sk; outputs ek_out, dk_out
* encaps: input ek; outputs ct_out, ss_out
* encaps_derand: inputs ek, eseed; outputs ct_out, ss_out
* decaps: inputs dk, ct; output ss_out
* validate_ek: input only
* No output may overlap an input or another output of the same call
* (QUANTAEGIS_ERR_BUFFER_OVERLAP).
*/
quantaegis_status_t quantaegis_xwing_keygen(
uint8_t *ek_out, size_t ek_len,
uint8_t *dk_out, size_t dk_len
);
#ifdef QUANTAEGIS_HAZMAT
quantaegis_status_t quantaegis_xwing_keygen_derand(
const uint8_t *sk, size_t sk_len,
uint8_t *ek_out, size_t ek_len,
uint8_t *dk_out, size_t dk_len
);
#endif
quantaegis_status_t quantaegis_xwing_encaps(
const uint8_t *ek, size_t ek_len,
uint8_t *ct_out, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
#ifdef QUANTAEGIS_HAZMAT
quantaegis_status_t quantaegis_xwing_encaps_derand(
const uint8_t *ek, size_t ek_len,
const uint8_t *eseed, size_t eseed_len,
uint8_t *ct_out, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
#endif
quantaegis_status_t quantaegis_xwing_decaps(
const uint8_t *dk, size_t dk_len,
const uint8_t *ct, size_t ct_len,
uint8_t *ss_out, size_t ss_len
);
quantaegis_status_t quantaegis_xwing_validate_ek(const uint8_t *ek, size_t ek_len);
/* ============================================================================
* FIPS 204: ML-DSA-44 / ML-DSA-65 / ML-DSA-87 Digital Signatures
* ========================================================================== */
/*
* Buffer rules (see Buffer Contract above).
* Exact lengths: pk / sk / sig = QUANTAEGIS_ML_DSA_<44|65|87>_PK_LEN / _SK_LEN /
* _SIG_LEN, seed = QUANTAEGIS_ML_DSA_SEED_LEN.
* Functions:
* keygen: outputs pk_out, sk_out
* keygen_from_seed: input seed; outputs pk_out, sk_out
* sign, sign_deterministic: inputs sk, msg, ctx; output sig_out
* verify: inputs pk, msg, ctx, sig (no outputs)
* msg: NULL allowed if msg_len == 0. ctx: NULL allowed if ctx_len == 0;
* ctx_len must not exceed 255. All other pointers must be non-NULL.
* No output may overlap an input or another output of the same call
* (QUANTAEGIS_ERR_BUFFER_OVERLAP); inputs (e.g. msg and ctx) may overlap.
*/
quantaegis_status_t quantaegis_ml_dsa_44_keygen(
uint8_t *pk_out, size_t pk_len,
uint8_t *sk_out, size_t sk_len
);
quantaegis_status_t quantaegis_ml_dsa_44_keygen_from_seed(
const uint8_t *seed, size_t seed_len,
uint8_t *pk_out, size_t pk_len,
uint8_t *sk_out, size_t sk_len
);
quantaegis_status_t quantaegis_ml_dsa_44_sign(
const uint8_t *sk, size_t sk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
uint8_t *sig_out, size_t sig_len
);
quantaegis_status_t quantaegis_ml_dsa_44_sign_deterministic(
const uint8_t *sk, size_t sk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
uint8_t *sig_out, size_t sig_len
);
quantaegis_status_t quantaegis_ml_dsa_44_verify(
const uint8_t *pk, size_t pk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
const uint8_t *sig, size_t sig_len
);
quantaegis_status_t quantaegis_ml_dsa_65_keygen(
uint8_t *pk_out, size_t pk_len,
uint8_t *sk_out, size_t sk_len
);
quantaegis_status_t quantaegis_ml_dsa_65_keygen_from_seed(
const uint8_t *seed, size_t seed_len,
uint8_t *pk_out, size_t pk_len,
uint8_t *sk_out, size_t sk_len
);
quantaegis_status_t quantaegis_ml_dsa_65_sign(
const uint8_t *sk, size_t sk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
uint8_t *sig_out, size_t sig_len
);
quantaegis_status_t quantaegis_ml_dsa_65_sign_deterministic(
const uint8_t *sk, size_t sk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
uint8_t *sig_out, size_t sig_len
);
quantaegis_status_t quantaegis_ml_dsa_65_verify(
const uint8_t *pk, size_t pk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
const uint8_t *sig, size_t sig_len
);
quantaegis_status_t quantaegis_ml_dsa_87_keygen(
uint8_t *pk_out, size_t pk_len,
uint8_t *sk_out, size_t sk_len
);
quantaegis_status_t quantaegis_ml_dsa_87_keygen_from_seed(
const uint8_t *seed, size_t seed_len,
uint8_t *pk_out, size_t pk_len,
uint8_t *sk_out, size_t sk_len
);
quantaegis_status_t quantaegis_ml_dsa_87_sign(
const uint8_t *sk, size_t sk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
uint8_t *sig_out, size_t sig_len
);
quantaegis_status_t quantaegis_ml_dsa_87_sign_deterministic(
const uint8_t *sk, size_t sk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
uint8_t *sig_out, size_t sig_len
);
quantaegis_status_t quantaegis_ml_dsa_87_verify(
const uint8_t *pk, size_t pk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
const uint8_t *sig, size_t sig_len
);
/* ============================================================================
* IETF LAMPS Composite Hybrid Signature: MLDSA65-Ed25519-SHA512
* ========================================================================== */
/*
* Buffer rules (see Buffer Contract above).
* Exact lengths: pk / sk / sig = QUANTAEGIS_MLDSA65_ED25519_PK_LEN / _SK_LEN /
* _SIG_LEN; keygen_from_seed seed = QUANTAEGIS_MLDSA65_ED25519_SK_LEN.
* Functions:
* keygen: outputs pk_out, sk_out
* keygen_from_seed: input seed; outputs pk_out, sk_out
* sign, sign_deterministic: inputs sk, msg, ctx; output sig_out
* verify: inputs pk, msg, ctx, sig (no outputs)
* msg: NULL allowed if msg_len == 0. ctx: NULL allowed if ctx_len == 0;
* ctx_len must not exceed 255. All other pointers must be non-NULL.
* No output may overlap an input or another output of the same call
* (QUANTAEGIS_ERR_BUFFER_OVERLAP); inputs (e.g. msg and ctx) may overlap.
*/
quantaegis_status_t quantaegis_mldsa65_ed25519_keygen(
uint8_t *pk_out, size_t pk_len,
uint8_t *sk_out, size_t sk_len
);
quantaegis_status_t quantaegis_mldsa65_ed25519_keygen_from_seed(
const uint8_t *seed, size_t seed_len,
uint8_t *pk_out, size_t pk_len,
uint8_t *sk_out, size_t sk_len
);
quantaegis_status_t quantaegis_mldsa65_ed25519_sign(
const uint8_t *sk, size_t sk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
uint8_t *sig_out, size_t sig_len
);
quantaegis_status_t quantaegis_mldsa65_ed25519_sign_deterministic(
const uint8_t *sk, size_t sk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
uint8_t *sig_out, size_t sig_len
);
quantaegis_status_t quantaegis_mldsa65_ed25519_verify(
const uint8_t *pk, size_t pk_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *ctx, size_t ctx_len,
const uint8_t *sig, size_t sig_len
);
/* ============================================================================
* FIPS 205: SLH-DSA-SHAKE (128s/f, 192s/f, 256s/f)
* ========================================================================== */
/*
* Buffer rules (see Buffer Contract above).
* Exact lengths: pk / sk / sig = QUANTAEGIS_SLH_DSA_SHAKE_<set>_PK_LEN / _SK_LEN /
* _SIG_LEN for the parameter set in the function name.
* Functions:
* keygen: outputs pk_out, sk_out
* sign, sign_deterministic: inputs sk, msg, ctx; output sig_out
* verify: inputs pk, msg, ctx, sig (no outputs)
* msg: NULL allowed if msg_len == 0. ctx: NULL allowed if ctx_len == 0;
* ctx_len must not exceed 255. All other pointers must be non-NULL.
* No output may overlap an input or another output of the same call
* (QUANTAEGIS_ERR_BUFFER_OVERLAP); inputs (e.g. msg and ctx) may overlap.
*/
quantaegis_status_t quantaegis_slh_dsa_shake_128s_keygen(uint8_t *pk_out, size_t pk_len, uint8_t *sk_out, size_t sk_len);
quantaegis_status_t quantaegis_slh_dsa_shake_128s_sign(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_128s_sign_deterministic(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_128s_verify(const uint8_t *pk, size_t pk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, const uint8_t *sig, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_128f_keygen(uint8_t *pk_out, size_t pk_len, uint8_t *sk_out, size_t sk_len);
quantaegis_status_t quantaegis_slh_dsa_shake_128f_sign(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_128f_sign_deterministic(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_128f_verify(const uint8_t *pk, size_t pk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, const uint8_t *sig, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_192s_keygen(uint8_t *pk_out, size_t pk_len, uint8_t *sk_out, size_t sk_len);
quantaegis_status_t quantaegis_slh_dsa_shake_192s_sign(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_192s_sign_deterministic(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_192s_verify(const uint8_t *pk, size_t pk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, const uint8_t *sig, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_192f_keygen(uint8_t *pk_out, size_t pk_len, uint8_t *sk_out, size_t sk_len);
quantaegis_status_t quantaegis_slh_dsa_shake_192f_sign(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_192f_sign_deterministic(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_192f_verify(const uint8_t *pk, size_t pk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, const uint8_t *sig, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_256s_keygen(uint8_t *pk_out, size_t pk_len, uint8_t *sk_out, size_t sk_len);
quantaegis_status_t quantaegis_slh_dsa_shake_256s_sign(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_256s_sign_deterministic(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_256s_verify(const uint8_t *pk, size_t pk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, const uint8_t *sig, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_256f_keygen(uint8_t *pk_out, size_t pk_len, uint8_t *sk_out, size_t sk_len);
quantaegis_status_t quantaegis_slh_dsa_shake_256f_sign(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_256f_sign_deterministic(const uint8_t *sk, size_t sk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, uint8_t *sig_out, size_t sig_len);
quantaegis_status_t quantaegis_slh_dsa_shake_256f_verify(const uint8_t *pk, size_t pk_len, const uint8_t *msg, size_t msg_len, const uint8_t *ctx, size_t ctx_len, const uint8_t *sig, size_t sig_len);
#ifdef __cplusplus
}
#endif
#endif /* QUANTAEGIS_FFI_H */
JavaScript and WebAssembly
Build the Wasm module and run the Node.js integration tests from the repository root.
rustup target add wasm32-unknown-unknown
cargo build --locked -p quantaegis-wasm --target wasm32-unknown-unknown --release
node --test wasm/test/quantaegis.test.mjs
In Node.js, read the compiled module with readFile and pass the bytes to initQuantAegisWasm, exported by wasm/quantaegis.mjs. In a browser, pass the ArrayBuffer returned by the fetched Wasm response. Key generation, KEM encapsulation and randomized signing require globalThis.crypto.getRandomValues.
On the initialized instance, qa.XWing.keygen() returns { ek, dk }. Calling qa.XWing.encaps(ek) returns { ct, sharedSecret }. The recipient can recover the shared secret with qa.XWing.decaps(dk, ct). Keys and ciphertexts are Uint8Array values. A signature mismatch throws an exception. Native failures expose a numeric code via QuantAegisWasmError.code. TypeScript declarations
This release implements X-Wing draft-11. ML-KEM and X-Wing decapsulation return 32 bytes even for an invalid capsule of the correct length. A returned secret alone cannot authenticate a message. Keep secret keys, seeds and shared secrets in Uint8Array buffers and clear each owned copy with .fill(0) after use. Wiping Wasm memory cannot clear copies on the JavaScript heap.
TypeScript declarations
The module declaration lists the initializer, the methods on its result, and the types each operation accepts and returns. Using the Wasm binding · Download the declaration
export type BytesLike = Uint8Array | string;
export class QuantAegisWasmError extends Error {
readonly code: number;
constructor(code: number, message: string);
}
export interface KemKeyPair {
readonly ek: Uint8Array;
readonly dk: Uint8Array;
}
export interface KemEncapsResult {
readonly ct: Uint8Array;
readonly sharedSecret: Uint8Array;
}
export interface KemApi {
readonly EK_LEN: number;
readonly DK_LEN: number;
readonly CT_LEN: number;
readonly SHARED_SECRET_LEN: 32;
keygen(): KemKeyPair;
encaps(ek: Uint8Array): KemEncapsResult;
/** An invalid capsule of the correct length also produces a secret. Authenticate the payload separately. */
decaps(dk: Uint8Array, ct: Uint8Array): Uint8Array;
}
export interface XWingHazmatApi {
/** Length in bytes of the `eseed` accepted by {@link XWingHazmatApi.encapsDerand}. */
readonly ENCAPS_SEED_LEN: 64;
/**
* Deterministic X-Wing `GenerateKeyPairDerand(skSeed)`.
*
* **Hazardous: intended for known-answer testing (KAT) only.** The 32-byte `skSeed` is the
* decapsulation key itself: it must come from a CSPRNG, be kept secret and never be reused for
* another key pair. Anyone who knows or can guess the seed recovers `dk`. Use
* {@link KemApi.keygen} for normal key generation.
*/
keygenDerand(skSeed: Uint8Array): KemKeyPair;
/**
* Deterministic X-Wing `EncapsulateDerand(ek, eseed)`.
*
* **Hazardous: intended for known-answer testing (KAT) only.** The 64-byte `eseed` replaces the
* encapsulation randomness. Reusing it, or using a predictable value, produces the same
* ciphertext and shared secret again and lets anyone who knows `eseed` compute the shared
* secret, which breaks security. Use {@link KemApi.encaps} in production.
*/
encapsDerand(ek: Uint8Array, eseed: Uint8Array): KemEncapsResult;
}
export interface QuantAegisWasmHazmat {
readonly XWing: XWingHazmatApi;
}
export interface SigKeyPair {
readonly pk: Uint8Array;
readonly sk: Uint8Array;
}
export interface SignatureApi {
readonly PK_LEN: number;
readonly SK_LEN: number;
readonly SIG_LEN: number;
readonly MAX_CTX_LEN: 255;
keygen(): SigKeyPair;
sign(sk: Uint8Array, msg: BytesLike, ctx?: BytesLike): Uint8Array;
/**
* Signs without fresh per-signature randomness (ML-DSA: `rnd = 0`; SLH-DSA:
* `opt_rand = PK.seed`), so the same `(sk, msg, ctx)` always yields the same signature.
*
* **Intended for known-answer testing (KAT) and reproducibility.** The deterministic variant is
* permitted by FIPS 204 / FIPS 205, but it drops the hedging randomness that mitigates
* fault-injection and side-channel attacks on the signing key. Prefer {@link SignatureApi.sign}
* (hedged) in production.
*/
signDeterministic(sk: Uint8Array, msg: BytesLike, ctx?: BytesLike): Uint8Array;
verify(pk: Uint8Array, msg: BytesLike, sig: Uint8Array, ctx?: BytesLike): void;
}
export interface SeededSignatureApi extends SignatureApi {
/** Length in bytes of the seed accepted by {@link SeededSignatureApi.fromSeed}. */
readonly SEED_LEN: number;
/**
* Derives a key pair deterministically from a `SEED_LEN`-byte seed (ML-DSA: the FIPS 204 `xi`
* seed; MLDSA65-Ed25519: the 64-byte composite seed).
*
* **Hazardous: intended for known-answer testing (KAT).** The seed is equivalent to the signing
* key: it must come from a CSPRNG, be kept secret and never be reused for another key pair.
* Anyone who knows or can guess the seed recovers `sk`. Use {@link SignatureApi.keygen} to
* generate new keys.
*/
fromSeed(seed: Uint8Array): SigKeyPair;
}
export interface QuantAegisWasmInstance {
readonly abiVersion: number;
sha3_256(data: BytesLike): Uint8Array;
shake256(data: BytesLike, outLen: number): Uint8Array;
readonly MlKem512: KemApi;
readonly MlKem768: KemApi;
readonly MlKem1024: KemApi;
readonly XWing: KemApi;
readonly MlDsa44: SeededSignatureApi;
readonly MlDsa65: SeededSignatureApi;
readonly MlDsa87: SeededSignatureApi;
readonly MlDsa65Ed25519: SeededSignatureApi;
readonly SlhDsaShake128f: SignatureApi;
readonly SlhDsaShake192f: SignatureApi;
readonly SlhDsaShake256f: SignatureApi;
readonly hazmat: QuantAegisWasmHazmat;
}
export function initQuantAegisWasm(
wasmSource: BufferSource | WebAssembly.Module,
): Promise<QuantAegisWasmInstance>;
Architecture and Envelope Format
The primitive layer uses types to distinguish keys and signatures, and provides ML-KEM, ML-DSA, SLH-DSA, SHA-3, and other primitives with no_std. quantaegis-drbg provides SHA-256, HMAC, HMAC_DRBG, and health tests for raw noise sources. The hybrid layer combines primitives with classical cryptography. The SDK handles scheme identifiers, key storage formats, policies, and envelopes. Python exposes this SDK as well; C and JS/WASM let callers invoke individual schemes using buffers or byte arrays. See the language support table.
Opening an Envelope v1
QAEN is a QuantAegis-specific format shared by the Rust SDK and Python. The public C and JS/WASM APIs work with individual primitives.
| Order | Stored content |
|---|---|
| Fixed header (10 bytes) | Magic QAEN, version, KEM ID, AEAD ID, KEM ciphertext length |
| Variable-length header | KEM ciphertext |
| Message | AEAD ciphertext and 16-byte authentication tag |
- The sender’s
sealperforms encapsulation each time, then feeds the header and shared secret into SHAKE256 with a purpose-specific label to derive a 32-byte AEAD key and 12-byte nonce. - It encrypts the message with AES-256-GCM or ChaCha20-Poly1305. The complete header and caller-provided AAD, including its length, are authenticated.
- The recipient can use
inspectto route the envelope before decryption. The header’s authenticity is established only whenopensucceeds with the matching private key and the same AAD.
During key rotation, encrypt with the new public key and pass both old and new private keys to the recipient’s open_with_keyring. If policy is tightened first and the old scheme is prohibited, previously stored data using that scheme can no longer be opened. See the Rust envelope specification · Python usage.
Testing and Audit Status
When adopting a scheme, check its conformance to the specification, interoperability with other implementations, and handling of secret values. Current maturity, third-party audit status, and the scope of CI, weekly, and manual verification are governed by the security policy. See SECURITY.md.
| What to check | Evidence in the repository |
|---|---|
| Does it return the specified output for known inputs? | NIST ACVP and hybrid-scheme known-answer tests. Sources and pinned revisions are documented in vector provenance. |
| How are invalid keys or signatures and boundary values handled? | Wycheproof cases, exception and error checks for each binding, and parser fuzzing. Test setup |
| Can keys and signatures be exchanged with another implementation? | Bidirectional tests with Go for ML-KEM-768 / 1024 and ML-DSA-44 / 65 / 87. Interoperability tests |
| Can timing differences caused by secret values be detected? | Assembly inspection of target code paths in CI and weekly dudect and ctgrind runs. |
Locally, run cargo test --locked for the regular Rust tests and cargo test --locked --release -- --ignored for the longer-running vector checks. Passing tests describe results observed for the cases covered. The security policy tracks certification and independent audits. FIPS 140-3 validation status · Independent audit status