Chilkat.Pkcs11 Class Overview

Chilkat.Pkcs11 provides access to PKCS#11-compatible smart cards, USB tokens, and HSMs through a vendor-supplied shared library. It supports discovering tokens, opening sessions, logging in with PINs, finding certificates and keys, generating keys on the token, importing keys, exporting public keys, creating or destroying PKCS#11 objects, and linking certificates for signing operations in other Chilkat classes.

What the Class Is Used For

Use Chilkat.Pkcs11 when an application needs to interact directly with a smart card, USB token, or HSM through a PKCS#11 driver. The private keys remain on the device, while Chilkat can discover objects, find certificates, sign through linked certificates, generate key pairs, and manage token sessions.

Discover Tokens Enumerate readers, slots, tokens, token information, and supported mechanisms through the configured PKCS#11 shared library.
Open and Authenticate Sessions Initialize the library, open a token session, login with a user PIN, logout, and close the session cleanly.
Find Certificates and Keys Locate certificates and public, private, secret, or OTP keys stored on the token.
Generate and Import Keys Generate RSA, EC, and symmetric keys on the HSM, or import private and SSH keys onto the device.
Important: Private keys are not visible until the PKCS#11 session is authenticated. Call Login after OpenSession, or use QuickSession with a PIN.

Typical Workflow

  1. Set SharedLibPath to the vendor’s PKCS#11 DLL, .so, or .dylib.
  2. Call Initialize to dynamically load and initialize the PKCS#11 library.
  3. Optionally call Discover to inspect available slots, readers, smart cards, USB tokens, and supported mechanisms.
  4. Call OpenSession with a slot ID, or pass -1 to use the first available non-empty slot.
  5. Call Login as the Normal User when private keys or authenticated operations are required.
  6. Find certificates or keys using FindCert, FindAllCerts, GetCert, FindAllKeys, or FindObject.
  7. Use the certificate, key handle, or generated key in the required operation. A certificate returned by FindCert is internally linked to this PKCS#11 session for signing by other Chilkat classes.
  8. Call Logout when finished with authenticated operations, then CloseSession to release the token session.
Always close sessions: The reference notes that memory leaks can occur if a PKCS#11 session is not properly closed. Call CloseSession when finished.

QuickSession Workflow

QuickSession combines common setup steps into one method. It initializes the library, opens a session on the first non-empty slot, and optionally logs in.

Scenario Call Result
Open a session without login QuickSession(userType, "") Opens a session on the first non-empty slot. The userType argument is ignored when the PIN is empty.
Open and login as Normal User QuickSession(1, pin) Initializes the library, opens the first non-empty slot, and logs in as the Normal User.
Replace manual setup QuickSession(...) Takes the place of separate calls to Initialize, OpenSession, and Login.

Core Concepts

Concept Meaning Important Members
PKCS#11 Shared Library The vendor-supplied DLL, .so, or .dylib that exposes the token’s PKCS#11 API. SharedLibPath, Initialize
Slot A connected smart card reader or USB hardware token. Methods that open or initialize a token use a slot ID, not a zero-based index. Discover, OpenSession, InitToken
Token The smart card inserted into a reader, or a USB hardware token that behaves as both reader and smart card in one device. OpenSession, Login, Logout
Session An active connection to a token. Sessions can be read-only or read-write and may be authenticated with a PIN. OpenSession, QuickSession, CloseSession
Login Type PKCS#11 supports Security Officer, Normal User, and Context Specific login types. Most applications login as Normal User. Login, QuickSession
Object Handle A numeric handle used to reference a PKCS#11 object during the current session. Handles are valid only for the session in which they were obtained. FindObject, GenRsaKey, GenEcKey, DestroyObject
Linked Certificate A certificate found through PKCS#11 can be internally linked to the session so other Chilkat classes can use it for signing on the device. FindCert, Cert

Core Properties

