{"id":8556,"library":"python-pkcs11","title":"PKCS#11 support for Python","description":"python-pkcs11 provides Python bindings for PKCS#11, a standard for cryptographic tokens. It allows interaction with hardware security modules (HSMs) and smart cards using a native Python API. The library is actively maintained with frequent minor releases, ensuring compatibility with the latest Python versions and addressing specific token behaviors. The current version is 0.9.4.","status":"active","version":"0.9.4","language":"en","source_language":"en","source_url":"https://github.com/pyauth/python-pkcs11","tags":["security","cryptography","hardware-security-module","hsm","pkcs11","smart-card"],"install":[{"cmd":"pip install python-pkcs11","lang":"bash","label":"Install with pip"}],"dependencies":[{"reason":"Used for calling C functions from Python, which is fundamental to PKCS#11 interaction.","package":"cffi","optional":false}],"imports":[{"symbol":"pkcs11","correct":"import pkcs11"},{"note":"The `lib` object is created by calling `pkcs11.lib()` with the path to the PKCS#11 shared library, not directly imported.","wrong":"from pkcs11 import lib","symbol":"lib","correct":"lib = pkcs11.lib(library_path)"}],"quickstart":{"code":"import pkcs11\nimport os\n\n# Set the path to your PKCS#11 shared library\n# For testing, you might use SoftHSM2: /usr/lib/softhsm/libsofthsm2.so (Linux)\n# or a vendor-specific driver.\nPKCS11_LIBRARY_PATH = os.environ.get('PKCS11_LIBRARY', '/usr/local/lib/softhsm/libsofthsm2.so')\n\ntry:\n    # Load the PKCS#11 library\n    lib = pkcs11.lib(PKCS11_LIBRARY_PATH)\n\n    # List available slots (where tokens/smart cards are inserted)\n    slots = lib.get_slots()\n    if not slots:\n        print(f\"No PKCS#11 slots found for library: {PKCS11_LIBRARY_PATH}\")\n        print(\"Please ensure your PKCS#11 library is correctly configured and tokens are present.\")\n    else:\n        print(f\"Found {len(slots)} PKCS#11 slots:\")\n        for i, slot in enumerate(slots):\n            try:\n                token_info = slot.get_token_info()\n                print(f\"  Slot {i}: '{token_info.label}' (serial: {token_info.serial_number})\")\n            except pkcs11.exceptions.PKCS11Error as e:\n                if e.rv == pkcs11.CKR_TOKEN_NOT_PRESENT:\n                    print(f\"  Slot {i}: No token present\")\n                else:\n                    print(f\"  Slot {i}: Error getting token info: {e}\")\n\nexcept pkcs11.exceptions.PKCS11Error as e:\n    print(f\"Failed to load PKCS#11 library at '{PKCS11_LIBRARY_PATH}': {e}\")\n    print(\"Please check the path and ensure the library is installed and accessible.\")\nexcept FileNotFoundError:\n    print(f\"PKCS#11 library not found at '{PKCS11_LIBRARY_PATH}'\")\n    print(\"Ensure the path is correct and the PKCS#11 shared library (e.g., .so, .dll) is installed.\")\n","lang":"python","description":"This quickstart demonstrates how to load a PKCS#11 shared library and list available slots. You must have a PKCS#11 library installed on your system (e.g., SoftHSM2 for testing, or a hardware vendor's driver). Set the `PKCS11_LIBRARY` environment variable to its path."},"warnings":[{"fix":"Install a suitable PKCS#11 implementation for your operating system (e.g., `sudo apt install softhsm2` on Ubuntu) and provide its path to `pkcs11.lib()`.","message":"This library requires a system-level PKCS#11 shared library (e.g., `libsofthsm2.so` on Linux, `pkcs11.dll` on Windows) to be installed and accessible. `python-pkcs11` itself is a wrapper, not a complete PKCS#11 implementation.","severity":"gotcha","affected_versions":"All versions"},{"fix":"If you relied on ECB for AES key wrapping, explicitly specify `pkcs11.Mechanism.AES_ECB_ENCRYPT_DATA` or update your code to use the new standard mechanisms like `AES_KEY_WRAP`.","message":"In v0.5.0, the default mechanism for wrapping AES keys changed from ECB to `AES_KEY_WRAP` to align with the updated PKCS#11 v2.4 specification. This may break existing applications that implicitly relied on ECB for AES key wrapping.","severity":"breaking","affected_versions":">=0.5.0"},{"fix":"Ensure your token's firmware is up-to-date. If issues persist, consider fetching attributes one by one using specific attribute types if the bundled mitigation doesn't resolve the problem for your specific hardware.","message":"Some PKCS#11 tokens or implementations may not handle multi-attribute fetches in a compliant way, leading to errors when trying to retrieve all object attributes at once. While v0.9.3 includes a mitigation, it can still cause unexpected behavior.","severity":"gotcha","affected_versions":"<0.9.3, potentially some tokens with >=0.9.3"},{"fix":"Review the documentation for managing multiple `pkcs11.lib()` instances and their sessions if your application requires interacting with more than one PKCS#11 shared library concurrently.","message":"Version 0.9.0 introduced internal restructuring to better support loading and unloading multiple PKCS#11 libraries. While not a direct API break for common use, advanced users managing multiple library instances might need to adapt their approach.","severity":"gotcha","affected_versions":">=0.9.0"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Verify the absolute path to your PKCS#11 shared library. Ensure it exists, is readable, and matches your Python interpreter's architecture (e.g., 64-bit Python with 64-bit library). For Linux, check `LD_LIBRARY_PATH` or `/etc/ld.so.conf`.","cause":"The specified PKCS#11 shared library (.so, .dll) could not be loaded. This often indicates an incorrect path, missing file, or architecture mismatch.","error":"pkcs11.exceptions.PKCS11Error: CKR_LIBRARY_LOAD_FAILED"},{"fix":"Run `pip install python-pkcs11` to install the library.","cause":"The `python-pkcs11` package has not been installed in your Python environment.","error":"ModuleNotFoundError: No module named 'pkcs11'"},{"fix":"Ensure your hardware token is properly inserted and initialized. For SoftHSM2, ensure you have created and initialized a token (e.g., `softhsm2-util --init-token --slot 0 --label 'my-token' --pin 1234 --so-pin 123456`).","cause":"The selected PKCS#11 slot does not have a cryptographic token (e.g., smart card, HSM) inserted or initialized, or the token is not responding.","error":"pkcs11.exceptions.PKCS11Error: CKR_TOKEN_NOT_PRESENT"},{"fix":"Always check if the result of `get_token()` or `get_slot()` is `None` before attempting to use it. For example: `token = lib.get_token(token_label='my-token'); if token: session = token.open()`.","cause":"Attempting to iterate or access attributes on a `None` object, typically returned when `lib.get_token()` or `lib.get_slot()` doesn't find a matching token/slot.","error":"TypeError: argument of type 'NoneType' is not iterable"}]}