PKCS#11 support for Python

0.9.4 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.")

view raw JSON →