Property Purpose Guidance
SharedLibPath Specifies the PKCS#11 shared library to load. On Windows, use a DLL name or full path. On Linux/macOS, use a full path or library name resolved through dlopen search rules.
NumCerts Number of certificates found on the token. Set after calling FindAllCerts. Retrieve each certificate with GetCert.
SigContextPin Context-specific signature PIN for tokens that require login during the signing operation. Most smart cards do not need this. Set it only when you know the token requires a signature-context login.
LastErrorText Detailed information about the last method call or property access. Check after failures or unexpected behavior.
UncommonOptions Enables uncommon behavior for selected methods. Supports options such as Pkcs11DiscoverSkipTokenInfo and Pkcs11DiscoverSkipMechanisms.

Session Management

Task Method Notes
Initialize PKCS#11 library Initialize Call after setting SharedLibPath. Dynamically loads the shared library and initializes the PKCS#11 library.
Open a session OpenSession Opens a token session. Pass a slot ID, or -1 to choose the first available non-empty slot.
Open and optionally login quickly QuickSession Replaces separate calls to Initialize, OpenSession, and Login.
Login with PIN Login User type is 0 for Security Officer, 1 for Normal User, and 2 for Context Specific. Most applications use Normal User.
Logout Logout Logs out from the token.
Close session CloseSession Closes the token session. This should be called to avoid session/resource leaks.

Discovery

Discover reports readers, smart cards, USB tokens, slot information, token information, and supported mechanisms through the configured PKCS#11 shared library.

Need Member Details
Discover available PKCS#11 slots and tokens Discover Writes discovery information to a JsonObject. The onlyTokensPresent argument controls whether only slots with tokens present are returned.
Skip token information during discovery Pkcs11DiscoverSkipTokenInfo Set in UncommonOptions. Discovery returns slot information only and avoids potentially time-consuming token-info calls.
Skip mechanism information during discovery Pkcs11DiscoverSkipMechanisms Set in UncommonOptions. Discovery returns slot and token info but skips potentially time-consuming mechanism information.

Finding Certificates and Keys

Task Method Important Notes
Find all certificates FindAllCerts Populates the internal certificate list and sets NumCerts. Retrieve certificates with GetCert.
Retrieve certificate by index GetCert Call after FindAllCerts. Indexing begins at 0.
Find a matching certificate FindCert Searches by privateKey, subjectDN, subjectDN_withTags, subjectCN, serial, or serial:issuerCN.
Find the first certificate with a private key FindCert("privateKey", "", cert) Requires an authenticated session. The returned certificate is linked to the PKCS#11 session for signing on the token.
Find all keys FindAllKeys Finds keys of class public, private, secret, or otp and returns information in JSON.
Find a generic PKCS#11 object FindObject Uses a JSON template and returns the handle of the first matching object, or 0 if not found.
Authentication requirement: Private keys will not be seen unless the session is authenticated. Call Login after OpenSession, or use QuickSession with a PIN.

Generating Keys on the HSM

Key Type Method Result
RSA key pair GenRsaKey Generates an RSA key pair suitable for signing and verification. The private key is created on the HSM, the public key is returned as a PublicKey, and key handles are returned in JSON.
EC key pair GenEcKey Generates an EC key pair suitable for signing and verification. The private key remains on the HSM, and the public key is returned.
Symmetric secret key GenSecretKey Generates a symmetric key and returns its handle, or 0 on failure.
Supported Secret Key Type Use
AES Generate an AES secret key.
AES XTS Generate a key suitable for AES-XTS usage.
Blowfish Generate a Blowfish secret key.
Twofish Generate a Twofish secret key.
ChaCha20 Generate a ChaCha20 secret key.
Handle lifetime: PKCS#11 object handles are valid during the current session. To use the same key in a later session, find the object again to obtain a new handle.

Importing, Exporting, Creating, and Destroying Objects

Task Method Purpose
Import a private key ImportPrivateKey Imports a PrivateKey onto the HSM and returns the resulting object handle, or 0 on failure.
Import an SSH private key ImportSshKey Imports an SshKey private key onto the HSM and returns the object handle.
Export a public key ExportPublicKey Exports a public key from a public or private key handle into a PublicKey object.
Create a generic PKCS#11 object CreatePkcs11Object Creates an object using attributes supplied in a JsonObject and returns its handle.
Destroy an object DestroyObject Deletes the object identified by the handle from the HSM.
Destructive operation: DestroyObject deletes an object from the HSM. Use it only when the application is certain the object should be removed.

