Registry / auth-security / python-pkcs11

python-pkcs11

JSON →
library0.9.4pypypi✓ verified 87d ago

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.

pip install python-pkcs11
INSTALL
IMPORT
SIG · PYTHON-PKCS11
P
python-pkcs11
auth-securitypythonv0.9.4
Install
1.8s avg
Import
141ms
Disk
23MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.9.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.148s · 23.6MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 1.8s · import 0.134s · 26MB
23MB installed
● package 23MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pkcs11
import pkcs11
lib
lib = pkcs11.lib(library_path)
from pkcs11 import lib
The `lib` object is created by calling `pkcs11.lib()` with the path to the PKCS#11 shared library, not directly imported.

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.

import pkcs11 import os # Set the path to your PKCS#11 shared library # For testing, you might use SoftHSM2: /usr/lib/softhsm/libsofthsm2.so (Linux) # or a vendor-specific driver. PKCS11_LIBRARY_PATH = os.environ.get('PKCS11_LIBRARY', '/usr/local/lib/softhsm/libsofthsm2.so') try: # Load the PKCS#11 library lib = pkcs11.lib(PKCS11_LIBRARY_PATH) # List available slots (where tokens/smart cards are inserted) slots = lib.get_slots() if not slots: print(f"No PKCS#11 slots found for library: {PKCS11_LIBRARY_PATH}") print("Please ensure your PKCS#11 library is correctly configured and tokens are present.") else: print(f"Found {len(slots)} PKCS#11 slots:") for i, slot in enumerate(slots): try: token_info = slot.get_token_info() print(f" Slot {i}: '{token_info.label}' (serial: {token_info.serial_number})") except pkcs11.exceptions.PKCS11Error as e: if e.rv == pkcs11.CKR_TOKEN_NOT_PRESENT: print(f" Slot {i}: No token present") else: print(f" Slot {i}: Error getting token info: {e}") except pkcs11.exceptions.PKCS11Error as e: print(f"Failed to load PKCS#11 library at '{PKCS11_LIBRARY_PATH}': {e}") print("Please check the path and ensure the library is installed and accessible.") except FileNotFoundError: print(f"PKCS#11 library not found at '{PKCS11_LIBRARY_PATH}'") print("Ensure the path is correct and the PKCS#11 shared library (e.g., .so, .dll) is installed.")
Debug
Known issues
gotchaThis 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.
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()`.
affects: All versions
breakingIn 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.
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`.
affects: >=0.5.0
gotchaSome 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.
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.
affects: <0.9.3, potentially some tokens with >=0.9.3
gotchaVersion 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.
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.
affects: >=0.9.0
Errors
Common errors & fixes
pkcs11.exceptions.PKCS11Error: CKR_LIBRARY_LOAD_FAILED
The specified PKCS#11 shared library (.so, .dll) could not be loaded. This often indicates an incorrect path, missing file, or architecture mismatch.
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`.
ModuleNotFoundError: No module named 'pkcs11'
The `python-pkcs11` package has not been installed in your Python environment.
fix
Run `pip install python-pkcs11` to install the library.
pkcs11.exceptions.PKCS11Error: CKR_TOKEN_NOT_PRESENT
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.
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`).
TypeError: argument of type 'NoneType' is not iterable
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.
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()`.
Upgrade
Version history
0.9.4latest on PyPI · released Apr 13, 2026
Audit
Dependencies
cffirequiredUsed for calling C functions from Python, which is fundamental to PKCS#11 interaction.
Agent activity
28 hits · last 30 days
node
26
OpenAI (training)
1
Resources
python-pkcs11 — pip install python-pkcs11 · libregistry