Skip to main content

PKCS#11 C API

All functions are loaded at runtime via dlopen/dlsym in hsm_test.c. Each returns CK_RV; CKR_OK (value 0) indicates success.
Initializes the PKCS#11 library. Must be the first function called.
CK_RV C_Initialize(CK_VOID_PTR pInitArgs);
ParameterTypeDescription
pInitArgsCK_VOID_PTRPass NULL for default single-threaded initialization.
Returns: CKR_OK on success.
CK_RV rv = C_Initialize(NULL);
Releases all resources held by the PKCS#11 library. Must be called before unloading the module.
CK_RV C_Finalize(CK_VOID_PTR pReserved);
ParameterTypeDescription
pReservedCK_VOID_PTRReserved; must be NULL.
Returns: CKR_OK on success.
C_Finalize(NULL);
Returns a list of slot IDs, optionally filtered to slots that have a token present.
CK_RV C_GetSlotList(
    CK_BBOOL    tokenPresent,
    CK_SLOT_ID_PTR pSlotList,
    CK_ULONG_PTR pulCount
);
ParameterTypeDescription
tokenPresentCK_BBOOLCK_TRUE to return only slots with a token present.
pSlotListCK_SLOT_ID_PTRBuffer to receive slot IDs. Pass NULL to query the count only.
pulCountCK_ULONG_PTROn input: capacity of pSlotList. On output: number of slots.
Returns: CKR_OK on success.
CK_ULONG count = 0;
C_GetSlotList(CK_TRUE, NULL, &count);
CK_SLOT_ID slots[count];
C_GetSlotList(CK_TRUE, slots, &count);
Retrieves information about the token in a given slot, including its label, serial number, and flags.
CK_RV C_GetTokenInfo(
    CK_SLOT_ID        slotID,
    CK_TOKEN_INFO_PTR pInfo
);
ParameterTypeDescription
slotIDCK_SLOT_IDThe slot containing the token.
pInfoCK_TOKEN_INFO_PTRPointer to a CK_TOKEN_INFO structure to fill.
Returns: CKR_OK on success.
CK_TOKEN_INFO token_info;
C_GetTokenInfo(slot, &token_info);
// token_info.label contains the 32-byte space-padded token label
Opens a session with a token in the specified slot.
CK_RV C_OpenSession(
    CK_SLOT_ID        slotID,
    CK_FLAGS          flags,
    CK_VOID_PTR       pApplication,
    CK_NOTIFY         Notify,
    CK_SESSION_HANDLE_PTR phSession
);
ParameterTypeDescription
slotIDCK_SLOT_IDTarget slot.
flagsCK_FLAGSSession flags. Use CKF_SERIAL_SESSION | CKF_RW_SESSION for a read/write session. CKF_SERIAL_SESSION is always required.
pApplicationCK_VOID_PTRApplication-defined pointer passed to the notify callback. Pass NULL.
NotifyCK_NOTIFYNotification callback function pointer. Pass NULL.
phSessionCK_SESSION_HANDLE_PTRReceives the new session handle.
Returns: CKR_OK on success.
CK_SESSION_HANDLE session;
C_OpenSession(
    slots[0],
    CKF_SERIAL_SESSION | CKF_RW_SESSION,
    NULL, NULL,
    &session
);
Closes an open session and releases associated resources.
CK_RV C_CloseSession(CK_SESSION_HANDLE hSession);
ParameterTypeDescription
hSessionCK_SESSION_HANDLEHandle of the session to close.
Returns: CKR_OK on success.
C_CloseSession(session);
Authenticates the session with the given PIN. Required before accessing private objects.
CK_RV C_Login(
    CK_SESSION_HANDLE hSession,
    CK_USER_TYPE      userType,
    CK_UTF8CHAR_PTR   pPin,
    CK_ULONG          ulPinLen
);
ParameterTypeDescription
hSessionCK_SESSION_HANDLEActive session handle.
userTypeCK_USER_TYPECKU_USER for normal user; CKU_SO for security officer.
pPinCK_UTF8CHAR_PTRPIN string (not null-terminated).
ulPinLenCK_ULONGLength of the PIN in bytes.
Returns: CKR_OK on success.
CK_UTF8CHAR pin[] = "1234";
C_Login(session, CKU_USER, pin, sizeof(pin) - 1);
Logs out the current user, ending the authenticated state of the session.
CK_RV C_Logout(CK_SESSION_HANDLE hSession);
ParameterTypeDescription
hSessionCK_SESSION_HANDLEActive session handle.
Returns: CKR_OK on success.
C_Logout(session);
Returns up to ulMaxObjectCount handles for objects matching the template set in C_FindObjectsInit.
CK_RV C_FindObjects(
    CK_SESSION_HANDLE    hSession,
    CK_OBJECT_HANDLE_PTR phObject,
    CK_ULONG             ulMaxObjectCount,
    CK_ULONG_PTR         pulObjectCount
);
ParameterTypeDescription
hSessionCK_SESSION_HANDLEActive session handle.
phObjectCK_OBJECT_HANDLE_PTRBuffer to receive object handles.
ulMaxObjectCountCK_ULONGMaximum number of handles to return.
pulObjectCountCK_ULONG_PTRReceives the actual number of handles returned.
Returns: CKR_OK on success. Returns fewer handles than ulMaxObjectCount when no more objects match.
CK_OBJECT_HANDLE handles[64];
CK_ULONG found = 0;
C_FindObjects(session, handles, 64, &found);
// found == number of matching objects
Retrieves the values of one or more attributes of a given object. Commonly used to read CKA_LABEL, CKA_ID, and CKA_CLASS.
CK_RV C_GetAttributeValue(
    CK_SESSION_HANDLE hSession,
    CK_OBJECT_HANDLE  hObject,
    CK_ATTRIBUTE_PTR  pTemplate,
    CK_ULONG          ulCount
);
ParameterTypeDescription
hSessionCK_SESSION_HANDLEActive session handle.
hObjectCK_OBJECT_HANDLEHandle of the object to query.
pTemplateCK_ATTRIBUTE_PTRArray of CK_ATTRIBUTE structures. Set pValue = NULL and ulValueLen = 0 on first call to query buffer sizes.
ulCountCK_ULONGNumber of attributes in pTemplate.
Returns: CKR_OK on success.
char label[33] = {0};
CK_ATTRIBUTE attr = { CKA_LABEL, label, sizeof(label) - 1 };
C_GetAttributeValue(session, handles[0], &attr, 1);
// label now contains the object's CKA_LABEL value

