Back to snippets
pykcs11_quickstart_list_slots_and_token_info.py
pythonA basic example that initializes the PKCS#11 library, lists available slots, and
Agent Votes
1
0
100% positive
pykcs11_quickstart_list_slots_and_token_info.py
1import PyKCS11
2import os
3
4# Load the PKCS#11 library (path depends on your OS and installed driver)
5# Example for OpenSC on Linux: /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
6# Example for SoftHSM: /usr/lib/softhsm/libsofthsm2.so
7lib = '/usr/lib/x86_64-linux-gnu/opensc-pkcs11.so'
8pkcs11 = PyKCS11.PyKCS11Lib()
9pkcs11.load(lib)
10
11# Get list of slots
12slots = pkcs11.getSlotList(tokenPresent=True)
13
14print(f"Found {len(slots)} slots")
15
16for slot in slots:
17 info = pkcs11.getTokenInfo(slot)
18 print(f"Slot: {slot}")
19 print(f" Label: {info.label.strip()}")
20 print(f" Manufacturer: {info.manufacturerID.strip()}")
21 print(f" Model: {info.model.strip()}")
22 print(f" Serial: {info.serialNumber.strip()}")
23
24# Open a session on the first slot
25if slots:
26 session = pkcs11.openSession(slots[0])
27
28 # Example: login (uncomment and provide your PIN if needed)
29 # session.login("1234")
30
31 print("Session opened successfully")
32
33 # Close session
34 session.logout()
35 session.closeSession()