Token and PIN Administration

Administrative Task Method Important Notes
Initialize a token InitToken Initializes or reinitializes a token for a slot ID. Reinitialization destroys objects that can be destroyed and disables normal-user access until the Security Officer sets the normal user PIN.
Initialize the normal user PIN InitPin Must be called from a Security Officer logged-in session. Can be used after logging in with the PUK to unblock a smart card and set a new user PIN.
Change PIN SetPin Modifies the PIN of the currently logged-in user, or the Normal User PIN if the session is not logged in.
Login as Security Officer Login(0, pin) Used for administrative operations such as initializing the normal user PIN.
Login as Normal User Login(1, pin) The usual login type for applications that need access to private keys or protected token objects.
Context-specific login Login(2, pin), SigContextPin Used only for special token behavior requiring context-specific login, commonly during a signing operation.
InitToken warning: Token initialization can destroy token objects. Treat InitToken as an administrative operation, not a normal application startup step.

Finding Certificates for Signing

A common use of Pkcs11 is to locate a certificate whose private key remains on the token, then use that certificate in another Chilkat class for signing. When FindCert succeeds, the returned Cert is internally linked with the PKCS#11 session.

FindCert certPart partValue Meaning
privateKey "" Finds the first certificate having a private key. Requires authenticated session visibility.
subjectDN Subject distinguished name Finds a certificate by subject DN.
subjectDN_withTags Tagged subject DN Finds a certificate by subject DN with tags.
subjectCN Subject common name Finds a certificate by subject CN.
serial Certificate serial number Finds a certificate by serial number.
serial:issuerCN Serial and issuer CN Finds a certificate by serial number and issuer common name.
Signing integration: A certificate returned by FindCert can be used for signing on the smart card in Chilkat classes such as XmlDSigGen, Pdf, Crypt2, Mime, and MailMan.

Diagnostics and Troubleshooting

Problem Area Member What to Check
General method failure LastErrorText Provides detailed information about the last method call or property access.
PKCS#11 library fails to load SharedLibPath, Initialize, LastErrorText Verify the vendor library path, architecture, dependencies, and whether the library can be loaded by the operating system.
No slots or tokens found Discover Confirm the correct PKCS#11 driver is being used and that the token is connected or inserted.
Private keys not visible OpenSession, Login, FindAllKeys, FindCert Private keys are not visible until the session is authenticated.
Discovery is slow UncommonOptions Use Pkcs11DiscoverSkipTokenInfo or Pkcs11DiscoverSkipMechanisms to skip slower discovery details.
Signing requires extra PIN during operation SigContextPin Set only for tokens that require a context-specific signature PIN.
Session/resource leak concerns CloseSession Ensure each opened session is closed when no longer needed.

Best Practices

Recommendation Reason
Set SharedLibPath before calling Initialize. Chilkat needs the vendor PKCS#11 library before it can discover or access the token.
Use Discover first when working with a new token or driver. Discovery confirms which slots, tokens, and mechanisms are visible through the selected shared library.
Use QuickSession for simple one-token workflows. It replaces the common initialize/open/login sequence.
Use OpenSession(-1, ...) only when the first non-empty slot is acceptable. If multiple tokens are connected, choose a specific slot ID returned by discovery.
Login as Normal User for most application operations. Normal User login is typically required to see private keys and use protected token objects.
Close every opened session with CloseSession. Proper session cleanup prevents token/session resource leaks.
Remember that object handles are session-specific. Store persistent object attributes, not handles, if you need to find the same key again in a future session.
Avoid InitToken except for deliberate administrative setup. Initializing or reinitializing a token can destroy objects and reset token access state.
Check LastErrorText after failures. It provides the most useful diagnostic information for library loading, discovery, login, object search, key generation, import, and session issues.

Summary

Chilkat.Pkcs11 is the direct interface for working with PKCS#11 smart cards, USB tokens, and HSMs. It manages the vendor shared library, token discovery, sessions, PIN login, certificate and key discovery, key generation, key import, object creation and deletion, public-key export, and token administration.

The most common production pattern is: load the PKCS#11 library, open and login to a session, find the certificate with a private key, use the linked Cert in another Chilkat signing class, then logout and close the session.