hsm_test.c. The test dynamically loads the SoftHSM2 shared library and drives the standard PKCS#11 C API to enumerate slots, authenticate, and list key objects on the token.
Token setup
Initialise the token
MyToken and sets the user PIN to 5678. These values match the constants in hsm_test.c:hsm_test.c
Configuration
SoftHSM2 reads its token storage location from/etc/softhsm/softhsm2.conf (system-wide) or ~/.config/softhsm2/softhsm2.conf (per-user).
/etc/softhsm/softhsm2.conf
If the token directory does not exist, create it before initialising:
mkdir -p /var/lib/softhsm/tokens.PKCS#11 library path
The shared library path differs by distribution. Common locations:| Distribution | Path |
|---|---|
| Ubuntu/Debian (x86-64) | /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so |
| Generic / compatibility symlink | /usr/lib/softhsm/libsofthsm2.so |
| macOS (Homebrew) | /usr/local/lib/softhsm/libsofthsm2.so |
hsm_test.c uses the generic path:
hsm_test.c
Dynamic loading in hsm_test.c
The test avoids link-time binding by loading the library at runtime with dlopen / dlsym, then resolving each PKCS#11 function pointer by name.
hsm_test.c
PKCS11_LIB define.
PKCS#11 functions used
The following PKCS#11 functions are called byhsm_test.c:
C_Initialize / C_Finalize
C_Initialize / C_Finalize
C_Initialize(NULL_PTR) initialises the Cryptoki library. It must be the first call made after loading the library. C_Finalize(NULL_PTR) releases all resources and must be the last call.C_GetSlotList
C_GetSlotList
Returns the list of available slot IDs. The source uses a fixed-size array of 32 slots.
C_GetTokenInfo
C_GetTokenInfo
Retrieves metadata for the token in a given slot, including its label. The test matches the label against
TOKEN_LABEL ("MyToken") to identify the target slot.C_OpenSession / C_CloseSession
C_OpenSession / C_CloseSession
Opens a read-only or read-write session on a slot.
C_Login / C_Logout
C_Login / C_Logout
Authenticates as the normal user (
CKU_USER) with the PIN. Required before accessing private key objects.C_FindObjectsInit / C_FindObjects / C_FindObjectsFinal
C_FindObjectsInit / C_FindObjects / C_FindObjectsFinal
Three-step pattern for searching objects on the token. For each handle returned, the test reads the
C_FindObjectsInit sets the search template (empty template matches all objects). C_FindObjects fills an array of object handles in batches. C_FindObjectsFinal cleans up the search context.CKA_LABEL and CKA_ID attributes to display the object.Token management with pkcs11-tool
pkcs11-tool (from the opensc package) provides a convenient CLI for interacting with PKCS#11 tokens without writing C code.