=============== LIBRARY RULES =============== From library maintainers: - Pass a context when signing and the same expected context when verifying. - Pass aad when sealing an envelope and expected_aad when opening it. - The default hybrid signature suite is Ed25519+ML-DSA-65-v2; the default hybrid KEM is X25519+ML-KEM-768. ### Development install and setup Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/installation.rst Clones the repository, installs in editable mode with dev dependencies, and sets up pre-commit hooks. ```bash git clone https://github.com/AnimeshShaw/quantum-safe cd quantum-safe pip install -e '.[dev]' pre-commit install ``` -------------------------------- ### Working example with HybridSign and HybridKEM Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/context-and-aad.rst Shows how to sign and verify with a context, and seal and open an envelope with AAD. Verification with a different context raises VerificationError. The example asserts that opening with the expected AAD returns the original data. ```python from quantum_safe.exceptions import VerificationError from quantum_safe.signatures.hybrid import HybridSign from quantum_safe.kem.hybrid import HybridKEM from quantum_safe.protocols.envelope import Envelope signer = HybridSign() kp = signer.generate_keypair() sm = signer.sign(b"transfer 5", kp.secret, context=b"payments-v1") signer.verify(sm, kp.public, context=b"payments-v1") # accepted try: signer.verify(sm, kp.public, context=b"auth-v1") # a different purpose except VerificationError: print("refused: made for another purpose") kem = HybridKEM() rk = kem.generate_keypair() sealed = Envelope.seal(b"card on file", rk.public, aad=b"tenant-A") assert Envelope.open(sealed, rk.secret, expected_aad=b"tenant-A") == b"card on file" ``` -------------------------------- ### Install core quantum-safe-py package Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/installation.rst Installs the core package without a PQC backend. Works with classical X25519/Ed25519 components. ```bash pip install quantum-safe-py ``` -------------------------------- ### XWing KEM usage example Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/kem.rst Shows how to instantiate XWing, generate a keypair, encapsulate a shared secret, and decapsulate it. The example asserts that the sender and receiver shared secrets match. ```python from quantum_safe.kem.xwing import XWing kem = XWing() kp = kem.generate_keypair() ct, ss_sender = kem.encapsulate(kp.public) ss_receiver = kem.decapsulate(kp.secret, ct) assert ss_sender == ss_receiver ``` -------------------------------- ### Install quantum-safe-py with pip extras Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/README.md Install the base package for classical primitives, formats, scanner, and audit. Use the liboqs extra for ML-KEM, ML-DSA, and SLH-DSA, or the pyca extra for ML-KEM and ML-DSA via cryptography>=48 without a compiler. Requires Python 3.10 or later. ```bash pip install quantum-safe-py # classical primitives, formats, scanner, audit pip install 'quantum-safe-py[liboqs]' # ML-KEM, ML-DSA, SLH-DSA through liboqs pip install 'quantum-safe-py[pyca]' # ML-KEM and ML-DSA through cryptography>=48 (no compiler) ``` -------------------------------- ### is_available() Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/backends.rst Return True if this backend is installed and functional. Default implementation tries to generate a key with the first supported algorithm. ```APIDOC ## is_available() ### Description Return True if this backend is installed and functional. Default implementation tries to generate a key with the first supported algorithm. Override if there's a cheaper availability check. ### Parameters None ### Returns - bool - True if the backend is available. ``` -------------------------------- ### Install quantum-safe-py with cryptography backend Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/installation.rst Installs the package with the pyca backend, which uses cryptography >= 48 for ML-KEM-768/1024 and ML-DSA-44/65/87. No compiler or liboqs required. Keys are seeds (32 bytes for ML-DSA, 64 for ML-KEM). ```bash pip install 'quantum-safe-py[pyca]' ``` -------------------------------- ### AbstractSignatureBackend.is_available() Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/backends.rst Return True if this backend is installed and functional. ```APIDOC ## is_available() ### Description Return True if this backend is installed and functional. ### Returns bool - True if the backend is available. ``` -------------------------------- ### Verify liboqs backend installation Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/installation.rst Checks which backends are available after installation. Expected output shows liboqs and pyca as True. ```bash python -c "from quantum_safe.backends import list_available_backends; print(list_available_backends())" # → {'rustcrypto': False, 'liboqs': True, 'pyca': True, 'noble': False} ``` -------------------------------- ### HybridCertificateBuilder usage example Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/protocols.rst Shows how to generate key material and build a hybrid certificate using HybridCertificateBuilder. The example creates a HybridSign keypair and an Ed25519 private key, then builds a certificate with a 365-day validity. ```python from quantum_safe.protocols.x509 import HybridCertificateBuilder from quantum_safe.signatures.hybrid import HybridSign # Generate key material signer = HybridSign() hybrid_kp = signer.generate_keypair() classical_priv = Ed25519PrivateKey.generate() builder = HybridCertificateBuilder( subject_cn="service.internal", classical_private_key=classical_priv, pqc_keypair=hybrid_kp, validity_days=365, ) cert_pem, cosig_bundle = builder.build() ``` -------------------------------- ### Install quantum-safe-py with LMS stateful signatures Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/installation.rst Installs the optional LMS backend for CNSA 2.0 software/firmware signing. LMS is stateful; misuse compromises the signing key permanently. Read the LMS section of Signatures (quantum_safe.signatures) before using. ```bash pip install 'quantum-safe-py[lms]' ``` -------------------------------- ### Generate keypair and print fingerprint Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/kem.rst Example from the generate_keypair() method documentation. Creates a new keypair and prints the public key's fingerprint. ```python kp = kem.generate_keypair() print(kp.public.fingerprint()) ``` -------------------------------- ### HybridSign usage example Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/signatures.rst Shows how to create a HybridSign instance, generate a keypair, sign a document with a context, and verify the signature. The default algorithm is Ed25519+ML-DSA-65-v2. ```python from quantum_safe import HybridSign signer = HybridSign() kp = signer.generate_keypair() sm = signer.sign(b"document", kp.secret, context=b"myapp-v1") signer.verify(sm, kp.public, context=b"myapp-v1") ``` -------------------------------- ### Install quantum-safe-py with liboqs backend Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/installation.rst Installs the package with the liboqs backend for full ML-KEM/ML-DSA support. On common platforms (Linux x86_64, Windows x64, macOS arm64 14+), the bundled wheel avoids compiler requirements. Requires liboqs-python 0.16.x with liboqs 0.16.0. ```bash pip install 'quantum-safe-py[liboqs]' ``` -------------------------------- ### qs-migrate upgrade-key command usage Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/cli.rst Shows the full usage and options for the qs-migrate upgrade-key command, including input/output paths, target algorithm, key type, and force flag. Examples demonstrate upgrading an X25519 key and an Ed25519 key with a custom target. ```text qs-migrate upgrade-key [OPTIONS] Options: -i, --input PATH Classical secret key (required): a PKCS#8 "PRIVATE KEY" PEM, or this library's "QUANTUM SAFE SECRET KEY" PEM -o, --output PATH Where to write the hybrid SECRET key (required) --public-output PATH Where to write the hybrid public key (default: .pub) --target TEXT Hybrid algorithm to produce. Default: X25519+ML-KEM-768 for an X25519 key, Ed25519+ML-DSA-65-v2 for an Ed25519 key --key-type {kem,sign} Check that the input is a KEM (X25519) or signing (Ed25519) key; required for P-256 and P-384 keys --force Replace --output / --public-output if they exist Examples: qs-migrate upgrade-key -i x25519.pem -o hybrid-kem.pem qs-migrate upgrade-key -i ed25519.pem -o hybrid-sign.pem --target Ed25519+ML-DSA-87 ``` -------------------------------- ### MigrationStateManager usage example Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/migrate.rst Shows how to instantiate MigrationStateManager with a plain dict store and record a first transition for a key. The resulting record is stored in store['user-123_current'] and full history in store['user-123_history']. ```python store = {} # replace with your database abstraction mgr = MigrationStateManager(store) # First time we see this key rec = mgr.transition( key_id="user-123", from_state=MigrationState.CLASSICAL_ONLY, to_state=MigrationState.HYBRID_TRANSITION, algorithm="X25519+ML-KEM-768", actor="key-rotation-job-v1", ) # rec is stored in `store["user-123_current"]` # Full history in `store["user-123_history"]` ``` -------------------------------- ### qs-audit cbom command usage and examples Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/cli.rst Shows the command syntax and available options for qs-audit cbom, including --output, --no-provided, and --exclude. Includes two example invocations: writing to a file and excluding tests. The command is an inventory, not a compliance verdict. ```bash qs-audit cbom [OPTIONS] Options: --output PATH Write CBOM JSON to file (default: stdout) --no-provided Omit the provided-algorithm inventory; list only what the scan detected --exclude PATTERN Glob pattern to exclude (repeatable) Examples: qs-audit cbom ./src --output cbom.json qs-audit cbom ./src --no-provided --exclude "tests/**" ``` -------------------------------- ### LMS Signer Usage Example Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/signatures.rst Shows how to generate an LMS signer, sign data, verify a signature, and load an existing key. Requires a durable LmsStateStore implementation; the in-memory store is for tests only. Loading a key from a stale backup is refused due to rewind detection. ```python from quantum_safe.signatures.stateful import LmsSigner, verify # `store` must be a durable LmsStateStore implementation you control — # never the in-memory one, outside tests. signer = LmsSigner.generate("firmware-signing-key-2027", store, tree_height=10) sig = signer.sign(firmware_image) assert verify(signer.public_key(), firmware_image, sig) # Loading an existing key re-checks the state store, so a key restored # from a stale backup is refused rather than silently reused: signer = LmsSigner.load("firmware-signing-key-2027", serialised_key, store) ``` -------------------------------- ### qs-audit sbom command usage and examples Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/cli.rst Enriches a CycloneDX SBOM with PQC-readiness annotations. Supports JSON output (default) or a human-readable summary table. ```bash qs-audit sbom [OPTIONS] Options: --output PATH Write enriched SBOM to file (default: stdout) --format {json,summary} json (default) outputs full CycloneDX; summary prints a human-readable table Examples: qs-audit sbom sbom.json --output sbom-pqc.json qs-audit sbom sbom.json --format summary ``` -------------------------------- ### Run NIST known-answer vectors with Docker Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/reproducible-build.rst Build the project Docker image with the pinned LIBOQS_TAG and run the conformance test script. The build needs git, CMake, Ninja, and a C compiler (the project image installs them). ```bash docker build -t quantum-safe-liboqs --build-arg LIBOQS_TAG=0.16.0 . docker run --rm quantum-safe-liboqs python tests/conformance/acvp_kat.py ``` -------------------------------- ### Quickest path to a compliant configuration Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/compliance.rst Use cnsa2.pqc_kem() and cnsa2.pqc_sign() to get ML-KEM-1024 and ML-DSA-87, which meet CNSA 2.0 requirements. ```python from quantum_safe.compliance import cnsa2 kem = cnsa2.pqc_kem() # ML-KEM-1024 signer = cnsa2.pqc_sign() # ML-DSA-87 ``` -------------------------------- ### BackendNotAvailable Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/exceptions.rst Raised when a required backend is not installed or could not be loaded. The install_hint attribute contains a pip command to fix the problem. ```APIDOC ## BackendNotAvailable ### Description A required backend is not installed or could not be loaded. The `install_hint` attribute contains a pip command the user can run to fix the problem. ### Constructor `BackendNotAvailable(backend)` ### Parameters - **backend** (str) - Required - The name of the unavailable backend. ### Attributes - **code** (str) - Stable machine-readable identifier of the error type. - **message** (str) - The human-readable message. - **context** (dict) - Contains `backend`. - **install_hint** (str) - A pip command to install the missing backend. ``` -------------------------------- ### Rebuild vendored liboqs from clean checkout Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/reproducible-build.rst From a clean checkout of the release tag, set QUANTUM_SAFE_VENDOR_LIBOQS=1 and build the wheel. The build hook runs the liboqs-python installer at the pinned release into a staging directory and copies the resulting library into the wheel. Compare contents, not byte-identical wheels, across machines. ```bash git checkout v1.0.0 QUANTUM_SAFE_VENDOR_LIBOQS=1 python -m build --wheel ``` -------------------------------- ### LiboqsKEMBackend.supported_algorithms() Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/backends.rst Returns the list of KEM algorithms supported by the installed liboqs build. ```APIDOC ## supported_algorithms() ### Description Return algorithms supported by this backend. Only algorithms enabled in the installed liboqs build are returned. ### Method supported_algorithms() ### Parameters None ### Returns List of supported algorithm names. ### Exceptions None ``` -------------------------------- ### NISTComplianceChecker usage example Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/audit.rst Shows how to use NISTComplianceChecker.check with a Scanner to generate a compliance report and print it as JSON. ```python from quantum_safe.audit.compliance import NISTComplianceChecker from quantum_safe.migrate.scanner import Scanner scan = Scanner.scan_directory("./src") report = NISTComplianceChecker.check(scan, target="./src") print(report.to_json()) ``` -------------------------------- ### lms_available() Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/compliance.rst Whether the optional LMS dependency is installed. ```APIDOC ## lms_available() ### Description Whether the optional LMS dependency is installed. ``` -------------------------------- ### qs-migrate rewrap command usage Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/cli.rst Shows the full usage and options for the qs-migrate rewrap command, including source/destination paths, old and new keys, AAD handling, in-place mode, dry-run, and report outputs. The example demonstrates rewrapping sealed envelopes with AAD from path and generating JSON and CycloneDX reports. ```text qs-migrate rewrap SOURCE [DESTINATION] [OPTIONS] Options: --old-secret PATH Secret-key PEM the envelopes are sealed to today (required) --new-public PATH Public-key PEM to seal them to (required) --new-secret PATH The matching new secret-key PEM: each result is opened again and compared (recommended) --aad TEXT The AAD every envelope must carry (UTF-8) --aad-from-path Expect each envelope's AAD to be its path relative to SOURCE --in-place Replace files in SOURCE (atomically); no DESTINATION --dry-run Check everything, write nothing --report PATH Write the JSON report --cbom PATH Write a CycloneDX report Examples: qs-migrate rewrap sealed/ sealed-new/ --old-secret old.pem --new-public new.pub.pem \ --new-secret new.pem --aad-from-path --report rewrap.json --cbom rewrap-cbom.json ``` -------------------------------- ### Sign and verify a JWT with JWTSigner and JWTVerifier Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/protocols.rst Shows the basic workflow: create a JWTSigner with a keypair and issuer, sign claims to get a token, then verify with a JWTVerifier using the public key. The verifier must use the same issuer and hedged setting as the signer. ```python signer = JWTSigner(keypair, issuer="auth.myapp.com") token = signer.sign({"sub": "user123", "role": "admin"}) # → "eyJhbGci..." verifier = JWTVerifier(public_key) claims = verifier.verify(token) # → {"sub": "user123", "role": "admin", "iss": "auth.myapp.com", ...} ``` ```python verifier = JWTVerifier(public_key, issuer="auth.myapp.com") claims = verifier.verify(token) user_id = claims["sub"] ``` -------------------------------- ### Scan codebase with qs-migrate scan Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/migration.rst The 'qs-migrate scan' command scans a codebase and can output SARIF format to a file. The example shows scanning './src' with '--format sarif' and '--output migrate.sarif'. ```bash # Scan a codebase qs-migrate scan ./src --format sarif --output migrate.sarif ``` -------------------------------- ### HybridSign and Sign with -v2 Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/signatures.rst Example of creating a hybrid signer with Ed25519 and ML-DSA-65-v2, generating a keypair, signing a document with a context, and verifying the signature. ```APIDOC ## HybridSign and Sign with -v2 ### Description Create a hybrid signer using Ed25519 and ML-DSA-65-v2, generate a keypair, sign a document with a context, and verify the signature. ### Usage ```python from quantum_safe import HybridSign from quantum_safe.signatures import Sign signer = Sign("ML-DSA-65-v2") # pure ML-DSA hybrid = HybridSign("Ed25519", "ML-DSA-65-v2") # Ed25519+ML-DSA-65-v2 kp = hybrid.generate_keypair() sm = hybrid.sign(b"document", kp.secret, context=b"myapp-v1") hybrid.verify(sm, kp.public, context=b"myapp-v1") ``` ### Supported Identifiers - `ML-DSA-44/65/87-v2` - `Ed25519+ML-DSA-44/65/87-v2` - `P-256+ML-DSA-44/65-v2` - `P-384+ML-DSA-87-v2` ### Notes - No prefix and no prefix length in the signature. - Hybrid signature is exactly `classical signature || ML-DSA signature`. - ML-DSA half is plain FIPS 204 `ML-DSA.Sign` with native context `quantum-safe-sig-v2` over `M2 = u8(len(algo)) || algo || u8(len(ctx)) || ctx || message`. - Classical half signs `"quantum-safe-sig-v2" || 0x00 || M2`. - ML-DSA signing is always hedged; `hedged=False` with a `-v2` suite raises `ValueError`. - Keys carry the `-v2` tag but are byte-identical to v1 keys; never use the same key in both formats. ### Default Formats | Call | Format | |------|--------| | `HybridSign()` | `Ed25519+ML-DSA-65-v2` | | `Sign()` | `ML-DSA-65` (original format) | | `HybridSign("Ed25519", "ML-DSA-65")` | Original hybrid format | | `Sign().sign_standard(...)` | Bare FIPS 204 signature with native context | ``` -------------------------------- ### get_signature_backend(name='auto') Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/backends.rst Returns the signature backend for the given name. Selection follows get_kem_backend: the QUANTUM_SAFE_BACKEND environment variable replaces 'auto', and 'auto' tries rustcrypto, liboqs, then pyca. Raises BackendNotAvailable if the backend is not installed or for 'noble', or ValueError if the name is unknown. ```APIDOC ## get_signature_backend(name='auto') ### Description Returns the signature backend for the given name. Selection follows get_kem_backend: the QUANTUM_SAFE_BACKEND environment variable replaces 'auto', and 'auto' tries rustcrypto, liboqs, then pyca. Raises BackendNotAvailable if the backend is not installed or for 'noble', or ValueError if the name is unknown. ### Parameters - **name** (str) - Optional - "auto", "liboqs", "rustcrypto" or "pyca". ### Raises - **BackendNotAvailable** - if the requested backend is not installed, or for "noble". - **ValueError** - if the backend name is unknown. ### Returns - The signature backend instance for the given name. ``` -------------------------------- ### Checking an arbitrary configuration Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/compliance.rst Use cnsa2.report() to evaluate a configuration against CNSA 2.0. The example shows a non-compliant configuration and the resulting report output. ```python from quantum_safe.compliance import cnsa2 report = cnsa2.report( kem="X25519+ML-KEM-768", signature="Ed25519+ML-DSA-65", hash_algorithm="SHA-256", ) print(report.render()) # [FAIL] Key establishment ... requires ML-KEM-1024 # [FAIL] Signatures ... requires ML-DSA-87 # [FAIL] Hashing ... requires SHA-384 or SHA-512 # [GAP ] Software/firmware signing (SP 800-208) ... # OVERALL: NOT compliant (4 issue(s)) ``` -------------------------------- ### get_kem_backend(name='auto') Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/backends.rst Returns the KEM backend for the given name. Supports 'auto', 'liboqs', 'rustcrypto', and 'pyca'. When 'auto', the QUANTUM_SAFE_BACKEND environment variable (case-insensitive) is used if set. Raises BackendNotAvailable if the backend is not installed, or ValueError if the name is unknown. ```APIDOC ## get_kem_backend(name='auto') ### Description Returns the KEM backend for the given name. Supports 'auto', 'liboqs', 'rustcrypto', and 'pyca'. When 'auto', the QUANTUM_SAFE_BACKEND environment variable (case-insensitive) is used if set. Raises BackendNotAvailable if the backend is not installed, or ValueError if the name is unknown. ### Parameters - **name** (str) - Optional - "auto", "liboqs", or "rustcrypto". Falls back through the priority list if "auto". "pyca" is accepted too. When `name` is "auto", a non-empty `QUANTUM_SAFE_BACKEND` environment variable (case-insensitive) replaces it. ### Raises - **BackendNotAvailable** - if the requested backend is not installed. - **ValueError** - if the backend name is unknown. ### Returns - The KEM backend instance for the given name. ``` -------------------------------- ### Quick start: hybrid KEM, encryption, and signing Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/README.md Demonstrates hybrid X25519 + ML-KEM-768 key exchange, KEM + AES-256-GCM encryption with AAD, and hybrid Ed25519 + ML-DSA-65 signing with context. The verify method raises VerificationError if the signature is invalid. ```python from quantum_safe import HybridKEM, HybridSign from quantum_safe.protocols import Envelope # Key exchange: hybrid X25519 + ML-KEM-768 kem = HybridKEM() kp = kem.generate_keypair() ct, shared_secret = kem.encapsulate(kp.public) assert shared_secret == kem.decapsulate(kp.secret, ct) # Encrypt to a public key: KEM + AES-256-GCM, and state the AAD you expect on open sealed = Envelope.seal(b"plaintext", kp.public, aad=b"record-42") plain = Envelope.open(sealed, kp.secret, expected_aad=b"record-42") # Sign: hybrid Ed25519 + ML-DSA-65, and state the context you expect on verify signer = HybridSign() sk = signer.generate_keypair() sm = signer.sign(b"important document", sk.secret, context=b"myapp-v1") signer.verify(sm, sk.public, context=b"myapp-v1") # raises VerificationError if invalid ``` -------------------------------- ### qs-migrate scan command usage Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/cli.rst Shows the full usage and options for the qs-migrate scan command, including format, output, severity filtering, and fail-on behavior. Examples demonstrate scanning a path with default options, SARIF output, and minimum severity filtering. ```bash qs-migrate scan [OPTIONS] Options: --format {text,json,sarif} Output format (default: text) --output PATH Write output to file --min-severity {info,medium,high,critical} Minimum severity to report --fail-on {info,medium,high,critical,never} Exit 1 at this severity or above Examples: qs-migrate scan ./src qs-migrate scan ./src --format sarif --output migrate.sarif qs-migrate scan ./src --min-severity high ``` -------------------------------- ### Track migration progress with MigrationStateManager Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/migration.rst Uses MigrationStateManager to transition a key from CLASSICAL_ONLY to HYBRID_TRANSITION and then print migration progress. The example uses a plain dict store, which is only safe for threads in one process; for multi-process or distributed safety, use a store with compare_and_set. The output shows a sample progress dictionary. ```python from quantum_safe.migrate import MigrationStateManager from quantum_safe.types import MigrationState store = {} # replace with Redis / DynamoDB / Postgres mgr = MigrationStateManager(store) mgr.transition( key_id="user-123", from_state=MigrationState.CLASSICAL_ONLY, to_state=MigrationState.HYBRID_TRANSITION, algorithm="X25519+ML-KEM-768", actor="key-rotation-v2", ) progress = mgr.migration_progress() print(progress) # {'classical_only': 847, 'hybrid_transition': 152, 'pqc_only': 1} ``` -------------------------------- ### Node.js: Verify signature with HybridSign and expectedContext Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/interop.rst Reads the signed.cbor and public.cbor files written by the Python example, constructs a HybridSign instance with 'Ed25519+ML-DSA-65-v2', and verifies the signature using the expected context 'deploys-v1'. The verify call throws if the signature is invalid. ```javascript import { readFileSync } from 'node:fs'; import { HybridSign, SignedMessage, PublicKey, utf8 } from 'quantum-safe-ts'; const signer = new HybridSign('Ed25519+ML-DSA-65-v2'); const signed = SignedMessage.fromBytes(readFileSync('signed.cbor')); const pub = PublicKey.fromCbor(readFileSync('public.cbor')); signer.verify(signed, pub, { expectedContext: utf8('deploys-v1') }); // throws if invalid ``` -------------------------------- ### Run a full audit with Auditor.audit Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/audit.rst Example of using the Auditor.audit classmethod to run a compliance audit on a directory. The policy is set to strict, metadata is provided, and the report is printed. If the audit fails, the JSON report is printed and the script exits with code 1. ```python from quantum_safe.audit import Auditor, AuditPolicy report = Auditor.audit( "./src", policy=AuditPolicy.strict(), metadata={"branch": "main", "commit": "abc123"}, ) print(report.summary_line()) if not report.passed: print(report.to_json()) sys.exit(1) ``` -------------------------------- ### Envelope seal and open example Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/protocols.rst Shows how to use Envelope.seal() to encrypt a plaintext to a recipient's public key, serialize the sealed message to bytes for network transmission, deserialize it back, and decrypt with Envelope.open() using the recipient's secret key. ```python # Sender: sealed = Envelope.seal(b"top secret", recipient_public_key) wire = sealed.to_bytes() # send this over the network # Recipient: msg = sealed.from_bytes(wire) plain = Envelope.open(msg, recipient_secret_key) ``` -------------------------------- ### Extract HybridSignature sub-signatures from SignedMessage Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/signatures.rst Shows how to parse the HybridSignature payload from a SignedMessage's signature field. The signature starts with a 1-byte prefix length, followed by the prefix and the HybridSignature payload. The example prints the lengths of the classical (Ed25519, 64 bytes) and PQC (ML-DSA-65, 3309 bytes per FIPS 204) signatures. ```python from quantum_safe.types import HybridSignature # sm.signature is prefix_len (1 byte) || prefix || HybridSignature payload prefix_len = sm.signature[0] hybrid_sig = HybridSignature.from_bytes(sm.signature[1 + prefix_len :]) print(len(hybrid_sig.classical_sig)) # Ed25519: 64 bytes print(len(hybrid_sig.pqc_sig)) # ML-DSA-65: 3309 bytes (FIPS 204) ``` -------------------------------- ### Assess PQC readiness from a requirements.txt string Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/audit.rst Shows the format of lines that SBOMEnricher.from_requirements() parses. Blank lines and comments are skipped, extras and environment markers are removed, and the version is the lowest one guaranteed by the line. ```text cryptography==44.0.5 pycryptodome>=3.20.0 quantum-safe==0.1.0 ``` -------------------------------- ### Docker build and run benchmarks (ENV-2) Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/benchmarks.rst Builds the Docker image with liboqs 0.16.0 (or 0.15.0 via build-arg) and runs KEM and signature benchmark suites, saving JSON results. Use 'docker compose up' to run both suites in one go. ```bash # Build once — compiles liboqs 0.16.0 from source (~3 min on a modern laptop) docker build -t quantum-safe-bench . # For the liboqs 0.15.0 numbers of the papers: docker build --build-arg LIBOQS_TAG=0.15.0 ... # KEM suite: classical + hybrid decomposition + concurrent load curve docker run --rm -v ${PWD}/results:/app/results quantum-safe-bench \ python -X utf8 tests/bench/bench_kem.py --with-pqc \ --save results/bench_kem_$(date +%Y-%m-%d).json # Signature suite: Ed25519 + ML-DSA-65 + HybridSign + X.509 certs docker run --rm -v ${PWD}/results:/app/results quantum-safe-bench \ python -X utf8 tests/bench/bench_signatures.py --with-pqc \ --save results/bench_sigs_$(date +%Y-%m-%d).json # Or run both in one go with docker-compose docker compose up ``` -------------------------------- ### HybridKEM with custom classical and PQC algorithms Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/kem.rst Shows how to instantiate HybridKEM with different algorithm combinations: X25519 with ML-KEM-1024, and P-256 with ML-KEM-768. ```python kem = HybridKEM(classical="X25519", pqc="ML-KEM-1024") kem = HybridKEM(classical="P-256", pqc="ML-KEM-768") ``` -------------------------------- ### Python: Sign with HybridSign and write CBOR files Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/interop.rst Creates a HybridSign instance with 'Ed25519' and 'ML-DSA-65-v2', generates a keypair, signs a message with context b'deploys-v1', and writes the signed message and public key as CBOR files to a temporary directory. The output prints the names of the written files. ```python import pathlib import tempfile from quantum_safe import HybridSign signer = HybridSign("Ed25519", "ML-DSA-65-v2") keys = signer.generate_keypair() signed = signer.sign(b"deploy build 4711", keys.secret, context=b"deploys-v1") out = pathlib.Path(tempfile.mkdtemp()) (out / "signed.cbor").write_bytes(signed.to_cbor()) (out / "public.cbor").write_bytes(keys.public.to_cbor()) print("wrote", sorted(p.name for p in out.iterdir())) ``` -------------------------------- ### LmsSigner.public_key Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/signatures.rst Method to get the serialised LMS public key for use with verify(). ```APIDOC ## LmsSigner.public_key ### Description The serialised LMS public key, for use with verify(). ### Method public_key() ``` -------------------------------- ### Build and serialize a CBOM from a scan Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/audit.rst Shows how to scan a directory, build a CBOM document, and print it as JSON. The scan report's findings become detected assets, and the library's post-quantum algorithms are included as provided assets by default. ```python from quantum_safe.audit.cbom import build_cbom, to_json from quantum_safe.migrate.scanner import Scanner scan = Scanner.scan_directory("./src") cbom = build_cbom(scan, application_name="my-service") print(to_json(cbom)) ``` -------------------------------- ### Basic usage of Sign for ML-DSA-65 signing and verification Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/signatures.rst Shows how to instantiate Sign with default ML-DSA-65, generate a keypair, sign a message with a context, and verify the signature. Verification raises VerificationError on failure. The hedged mode is enabled by default, prepending 32 random bytes before signing. ```python from quantum_safe.signatures import Sign signer = Sign() # ML-DSA-65, hedged kp = signer.generate_keypair() sm = signer.sign(b"hello", kp.secret, context=b"myapp-v1") signer.verify(sm, kp.public, context=b"myapp-v1") # raises VerificationError ``` -------------------------------- ### list_available_backends() Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/backends.rst Returns availability status for all known backends. Useful for diagnostics, e.g., python -c "from quantum_safe.backends import list_available_backends; print(list_available_backends())". ```APIDOC ## list_available_backends() ### Description Returns availability status for all known backends. Useful for diagnostics, e.g., python -c "from quantum_safe.backends import list_available_backends; print(list_available_backends())". ### Returns - A dictionary or similar structure indicating availability status for each known backend. ``` -------------------------------- ### qs-audit compliance command usage and examples Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/cli.rst Generates a NIST SP 800-208 compliance report. Supports text (default) or JSON output. ```bash qs-audit compliance [OPTIONS] Options: --format {text,json} Output format (default: text) --output PATH Write report to file Examples: qs-audit compliance ./src --format json --output compliance.json ``` -------------------------------- ### Check migration progress with qs-migrate status Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/migration.rst The 'qs-migrate status' command checks the migration progress. The example shows the command without additional arguments. ```bash # Check migration progress qs-migrate status ``` -------------------------------- ### Deterministic signatures with hedged=False Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/signatures.rst Disable hedging with hedged=False to get deterministic signatures: the same message produces identical signatures. Use only when deterministic signatures are required. ```python signer = HybridSign(hedged=False) sm1 = signer.sign(b"same", kp.secret) sm2 = signer.sign(b"same", kp.secret) assert sm1.signature == sm2.signature # deterministic ``` -------------------------------- ### upgrade_kem_key Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/migrate.rst Upgrades a classical KEM key to a hybrid key. The original classical sub-key is retained in the output. Raises ValueError for invalid combinations or unknown backend, and BackendNotAvailable if the backend is not installed. ```APIDOC ## upgrade_kem_key ### Description Upgrade a classical KEM key to a hybrid key. The original classical sub-key is retained in the output — it is the same bytes as classical_secret_bytes / classical_public_bytes, just wrapped alongside the new PQC component. ### Method classmethod ### Signature upgrade_kem_key(classical_secret_bytes, classical_public_bytes, classical_algorithm='X25519', target_pqc='ML-KEM-768', backend='auto') ### Parameters - **classical_secret_bytes** (bytes) - Required - Raw bytes of the classical private key. For X25519: 32 bytes. - **classical_public_bytes** (bytes) - Required - Raw bytes of the classical public key. For X25519: 32 bytes. - **classical_algorithm** (str) - Optional - "X25519" or "P-256". Default: "X25519". - **target_pqc** (str) - Optional - PQC algorithm to add. Default "ML-KEM-768". - **backend** (str) - Optional - PQC backend. Default "auto". ### Returns UpgradeResult with the new hybrid KeyPair. ### Raises - **ValueError** - if `classical_algorithm` and `target_pqc` are not an approved hybrid KEM combination, or the backend name is unknown. - **BackendNotAvailable** - if the requested backend is not installed. ### Return Type UpgradeResult ``` -------------------------------- ### Scan and migrate with qs-audit and qs-migrate CLI Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/README.md Use qs-audit to scan for classical crypto with fix hints, output SARIF for GitHub Code Scanning, generate a CycloneDX Cryptographic Bill of Materials, and produce a CNSA 2.0 parameter-set report. Use qs-migrate status to check migration progress per key. ```bash qs-audit scan ./src # find classical crypto, with fix hints qs-audit scan ./src --format sarif --output audit.sarif # GitHub Code Scanning qs-audit cbom ./src --output cbom.json # CycloneDX Cryptographic Bill of Materials qs-audit cnsa2 # CNSA 2.0 parameter-set report qs-migrate status # migration progress per key ``` -------------------------------- ### Python: Using -v2 signature format with Sign and HybridSign Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/signatures.rst Shows how to create a pure ML-DSA signer and a hybrid signer using the -v2 format, generate a keypair, sign a document with a context, and verify the signature. The -v2 format is byte-compatible with quantum-safe-ts and is the default hybrid format from version 1.0.0. ```python from quantum_safe import HybridSign from quantum_safe.signatures import Sign signer = Sign("ML-DSA-65-v2") # pure ML-DSA hybrid = HybridSign("Ed25519", "ML-DSA-65-v2") # Ed25519+ML-DSA-65-v2 kp = hybrid.generate_keypair() sm = hybrid.sign(b"document", kp.secret, context=b"myapp-v1") hybrid.verify(sm, kp.public, context=b"myapp-v1") ``` -------------------------------- ### quantum_safe.kem.algorithms.canonical_hybrid_name(classical, pqc) Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/kem.rst Returns the canonical algorithm string for a hybrid combination. For example, canonical_hybrid_name("X25519", "ML-KEM-768") returns "X25519+ML-KEM-768". ```APIDOC ## canonical_hybrid_name(classical, pqc) ### Description Returns the canonical algorithm string for a hybrid combination. ### Parameters - **classical** (string) - Required - The classical algorithm name. - **pqc** (string) - Required - The PQC algorithm name. ### Returns - The canonical hybrid algorithm string, e.g., "X25519+ML-KEM-768". ``` -------------------------------- ### Run signature benchmarks natively Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/benchmarks.rst Runs the signature benchmark script with optional PQC support and JSON output. The --with-pqc flag adds standalone ML-DSA-65, which requires liboqs. ```bash # Ed25519 baselines + HybridSign + X.509 certs python -X utf8 tests/bench/bench_signatures.py # Add standalone ML-DSA-65 (requires liboqs) python -X utf8 tests/bench/bench_signatures.py --with-pqc # Save JSON snapshot python -X utf8 tests/bench/bench_signatures.py --with-pqc \ --save results/bench_sigs_$(date +%Y-%m-%d).json ``` -------------------------------- ### Sign with ML-DSA-65 Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/signatures.rst Creates a Sign instance with the ML-DSA-65 algorithm, generates a keypair, signs a document with a context, and verifies the signature. ```python from quantum_safe import Sign signer = Sign("ML-DSA-65") kp = signer.generate_keypair() sm = signer.sign(b"document", kp.secret, context=b"myapp") signer.verify(sm, kp.public, context=b"myapp") ``` -------------------------------- ### Use Auditor.ci_gate in CI pipeline Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/audit.rst Example of using the Auditor.ci_gate classmethod to run an audit and obtain a shell exit code, designed for CI pipeline steps. The exit code is passed to sys.exit. ```python exit_code = Auditor.ci_gate("./src", output_sarif="audit.sarif") sys.exit(exit_code) ``` -------------------------------- ### InsecureOperationError Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/exceptions.rst Raised when an attempted operation is insecure and has been blocked. Examples include using an algorithm below the required security level, disabling hybrid mode without an explicit override, or reusing a nonce in a scheme that prohibits it. ```APIDOC ## InsecureOperationError ### Description Attempted operation is insecure and has been blocked. Examples include using an algorithm below the required security level, disabling hybrid mode without an explicit override, or reusing a nonce in a scheme that prohibits it. ### Constructor `InsecureOperationError(message, **context)` ### Parameters - **message** (str) - Required - The human-readable message. - **context** (dict) - Optional - Additional context for structured logging. ### Attributes - **code** (str) - Stable machine-readable identifier of the error type. - **message** (str) - The human-readable message. - **context** (dict) - The context dictionary provided at construction. ``` -------------------------------- ### SBOMEnricher.from_requirements(requirements_txt) Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/api/audit.rst Assesses PQC readiness from a requirements.txt string. This method does not require a full SBOM and is useful as a quick check during CI. It parses lines of the form 'package==version' and returns a list of ComponentAssessment objects. ```APIDOC ## SBOMEnricher.from_requirements(requirements_txt) ### Description Assesses PQC readiness from a requirements.txt string. Does not require a full SBOM — useful as a quick check during CI. Parses lines of the form `cryptography==44.0.5`, `pycryptodome>=3.20.0`, `quantum-safe==0.1.0`. Blank lines and `#` comment lines are skipped, and extras (`[crypto]`) and environment markers (after `;`) are removed. The version is the lowest one the line guarantees: the first `==`, `===`, `~=`, `>=` or `>` specifier, so for `pkg>=1.0,<2` it is `1.0`. An upper bound (`<`, `<=`), `!=` or a line without a specifier gives no version, and the component is then reported as UNKNOWN. ### Method Classmethod ### Signature `SBOMEnricher.from_requirements(requirements_txt)` ### Parameters - **requirements_txt** (str) - Required - Contents of a requirements.txt file. ### Returns - **list[ComponentAssessment]** - List of ComponentAssessment objects, one per package line, in file order. ### Usage Example ```python assessments = SBOMEnricher.from_requirements(requirements_txt) ``` ``` -------------------------------- ### Generate CNSA 2.0 compliance report Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/compliance.rst Creates a compliance report for a given KEM, signature, and hash algorithm, then renders and checks compliance. The example uses X25519+ML-KEM-768 and Ed25519+ML-DSA-65, which results in report.compliant being False. ```python from quantum_safe.compliance import cnsa2 report = cnsa2.report( kem="X25519+ML-KEM-768", signature="Ed25519+ML-DSA-65", hash_algorithm="SHA-256", ) print(report.render()) assert not report.compliant ``` -------------------------------- ### Verify with context parameter Source: https://github.com/animeshshaw/quantum-safe-py/blob/master/docs/guides/upgrading.rst Demonstrates the new context parameter in verify(). The context must match the one used during signing, otherwise VerificationError is raised. ```python from quantum_safe import Sign, VerificationError signer = Sign("ML-DSA-65") kp = signer.generate_keypair() sm = signer.sign(b"transfer 5", kp.secret, context=b"login") signer.verify(sm, kp.public, context=b"login") # OK: the context you expect try: signer.verify(sm, kp.public, context=b"payments") # a different purpose except VerificationError: print("a signature made for 'login' is refused for 'payments'") ```