pkcs11-tool CLI reference

pkcs11-tool is part of the opensc package and is used throughout this project to manage tokens and keys via the SoftHSM2 PKCS#11 module.

Flags

--module
string
required
Path to the PKCS#11 shared library. For SoftHSM2 on x86-64 Debian/Ubuntu: /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so
--slot
number
Numeric slot ID. Obtain available slot IDs with softhsm2-util --show-slots.
--login
Prompt for (or accept via --pin) the user PIN before performing the operation.
--pin
string
User PIN supplied non-interactively, e.g. --pin 1234.
--keypairgen
Generate an asymmetric key pair (public + private). Requires --key-type, --id, and --label.
--key-type
string
Key algorithm and size, e.g. rsa:2048 or EC:prime256v1.
--id
hex
Hex object ID assigned to the key, e.g. 10. Used to reference the key in sign and read operations.
--label
string
Human-readable label for the key object, e.g. FirmwareKey.
--list-objects
List all objects visible in the current session (after login).
--verbose
Print extended attribute information when listing objects.
--sign
Sign data from --input-file and write the signature to --output-file. Requires --mechanism and --id.
--mechanism
string
Signing mechanism, e.g. RSA-PKCS or ECDSA.
--input-file
string
Path to the file containing data to sign, e.g. a pre-computed SHA-256 digest (data.sha256).
--output-file
string
Path where the signature bytes will be written, e.g. signature.bin.
--read-object
Read a single object from the token. Requires --type and --id.
--type
string
Object type for --read-object. Use pubkey to export the DER-encoded public key.
--delete-object
Delete an object from the token. Requires --type and --id.

Usage examples

# Initialize a new token
softhsm2-util --init-token --free --label FirmwareHSM
softhsm2-util --show-slots

# Generate an RSA-2048 key pair
pkcs11-tool --module /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so \
  --slot <SLOT_ID> --login --pin 1234 \
  --keypairgen --key-type rsa:2048 --id 10 --label FirmwareKey

# Generate an EC key pair (prime256v1)
pkcs11-tool --module /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so \
  --slot <SLOT_ID> --login --pin 1234 \
  --keypairgen --key-type EC:prime256v1 --id 10 --label FirmwareKey

# List all objects
pkcs11-tool --module /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so \
  --slot <SLOT_ID> --login --pin 1234 --list-objects --verbose

# Sign with RSA-PKCS
pkcs11-tool --module /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so \
  --slot <SLOT_ID> --login --pin 1234 \
  --sign --mechanism RSA-PKCS \
  --input-file data.sha256 --output-file signature.bin --id 10

# Sign with ECDSA
pkcs11-tool --module /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so \
  --slot <SLOT_ID> --login --pin 1234 \
  --sign --mechanism ECDSA \
  --input-file data.sha256 --output-file signature.bin --id 10

# Export public key (DER)
pkcs11-tool --module /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so \
  --slot <SLOT_ID> --login --pin 1234 \
  --read-object --type pubkey --id 10 --output-file pubkey.der

# Delete token
softhsm2-util --delete-token --slot <SLOT_ID>

Build docs developers (and LLMs) love