### Setup Standard venv for liboqs-python Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Create and activate a standard Python virtual environment (venv) and install the liboqs-python package. Note that liboqs is auto-installed in the user's home directory. ```bash # Create virtual environment python3 -m venv venv source venv/bin/activate # Linux/macOS # or venv\Scripts\activate # Windows # Install liboqs-python pip install liboqs-python # liboqs is auto-installed in $HOME/_oqs ``` -------------------------------- ### Install liboqs-python Wrapper Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Clone the liboqs-python repository, navigate into the directory, and install the wrapper using pip. ```shell git clone --depth=1 https://github.com/open-quantum-safe/liboqs-python cd liboqs-python pip install . ``` -------------------------------- ### Run Key Encapsulation Example in Docker Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Execute the key encapsulation example within the oqs-python Docker container. This command activates the virtual environment and runs the 'kem.py' example script. ```shell docker run -it oqs-python sh -c ". venv/bin/activate && python liboqs-python/examples/kem.py" ``` -------------------------------- ### Run liboqs-python Examples Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Execute the provided Python example scripts for Key Encapsulation Mechanisms (KEM), signatures, secure transport, and random number generation. ```shell python3 liboqs-python/examples/kem.py ``` ```shell python3 liboqs-python/examples/sig.py ``` ```shell python3 liboqs-python/examples/stfl_sig.py ``` ```shell python3 liboqs-python/examples/rand.py ``` -------------------------------- ### Signature Example Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/CHANGES.md Example demonstrating the usage of signature functionalities. ```python # Added a signature example ``` -------------------------------- ### Install liboqs and Verify Detection Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md After installing liboqs to a standard location, liboqs-python can automatically detect and use it. This snippet shows how to verify the installation and version. ```bash # After installing liboqs: cmake --build liboqs/build --target install # liboqs-python will find it automatically python -c "import oqs; print(oqs.oqs_version())" ``` -------------------------------- ### Setup venv with Custom liboqs Path Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Configure a Python virtual environment (venv) to use a custom installation path for liboqs. This involves setting the OQS_INSTALL_PATH environment variable before installing and using the library. ```bash # Create and activate venv python3 -m venv venv source venv/bin/activate # Point to custom liboqs export OQS_INSTALL_PATH=/opt/my-liboqs # Install and use pip install liboqs-python python script.py ``` -------------------------------- ### Setup Conda Environment for liboqs-python Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Create and activate a Conda environment for Python and install the liboqs-python package. Similar to venv, liboqs is auto-installed in the user's home directory. ```bash # Create environment conda create -n quantum-safe python=3.10 conda activate quantum-safe # Install liboqs-python pip install liboqs-python # liboqs auto-installs to $HOME/_oqs ``` -------------------------------- ### Configure liboqs-python in Docker Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Set up a Docker environment for liboqs-python by installing dependencies, setting environment variables for the installation path and library path, and installing the Python package. ```dockerfile FROM python:3.10 # Install dependencies RUN apt-get update && apt-get install -y \ build-essential cmake git # Set liboqs installation path ENV OQS_INSTALL_PATH=/opt/liboqs ENV LD_LIBRARY_PATH=/opt/liboqs/lib:$LD_LIBRARY_PATH # Install liboqs-python (auto-installs liboqs) RUN pip install liboqs-python # Test installation RUN python -c "import oqs; print(oqs.oqs_version())" ``` -------------------------------- ### Set OQS_INSTALL_PATH for Custom Installation Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Specify the directory where liboqs is installed or should be installed. This is used for custom locations or isolated environments and for auto-installation if liboqs is not found. ```bash # Unix/Linux/macOS export OQS_INSTALL_PATH=/opt/liboqs ``` ```bash # Windows (Command Prompt) set OQS_INSTALL_PATH=C:\liboqs ``` ```bash # Windows (PowerShell) $env:OQS_INSTALL_PATH = "C:\liboqs" ``` -------------------------------- ### Verify liboqs Installation Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Confirm that liboqs is correctly installed and accessible by the Python wrapper by checking the liboqs version. ```python import oqs; print(oqs.oqs_version()) ``` -------------------------------- ### Setup Development Environment with Docker Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Launch a Docker container for development, mounting the current project directory into the container's '/app' directory. This allows for interactive development within the containerized environment. ```shell docker run --rm -it --workdir=/app -v ${PWD}:/app oqs-python /bin/bash ``` -------------------------------- ### Clone and Build liboqs Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Clone the liboqs repository, configure the build with CMake, and build the project. Adjust --parallel to your system's core count. The install step may require sudo. ```shell git clone --depth=1 https://github.com/open-quantum-safe/liboqs cmake -S liboqs -B liboqs/build -DBUILD_SHARED_LIBS=ON cmake --build liboqs/build --parallel 8 cmake --build liboqs/build --target install ``` -------------------------------- ### Hybrid Signing (Post-Quantum Example) Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/signature.md Demonstrates a hybrid signing approach by first signing with a post-quantum algorithm. In a real-world scenario, a classical signature would also be generated and combined. ```python import oqs import hashlib message = b"Important message" # Sign with post-quantum algorithm with oqs.Signature("ML-DSA-44") as pq_signer: pq_public_key = pq_signer.generate_keypair() pq_signature = pq_signer.sign(message) # In production, also use classical signature (e.g., RSA-4096, ECDSA) # For now, just demonstrate hybrid approach hybrid_signature = { "pq_algorithm": "ML-DSA-44", "pq_public_key": pq_public_key.hex(), "pq_signature": pq_signature.hex(), # "classical_signature": classical_sig.hex() # Add classical sig in real use } # Verification verifies both classical and post-quantum signatures with oqs.Signature("ML-DSA-44") as verifier: is_valid = verifier.verify( message, bytes.fromhex(hybrid_signature["pq_signature"]), bytes.fromhex(hybrid_signature["pq_public_key"]) ) print(f"PQ Signature valid: {is_valid}") ``` -------------------------------- ### Check liboqs-python Installation Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Verify if the liboqs-python package is installed using pip. ```bash pip show liboqs-python ``` -------------------------------- ### Automatic liboqs Installation Trigger Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/module-overview.md The first import of the 'oqs' module triggers automatic download and installation of liboqs if it's not found. This ensures the library is ready to use. ```python # First import triggers automatic installation if needed import oqs # liboqs is now available ``` -------------------------------- ### Configure liboqs with Custom Install Prefix and Windows Symbols Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Configure the liboqs build using CMake, specifying a custom installation prefix and enabling symbol export for Windows. Shared libraries must be enabled. ```shell cmake -S liboqs -B liboqs/build -DCMAKE_INSTALL_PREFIX="C:\liboqs" -DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS=TRUE -DBUILD_SHARED_LIBS=ON ``` -------------------------------- ### Basic KEM Usage with liboqs-python Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/README.md Demonstrates a basic post-quantum key exchange using the KeyEncapsulation class. This example shows how Alice and Bob can establish a shared secret using the ML-KEM-512 algorithm. ```python import oqs # Key encapsulation exchange with oqs.KeyEncapsulation("ML-KEM-512") as alice: alice_public = alice.generate_keypair() with oqs.KeyEncapsulation("ML-KEM-512") as bob: ciphertext, bob_secret = bob.encap_secret(alice_public) alice_secret = alice.decap_secret(ciphertext) assert alice_secret == bob_secret ``` -------------------------------- ### Configure liboqs-python on Windows (Command Prompt) Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Set the installation path and add the liboqs binary directory to the system PATH environment variable in the Windows Command Prompt. This allows the system to find the required DLLs. ```cmd REM Set installation path set OQS_INSTALL_PATH=C:\liboqs REM Add to system PATH for DLL loading set PATH=%PATH%;C:\liboqs\bin REM Run Python python script.py ``` -------------------------------- ### Check liboqs and Wrapper Versions Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Compare the installed liboqs library version with the liboqs-python wrapper version to diagnose potential mismatches. ```python import oqs; print(f'liboqs: {oqs.oqs_version()}, wrapper: {oqs.oqs_python_version()}') ``` -------------------------------- ### Basic Signature Usage with liboqs-python Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/README.md Illustrates basic post-quantum digital signature generation and verification using the Signature class. This example uses the ML-DSA-44 algorithm to sign a message and then verify the signature. ```python import oqs message = b"Message to authenticate" with oqs.Signature("ML-DSA-44") as signer: public_key = signer.generate_keypair() signature = signer.sign(message) with oqs.Signature("ML-DSA-44") as verifier: is_valid = verifier.verify(message, signature, public_key) print(f"Signature valid: {is_valid}") ``` -------------------------------- ### RNG Example Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/CHANGES.md Example demonstrating the usage of Random Number Generator (RNG) functionalities. ```python # Added an RNG example ``` -------------------------------- ### Configure liboqs-python on Windows (PowerShell) Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Set the installation path and append the liboqs binary directory to the system PATH environment variable using PowerShell. This is the PowerShell equivalent for Windows configuration. ```powershell # Set installation path $env:OQS_INSTALL_PATH = "C:\liboqs" # Add to system PATH $env:PATH += ";C:\liboqs\bin" # Run Python python script.py ``` -------------------------------- ### Configure liboqs-python on macOS Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Set the installation path and dynamic library path for liboqs on macOS, especially when installed via Homebrew. This ensures the Python environment can locate the necessary libraries. ```bash # With Homebrew export OQS_INSTALL_PATH=/usr/local/opt/liboqs export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:/usr/local/opt/liboqs/lib python script.py ``` -------------------------------- ### Listing Stateful Signature Algorithms by Family Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/stateful-signature.md Provides examples of how to filter and list available stateful signature algorithms based on their family prefixes, such as XMSS, XMSSMT, and LMS. ```python import oqs # XMSS (single-level hash-based signatures) xmss_algs = [ alg for alg in oqs.get_enabled_stateful_sig_mechanisms() if alg.startswith("XMSS-") ] print(f"Available XMSS: {xmss_algs}") # XMSSMT (multi-level hash-based signatures) xmlsmt_algs = [ alg for alg in oqs.get_enabled_stateful_sig_mechanisms() if alg.startswith("XMSSMT-") ] print(f"Available XMSSMT: {xmlsmt_algs}") # LMS (Leighton-Micali signatures, verify-only) lms_algs = [ alg for alg in oqs.get_enabled_stateful_sig_mechanisms() if alg.startswith("LMS") ] print(f"Available LMS: {lms_algs}") ``` -------------------------------- ### String Representation Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Shows how to get a string representation of a KeyEncapsulation instance. ```APIDOC ## String Representation ### `__repr__() -> str` Returns a string representation of the instance: ```python >>> str(kem) "Key encapsulation mechanism: ML-KEM-512" ``` ``` -------------------------------- ### Configure Custom liboqs Installation Path Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md To use a liboqs installation located in a custom directory, set the OQS_INSTALL_PATH environment variable before running Python. This snippet demonstrates the process. ```bash # Install liboqs to custom location cmake --build liboqs/build --target install \ -DCMAKE_INSTALL_PREFIX=/opt/my-liboqs # Configure liboqs-python to use it export OQS_INSTALL_PATH=/opt/my-liboqs python -c "import oqs; print(oqs.oqs_version())" ``` -------------------------------- ### Configure liboqs-python on Linux Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Set the installation path and library path for liboqs on Linux systems. This is typically done before running Python scripts that utilize the library. ```bash # Typical installation export OQS_INSTALL_PATH=/usr/local/opt/liboqs export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/opt/liboqs/lib python script.py ``` -------------------------------- ### Basic KEM Exchange Example Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Demonstrates a standard Key Encapsulation Mechanism (KEM) exchange between two parties (Alice and Bob). This involves generating a key pair, encapsulating a secret using the recipient's public key, and then decapsulating the secret using the corresponding private key. Asserts that the secrets match. ```python import oqs messag = b"This is a test message" # Create Alice's KEM instance with oqs.KeyEncapsulation("ML-KEM-512") as alice: alice_public = alice.generate_keypair() # Create Bob's KEM instance with oqs.KeyEncapsulation("ML-KEM-512") as bob: # Bob encapsulates using Alice's public key ciphertext, bob_secret = bob.encap_secret(alice_public) # Alice decapsulates to get the same secret alice_secret = alice.decap_secret(ciphertext) # Secrets match! assert alice_secret == bob_secret # Use the secret for further encryption/decryption # (with AES-256 or other symmetric cipher) ``` -------------------------------- ### Key Encapsulation and Decapsulation Example Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Demonstrates the full lifecycle of key encapsulation and decapsulation using the ML-KEM-512 algorithm. It shows how to generate a key pair, export and restore a secret key, encapsulate a secret on the sender side, and decapsulate it on the receiver side, verifying the shared secrets match. ```python import oqs # See encap_secret example above for full context with oqs.KeyEncapsulation("ML-KEM-512") as receiver: public_key = receiver.generate_keypair() secret_key = receiver.export_secret_key() # Later, restore the receiver's session receiver_restored = oqs.KeyEncapsulation("ML-KEM-512", secret_key=secret_key) with oqs.KeyEncapsulation("ML-KEM-512") as sender: ciphertext, sender_secret = sender.encap_secret(public_key) receiver_secret = receiver_restored.decap_secret(ciphertext) assert receiver_secret == sender_secret ``` -------------------------------- ### Signature Algorithm Names Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/types.md Provides examples of signature algorithm names as strings, such as ML-DSA, FALCON, and others. These are used for signature operations. ```python "ML-DSA-44" # ML-DSA (NIST FIPS 204) with 2-bit NIST level "ML-DSA-65" # ML-DSA with 3-bit NIST level "ML-DSA-87" # ML-DSA with 5-bit NIST level "FALCON-512" # FALCON (if enabled) "FALCON-1024" # FALCON (if enabled) # Others (if enabled) ``` -------------------------------- ### Configure OQS_INSTALL_PATH in Python Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Set the OQS_INSTALL_PATH environment variable within a Python script before importing the oqs library to direct it to a custom liboqs installation. ```python import os os.environ["OQS_INSTALL_PATH"] = "/opt/liboqs" import oqs # liboqs will be loaded from /opt/liboqs/lib (or /opt/liboqs/bin on Windows) ``` -------------------------------- ### List All Supported KEM Algorithms Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Retrieves a tuple of all Key Encapsulation Mechanism (KEM) algorithms that are supported by the liboqs-python installation, including those that may be disabled. ```python supported = oqs.get_supported_kem_mechanisms() print(supported) # All supported, including disabled ones ``` -------------------------------- ### Set OQS_INSTALL_PATH Environment Variable Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Set the OQS_INSTALL_PATH environment variable to specify the liboqs installation directory. This is an alternative to setting CMAKE_INSTALL_PREFIX during the build. ```shell export OQS_INSTALL_PATH=/path/to/liboqs ``` -------------------------------- ### Get liboqs Version with OQS_VERSION Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md Retrieve the version string of the liboqs library using OQS_VERSION. This can be controlled by the PYOQS_VERSION environment variable for specific installations or the main branch. ```python import oqs print(f"Will install liboqs: {oqs.OQS_VERSION}") # Controlled by environment: # export PYOQS_VERSION=0.15.0 # Specific version # export PYOQS_VERSION=latest # Main branch ``` -------------------------------- ### Initialize Signature Instance Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/signature.md Demonstrates initializing a Signature instance with a given algorithm name. It also shows usage with a context manager and session resumption using a pre-existing secret key. ```python import oqs # Create a new Signature instance sig = oqs.Signature("ML-DSA-44") # With context manager (recommended) with oqs.Signature("ML-DSA-65") as signer: public_key = signer.generate_keypair() # ... # Session resumption with existing secret key secret_key = signer.export_secret_key() signer.free() # Later, restore the session signer_restored = oqs.Signature("ML-DSA-44", secret_key=secret_key) ``` -------------------------------- ### Initialize and Use StatefulSignature Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/stateful-signature.md Demonstrates how to initialize a StatefulSignature instance for a specific algorithm, use it with a context manager for key generation, and resume a session using an exported secret key. ```python import oqs # Create a new stateful signature instance stfl_sig = oqs.StatefulSignature("XMSS-SHA2_10_256") # With context manager (recommended) with oqs.StatefulSignature("XMSS-SHA2_10_256") as signer: public_key = signer.generate_keypair() # ... # Session resumption with existing secret key secret_key = signer.export_secret_key() signer.free() # Later, restore the session signer_restored = oqs.StatefulSignature("XMSS-SHA2_10_256", secret_key=secret_key) ``` -------------------------------- ### Set PYOQS_VERSION for Automatic liboqs Installation Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Override the default liboqs version installed automatically by liboqs-python by setting the PYOQS_VERSION environment variable. Use 'latest' to install from the main branch. ```shell export PYOQS_VERSION=0.15.0 # install a specific liboqs release ``` ```shell export PYOQS_VERSION=latest # install liboqs from main (HEAD) ``` -------------------------------- ### Initialize KeyEncapsulation Instance Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Instantiate a KeyEncapsulation object for a specific KEM algorithm. The recommended approach is to use a context manager for automatic resource management. Alternatively, you can manually manage the instance or restore a session using a previously exported secret key. ```python import oqs # Create a new KEM instance kem = oqs.KeyEncapsulation("ML-KEM-512") # With context manager (recommended) with oqs.KeyEncapsulation("ML-KEM-768") as kem: public_key = kem.generate_keypair() # ... # Session resumption with existing secret key secret_key = kem.export_secret_key() kem.free() # Later, restore the session kem_restored = oqs.KeyEncapsulation("ML-KEM-512", secret_key=secret_key) ``` -------------------------------- ### Check OQS_INSTALL_PATH and Library Existence Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Verify that the OQS_INSTALL_PATH environment variable is set correctly and that the liboqs shared library exists in the expected location. ```bash echo $OQS_INSTALL_PATH # Should be set or default to $HOME/_oqs ls $OQS_INSTALL_PATH/lib/liboqs* ``` -------------------------------- ### KeyEncapsulation Object Initialization and Freeing Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Shows how to instantiate a KeyEncapsulation object for a specific algorithm and explicitly free its resources when not using a context manager. This is useful for manual resource management. ```python import oqs kem = oqs.KeyEncapsulation("ML-KEM-512") public_key = kem.generate_keypair() # ... use kem ... kem.free() # Explicitly free when not using context manager ``` -------------------------------- ### Basic Stateful Signing and Verification Flow Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/stateful-signature.md Demonstrates the fundamental process of generating a key pair, signing a message, and verifying the signature using `StatefulSignature`. Ensure the same algorithm is used for signing and verification. ```python import oqs message = b"This is the message to sign" with oqs.StatefulSignature("XMSS-SHA2_10_256") as signer: public_key = signer.generate_keypair() print(f"Total signatures: {signer.sigs_total()}") signature = signer.sign(message) print(f"Remaining signatures: {signer.sigs_remaining()}") with oqs.StatefulSignature("XMSS-SHA2_10_256") as verifier: is_valid = verifier.verify(message, signature, public_key) print(f"Signature valid: {is_valid}") # True ``` -------------------------------- ### Context-Aware Signing and Verification Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/signature.md Illustrates how to perform signing and verification with context binding using `sign_with_ctx_str` and `verify_with_ctx_str`. This ensures the signature is bound to a specific context, enhancing security. The algorithm must support context operations. ```python import oqs message = b"Message requiring context binding" with oqs.Signature("ML-DSA-44") as signer: if not oqs.sig_supports_context("ML-DSA-44"): raise RuntimeError("Algorithm does not support context signing") public_key = signer.generate_keypair() context = b"my-application-v1" signature = signer.sign_with_ctx_str(message, context) with oqs.Signature("ML-DSA-44") as verifier: # Correct context succeeds is_valid = verifier.verify_with_ctx_str(message, signature, context, public_key) assert is_valid # Wrong context fails (signature binding) is_valid = verifier.verify_with_ctx_str(message, signature, b"different-context", public_key) assert not is_valid ``` -------------------------------- ### Stateful Signature Usage with liboqs-python Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/README.md Demonstrates the usage of stateful signatures with the StatefulSignature class, specifically for hash-based signatures like XMSS. It shows key pair generation, signing, and querying the number of available signatures. ```python import oqs with oqs.StatefulSignature("XMSS-SHA2_10_256") as signer: public_key = signer.generate_keypair() signature = signer.sign(b"Message") print(f"Total signatures: {signer.sigs_total()}") # 1024 print(f"Remaining: {signer.sigs_remaining()}") # 1023 ``` -------------------------------- ### Safe Algorithm Selection in Python Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/README.md Demonstrates how to safely select and use a Key Encapsulation Mechanism (KEM) algorithm. It first checks if the algorithm is enabled before proceeding to use it. ```python if oqs.is_kem_enabled("ML-KEM-512"): with oqs.KeyEncapsulation("ML-KEM-512") as kem: # Use KEM pass else: print("Algorithm not available") ``` -------------------------------- ### Get Library Version Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/CHANGES.md Function to retrieve the version of the liboqs library. ```python oqs_version() ``` -------------------------------- ### native() Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md Gets a handle to the native liboqs library as a ctypes CDLL object. ```APIDOC ## native() ### Description Get a handle to the native liboqs library (ctypes CDLL object). ### Method N/A (Python function) ### Endpoint N/A (Python function) ### Parameters None ### Returns `ctypes.CDLL` - Handle to the loaded liboqs shared library ### Raises No exceptions ### Details - Returns the underlying C library handle - Advanced users can use this for direct FFI calls - Module initialization loads liboqs automatically or installs it on-demand ### Example ```python import oqs import ctypes lib = oqs.native() # Direct C library calls (advanced) lib.OQS_init() # Access function pointers lib.OQS_version.restype = ctypes.c_char_p version = lib.OQS_version().decode() print(version) ``` ``` -------------------------------- ### Get Python Wrapper Version Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/CHANGES.md Function to retrieve the version of the liboqs-python wrapper. ```python oqs_python_version() ``` -------------------------------- ### KeyEncapsulation Context Manager Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Demonstrates the recommended approach to using KeyEncapsulation objects within a context manager, ensuring automatic resource cleanup. ```APIDOC ## KeyEncapsulation Context Manager ### `__enter__() -> KeyEncapsulation` Enter context manager (returns self). ### `__exit__(exc_type, exc_value, traceback) -> None` Exit context manager and call `free()` to clean up resources. **Example**: ```python # Recommended approach with oqs.KeyEncapsulation("ML-KEM-512") as kem: public_key = kem.generate_keypair() ciphertext, secret = kem.encap_secret(peer_public_key) # Automatically freed here ``` ``` -------------------------------- ### Get String Representation of KeyEncapsulation Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Retrieves a human-readable string representation of the KeyEncapsulation instance, typically showing the algorithm name. ```python >>> str(kem) "Key encapsulation mechanism: ML-KEM-512" ``` -------------------------------- ### List Enabled KEM Algorithms Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Retrieves a tuple of all Key Encapsulation Mechanism (KEM) algorithms that are currently enabled in the liboqs-python installation. ```python enabled = oqs.get_enabled_kem_mechanisms() print(enabled) # ('ML-KEM-512', 'ML-KEM-768', 'ML-KEM-1024', ...) ``` -------------------------------- ### Basic Stateful Signing and Verification Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/stateful-signature.md Demonstrates the fundamental workflow of generating a key pair, signing a message, and verifying the signature using the StatefulSignature class. ```APIDOC ## Common Patterns ### Basic Stateful Signing and Verification ```python import oqs message = b"This is the message to sign" with oqs.StatefulSignature("XMSS-SHA2_10_256") as signer: public_key = signer.generate_keypair() print(f"Total signatures: {signer.sigs_total()}") signature = signer.sign(message) print(f"Remaining signatures: {signer.sigs_remaining()}") with oqs.StatefulSignature("XMSS-SHA2_10_256") as verifier: is_valid = verifier.verify(message, signature, public_key) print(f"Signature valid: {is_valid}") # True ``` ``` -------------------------------- ### Build liboqs with CMake Flags Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md These CMake flags are automatically applied by liboqs-python during installation. Customization requires manual pre-installation of liboqs. ```bash cmake -S liboqs -B liboqs/build \ -DBUILD_SHARED_LIBS=ON \ -DOQS_BUILD_ONLY_LIB=ON \ -DOQS_ENABLE_SIG_STFL_LMS=ON \ -DOQS_ENABLE_SIG_STFL_XMSS=ON \ -DOQS_HAZARDOUS_EXPERIMENTAL_ENABLE_SIG_STFL_KEY_SIG_GEN=ON \ -DCMAKE_INSTALL_PREFIX=$OQS_INSTALL_PATH ``` -------------------------------- ### Basic Signing and Verification with Signature Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/signature.md Demonstrates the fundamental process of generating a key pair, signing a message, and verifying the signature using the Signature API. Ensure the algorithm is enabled before use. ```python import oqs message = b"This is the message to sign" with oqs.Signature("ML-DSA-44") as signer: public_key = signer.generate_keypair() signature = signer.sign(message) with oqs.Signature("ML-DSA-44") as verifier: is_valid = verifier.verify(message, signature, public_key) print(f"Signature valid: {is_valid}") # True ``` -------------------------------- ### Get String Representation of Signature Instance Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/signature.md Obtain a string representation of a Signature instance, typically showing the algorithm mechanism used. ```python >>> str(sig) "Signature mechanism: ML-DSA-44" ``` -------------------------------- ### MechanismNotSupportedError Exception Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md This exception is raised when a requested cryptographic algorithm is not supported by the installed liboqs library. It provides details about the algorithm name that was not found. ```APIDOC ## MechanismNotSupportedError ### Description Exception raised when an algorithm is not supported by liboqs. ### Source `oqs/oqs.py:328-346` ### Constructor ```python def __init__( self, alg_name: str, supported: Optional[Iterable[str]] = None ) -> None: ``` ### Attributes | Attribute | Type | Description | |-----------|------|-------------| | `alg_name` | `str` | The algorithm name that was requested | | `message` | `str` | Human-readable error message | ### Example ```python import oqs try: kem = oqs.KeyEncapsulation("NONEXISTENT-ALGORITHM") except oqs.MechanismNotSupportedError as e: print(f"Algorithm not supported: {e.alg_name}") print(f"Message: {e.message}") ``` ``` -------------------------------- ### Context-Aware Signing Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/signature.md Illustrates how to perform signing and verification with context binding, ensuring the signature is tied to a specific context. ```APIDOC ## Context-Aware Signing ```python import oqs message = b"Message requiring context binding" with oqs.Signature("ML-DSA-44") as signer: if not oqs.sig_supports_context("ML-DSA-44"): raise RuntimeError("Algorithm does not support context signing") public_key = signer.generate_keypair() context = b"my-application-v1" signature = signer.sign_with_ctx_str(message, context) with oqs.Signature("ML-DSA-44") as verifier: # Correct context succeeds is_valid = verifier.verify_with_ctx_str(message, signature, context, public_key) assert is_valid # Wrong context fails (signature binding) is_valid = verifier.verify_with_ctx_str(message, signature, b"different-context", public_key) assert not is_valid ``` ``` -------------------------------- ### Set PYOQS_VERSION Environment Variable Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/module-overview.md Control the specific version of liboqs to be automatically installed by setting the PYOQS_VERSION environment variable before importing 'oqs'. ```bash export PYOQS_VERSION=0.15.0 # Install specific version ``` ```bash export PYOQS_VERSION=latest # Install from main branch ``` -------------------------------- ### Basic Signing and Verification Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/signature.md Demonstrates the fundamental process of generating a key pair, signing a message, and verifying the signature. ```APIDOC ## Basic Signing and Verification ```python import oqs message = b"This is the message to sign" with oqs.Signature("ML-DSA-44") as signer: public_key = signer.generate_keypair() signature = signer.sign(message) with oqs.Signature("ML-DSA-44") as verifier: is_valid = verifier.verify(message, signature, public_key) print(f"Signature valid: {is_valid}") # True ``` ``` -------------------------------- ### List and Inspect Supported Algorithms Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md Enumerates all supported Key Encapsulation Mechanisms (KEMs) and Signature (SIG) algorithms, indicating whether each is enabled. Also checks if signature algorithms support contexts. ```python import oqs def list_all_algorithms(): """List and classify all supported algorithms.""" print("=== KEM Algorithms ===") for alg in oqs.get_supported_kem_mechanisms(): status = "enabled" if oqs.is_kem_enabled(alg) else "disabled" print(f" {alg}: {status}") print("\n=== Signature Algorithms ===") for alg in oqs.get_supported_sig_mechanisms(): status = "enabled" if oqs.is_sig_enabled(alg) else "disabled" ctx = " (supports context)" if oqs.sig_supports_context(alg) else "" print(f" {alg}: {status}{ctx}") print("\n=== Stateful Signature Algorithms ===") for alg in oqs.get_supported_stateful_sig_mechanisms(): status = "enabled" if oqs.is_sig_enabled(alg) else "disabled" print(f" {alg}: {status}") list_all_algorithms() ``` -------------------------------- ### Get Enabled KEM Mechanisms Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/types.md Retrieves a tuple of strings representing all enabled Key Encapsulation Mechanisms (KEMs). Use this to see available algorithms. ```python import oqs enabled_kems: tuple[str, ...] = oqs.get_enabled_kem_mechanisms() # Example value: ('ML-KEM-512', 'ML-KEM-768', 'ML-KEM-1024') for alg in enabled_kems: print(f" - {alg}") ``` -------------------------------- ### List Enabled Signature Mechanisms Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/INDEX.md Get a list of all digital signature mechanisms that are enabled in the current liboqs build. This helps in selecting available algorithms. ```python oqs.get_enabled_sig_mechanisms() ``` -------------------------------- ### Set PYOQS_VERSION in Python for Auto-Installation Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md Configure the PYOQS_VERSION environment variable in Python before importing oqs to ensure a specific version of liboqs is installed automatically if needed. ```python import os # Set before importing oqs os.environ["PYOQS_VERSION"] = "0.15.0" import oqs # First import triggers installation of version 0.15.0 ``` -------------------------------- ### Handle Unsupported Algorithm with MechanismNotSupportedError Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md Catch MechanismNotSupportedError when attempting to use an algorithm that is not supported by liboqs. This example shows how to access the algorithm name and the error message. ```python import oqs try: kem = oqs.KeyEncapsulation("NONEXISTENT-ALGORITHM") except oqs.MechanismNotSupportedError as e: print(f"Algorithm not supported: {e.alg_name}") print(f"Message: {e.message}") ``` -------------------------------- ### Get Enabled Signature Algorithms Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md Retrieves a tuple of all signature algorithm names that are enabled in the current liboqs build. Use this to determine which algorithms are available for instantiation. ```python import oqs enabled = oqs.get_enabled_sig_mechanisms() print(enabled) # ('ML-DSA-44', 'ML-DSA-65', 'ML-DSA-87', 'FALCON-512', ...) if "ML-DSA-44" in enabled: sig = oqs.Signature("ML-DSA-44") ``` -------------------------------- ### Build Docker Image for oqs-python Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md Build the Docker image for oqs-python. This command tags the image as 'oqs-python'. ```shell docker build -t oqs-python . ``` -------------------------------- ### Get liboqs-python Package Version Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md Retrieves the version string of the liboqs-python package. Returns None if the version cannot be determined. Issues a warning if version determination fails. ```python import oqs version = oqs.oqs_python_version() print(f"liboqs-python version: {version}") # liboqs-python version: 0.16.0-dev ``` -------------------------------- ### Deterministic Keypair Generation Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/key-encapsulation.md Demonstrates how to generate a KEM keypair deterministically using a provided seed. ```APIDOC ### Deterministic Keypair Generation ```python import oqs # Generate deterministically from seed seed = b"your-deterministic-seed-here-00" * 2 # Must be exactly 64 bytes with oqs.KeyEncapsulation("ML-KEM-512") as kem: public_key = kem.generate_keypair_seed(seed) secret_key = kem.export_secret_key() # Same seed produces same keypair kem2 = oqs.KeyEncapsulation("ML-KEM-512") public_key2 = kem2.generate_keypair_seed(seed) assert public_key == public_key2 ``` ``` -------------------------------- ### List Enabled KEM Mechanisms Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/INDEX.md Get a list of all Key Encapsulation Mechanisms (KEMs) that are enabled in the current liboqs build. This helps in selecting available algorithms. ```python oqs.get_enabled_kem_mechanisms() ``` -------------------------------- ### OQS_VERSION Constant Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md The OQS_VERSION constant provides the version string of the liboqs library. This is used for managing the installation of liboqs, either a specific version or the latest from the main branch. ```APIDOC ## OQS_VERSION ### Description Version string of the liboqs library to install/use. ### Type `str | None` ### Details - Set from `PYOQS_VERSION` environment variable if present - Otherwise uses version from `pyproject.toml` - None indicates "latest" (main branch) - Used for automatic liboqs installation on-demand ### Usage ```python import oqs print(f"Will install liboqs: {oqs.OQS_VERSION}") # Controlled by environment: # export PYOQS_VERSION=0.15.0 # Specific version # export PYOQS_VERSION=latest # Main branch ``` ``` -------------------------------- ### Configure PATH on Windows Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md On Windows, add the directory containing the liboqs DLL (e.g., oqs.dll or liboqs.dll) to the system's PATH environment variable. This allows the operating system to find the necessary dynamic libraries. ```cmd set PATH=%PATH%;C:\liboqs\bin ``` -------------------------------- ### Force Version Match and Clear Cache Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/configuration.md To resolve version mismatch warnings, set the PYOQS_VERSION environment variable to match the wrapper version and clear the cached installation. ```bash export PYOQS_VERSION=0.16.0 # Match wrapper version rm -rf $HOME/_oqs # Clear cache python -c "import oqs; print(oqs.oqs_version())" ``` -------------------------------- ### Check liboqs and Wrapper Version Compatibility Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/utility-functions.md Compares the major versions of the liboqs C library and the liboqs-python wrapper. Prints a warning if a major version mismatch is detected. ```python import oqs def check_compatibility(): """Check liboqs and wrapper versions.""" oqs_ver = oqs.oqs_version() wrapper_ver = oqs.oqs_python_version() print(f"liboqs version: {oqs_ver}") print(f"liboqs-python version: {wrapper_ver}") if wrapper_ver and oqs_ver.split('.')[0] != wrapper_ver.split('.')[0]: print("Warning: Major version mismatch") check_compatibility() ``` -------------------------------- ### Get Total Available Signatures Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/stateful-signature.md Retrieves the total number of signatures that can be generated with the current secret key. This count is determined by the algorithm's parameters, such as tree height. ```python with oqs.StatefulSignature("XMSS-SHA2_10_256") as signer: public_key = signer.generate_keypair() total = signer.sigs_total() print(f"Total signatures available: {total}") # 1024 ``` -------------------------------- ### State-Aware Signing with Signature Limits Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/stateful-signature.md Illustrates how to perform multiple signings with a `StatefulSignature` object while tracking the remaining signature count. The loop breaks if no more signatures can be generated. ```python import oqs with oqs.StatefulSignature("XMSS-SHA2_10_256") as signer: public_key = signer.generate_keypair() # Sign multiple messages with state tracking messages = [ b"Message 1", b"Message 2", b"Message 3", ] signatures = [] for msg in messages: if signer.sigs_remaining() > 0: signature = signer.sign(msg) signatures.append(signature) print(f"Signed message, {signer.sigs_remaining()} remaining") else: print("No signatures remaining!") break ``` -------------------------------- ### KeyEncapsulation Context Manager Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/_autodocs/api-reference/module-overview.md Demonstrates using the KeyEncapsulation class as a context manager. Resources are automatically freed upon exiting the 'with' block. ```python with oqs.KeyEncapsulation("ML-KEM-512") as kem: public_key = kem.generate_keypair() # ... # Resources automatically freed on exit ``` -------------------------------- ### Set PATH on Windows Source: https://github.com/open-quantum-safe/liboqs-python/blob/main/README.md On Windows, ensure the liboqs shared library is visible by adding its bin directory to the system's PATH environment variable. ```shell set PATH=%PATH%;C:\Program Files (x86)\liboqs\bin ```