Class Pkcs11
- All Implemented Interfaces:
AutoCloseable
Work directly with PKCS#11 smart cards, USB tokens, and HSMs.
Chilkat.Pkcs11 is the direct Chilkat interface for working with
PKCS#11 devices such as smart cards, USB tokens, and hardware security
modules. It manages the vendor PKCS#11 shared library, slot and token
discovery, session opening, PIN login, certificate and key discovery, object
attributes, key generation, key import, object creation and deletion,
public-key export, and token administration.
Load vendor libraries
Initialize access to the PKCS#11 module supplied by the smart-card, token, or HSM vendor.
Discover slots and tokens
Enumerate available slots, detect inserted tokens, and inspect token or slot information before opening a session.
Open sessions and login
Open PKCS#11 sessions, login with a user PIN, perform private-key operations, then logout and close the session.
Find certs and keys
Search for certificates, public keys, private keys, and other token objects using labels, IDs, classes, attributes, or key relationships.
Create and manage objects
Generate keys, import keys, create token objects, inspect attributes, and delete objects when supported by the token policy.
Use with signing classes
Link a token-backed certificate or private key to other Chilkat classes so signing can occur without the private key leaving the device.
Common pattern:
Load the vendor PKCS#11 library, select the slot or token, open a session,
login with the PIN, find the certificate that has the needed private key,
link that certificate for use by another Chilkat signing class, then logout
and close the session. Use Pkcs11 when the application needs
direct token control; use Chilkat.Cert once a token-backed
certificate has been selected for signing or authentication.
For an extended overview, see Pkcs11 Class Overview.
</section>
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidCloses the session on the token (i.e.longcreatePkcs11Object(JsonObject attrs)Creates an object and returns the handle.voiddestroyObject(long hObject)Destroys an object (deletes it from the HSM).voiddiscover(boolean onlyTokensPresent, JsonObject json)Discovers the readers, smart cards, and USB tokens accessible via PKCS11 on the computer (using the DLL/shared lib specified by SharedLibPath).voidexportPublicKey(long keyHandle, PublicKey pubKey)Export a public key given a public or private key handle.voidFinds all certificates contained on the smart card (or USB token).voidfindAllKeys(String keyClass, JsonObject json)Finds all keys contained on the smart card (or USB token).voidFinds the certificate where the givencertPartequals thepartValue.longfindObject(JsonObject jsonTemplate)General function for finding an object such as a private key.voidgenEcKey(JsonObject publicAttrs, JsonObject privateAttrs, JsonObject jsonOut, PublicKey pubKey)Generate an EC key pair suitable for signing data and verifying signatures.voidgenRsaKey(JsonObject publicAttrs, JsonObject privateAttrs, JsonObject jsonOut, PublicKey pubKey)Generate an RSA key pair suitable for signing data and verifying signatures.longgenSecretKey(String keyType, JsonObject jsonTemplate)Generates a symmetric encryption key.voidLoadscertwith the Nth certificate indicated byindex.intThe number of certificates contained on the smart card or USB token.On Windows systems, then should be set to the name of the DLL file (if the DLL is located in C:\Windows\System32), or it can be the full path to the DLL.If the smart card or token requires a signature context login within the signing operation, then set this property to the context-specific signature PIN.This is a catch-all property to be used for uncommon needs.longimportPrivateKey(PrivateKey privKey, JsonObject jsonTemplate)Imports a private key onto the HSM.longimportSshKey(SshKey sshKey, JsonObject jsonTemplate)Imports an SSH private key onto the HSM.voidInitializes the PKCS#11 library.voidInitializes the normal user's PIN.voidInitializes a token.voidAuthenticates a session with a PIN.voidlogout()Logs out from a token (smart card).voidopenSession(int slotId, boolean readWrite)Opens a session on the token (i.e.voidquickSession(int userType, String pin)Quickly establishes a session on the 1st unempty slot, with or without login.voidModifies the PIN of the user that is currently logged in, or the Normal User PIN if the session is not logged in.voidsetSharedLibPath(String value)Sets theSharedLibPathproperty; seegetSharedLibPath().voidsetSigContextPin(String value)Sets theSigContextPinproperty; seegetSigContextPin().voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Pkcs11
public Pkcs11()Creates a newPkcs11object.
-
-
Method Details
-
getNumCerts
public int getNumCerts()The number of certificates contained on the smart card or USB token. This property is set when FindAllCerts is called.- Returns:
- the value of the
NumCertsproperty (read-only)
-
getSigContextPin
If the smart card or token requires a signature context login within the signing operation, then set this property to the context-specific signature PIN. Most smart cards do not need this. Don't set this property unless you know for sure your smart card needs it.- Returns:
- the value of the
SigContextPinproperty
-
setSigContextPin
Sets theSigContextPinproperty; seegetSigContextPin().- Parameters:
value- the new value (notnull)
-
getUncommonOptions
This is a catch-all property to be used for uncommon needs. This property defaults to the empty string. It can be set to a list of one or more of the following comma separated keywords:- Pkcs11DiscoverSkipTokenInfo - Introduced in v9.5.0.99. Applies to the Discover method. If this keyword is present, then Discover will only return the slot information and will not make potentially time-consuming calls to get TokenInfo or information about supported mechanisms.
- Pkcs11DiscoverSkipMechanisms - Introduced in v9.5.0.99. Applies to the Discover method.
If this keyword is present, then Discover will get slot and token info, but will not make
potentially time-consuming calls to get information about supported mechanisms.
- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
closeSession
public void closeSession()Closes the session on the token (i.e. smart card).Note: Memory leaks can occur if the session is not properly closed.
- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
createPkcs11Object
Creates an object and returns the handle. Theattrsspecifies the attributes that define the object to be created. See the linked examples below for more information.- Parameters:
attrs- theattrsargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
destroyObject
public void destroyObject(long hObject)Destroys an object (deletes it from the HSM).hObjectis the object's handle.- Parameters:
hObject- thehObjectargument (0 .. 4294967295)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
discover
Discovers the readers, smart cards, and USB tokens accessible via PKCS11 on the computer (using the DLL/shared lib specified by SharedLibPath). TheonlyTokensPresentspecifies if only slots (readers) with tokens (smart cards) present should be returned. The information is written to thejson. (For details, see the example below.)- Parameters:
onlyTokensPresent- theonlyTokensPresentargumentjson- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
exportPublicKey
Export a public key given a public or private key handle. ThepubKeyis loaded with the exported public key.See the example linked below for more details.
- Parameters:
keyHandle- thekeyHandleargument (0 .. 4294967295)pubKey- thepubKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
findAllCerts
public void findAllCerts()Finds all certificates contained on the smart card (or USB token). This sets the NumCerts property. Each certificate can be obtained by calling GetCert(index) where the 1st cert is at index 0.Important: Private keys will not be seen unless the PKCS11 session is authenticated. To authenticate, your application must call Login after calling OpenSession.
- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
findAllKeys
Finds all keys contained on the smart card (or USB token). ThekeyClassindicates the kind of keys to return, and can be one of the following:- public
- private
- secret
- otp
Information about the keys is returned in
json.Important: Private keys will not be seen unless the PKCS11 session is authenticated. To authenticate, your application must call Login after calling OpenSession.
- Parameters:
keyClass- thekeyClassargument (notnull)json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
findCert
Finds the certificate where the givencertPartequals thepartValue. Possible values forcertPartare:privateKey,subjectDN,subjectDN_withTags,subjectCN,serial, orserial:issuerCN. IfcertPartequalsprivateKey, then pass an empty string inpartValue. SpecifyingprivateKeymeans to return the first certificate having a private key.The
certis loaded with the certificate if successful.Important: Private keys will not be seen unless the PKCS11 session is authenticated. To authenticate, your application must call Login after calling OpenSession.
Note: If successful, the
certwill be linked internally with this PKCS11 session such that certificate can be used for signing on the smart card when used in other Chilkat classes such as XmlDSigGen, Pdf, Crypt2, Mime, MailMan, etc.- Parameters:
certPart- thecertPartargument (notnull)partValue- thepartValueargument (notnull)cert- thecertargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
findObject
General function for finding an object such as a private key. Returns the handle of the first matching object, or 0 if not found.- Parameters:
jsonTemplate- thejsonTemplateargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
genEcKey
public void genEcKey(JsonObject publicAttrs, JsonObject privateAttrs, JsonObject jsonOut, PublicKey pubKey)Generate an EC key pair suitable for signing data and verifying signatures. The private key is created on the HSM (smart card or token), and the public key is returned inpubKey. ThepublicAttrsandprivateAttrscontain attributes for the public and private keys respectively. The PKCS11 public and private key handles are returned injsonOut. Handles are used to reference a PKCS11 object, such as a public or private key, and are valid during the PKCS11 session. To use the key in future PKCS11 sessions, your application would need to find the object to get a new handle.See the example linked below for more details.
- Parameters:
publicAttrs- thepublicAttrsargument (notnull)privateAttrs- theprivateAttrsargument (notnull)jsonOut- thejsonOutargument (notnull)pubKey- thepubKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
genRsaKey
public void genRsaKey(JsonObject publicAttrs, JsonObject privateAttrs, JsonObject jsonOut, PublicKey pubKey)Generate an RSA key pair suitable for signing data and verifying signatures. The private key is created on the HSM (smart card or token), and the public key is returned inpubKey. ThepublicAttrsandprivateAttrscontain attributes for the public and private keys respectively. The PKCS11 public and private key handles are returned injsonOut. Handles are used to reference a PKCS11 object, such as a public or private key, and are valid during the PKCS11 session. To use the key in future PKCS11 sessions, your application would need to find the object to get a new handle.See the example linked below for more details.
- Parameters:
publicAttrs- thepublicAttrsargument (notnull)privateAttrs- theprivateAttrsargument (notnull)jsonOut- thejsonOutargument (notnull)pubKey- thepubKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
genSecretKey
Generates a symmetric encryption key. ThekeyTypeis the key type, which can be one of the following values:- AES
- AES XTS
- Blowfish
- Twofish
- ChaCha20
The
jsonTemplateis a template that specifies attributes about the key to be generated. See the example at the link below.The handle to the generated key is returned. A value of 0 is returned on failure.
- Parameters:
keyType- thekeyTypeargument (notnull)jsonTemplate- thejsonTemplateargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
getCert
Loadscertwith the Nth certificate indicated byindex. The 1st certificate is at index 0. The FindAllCerts method must be called beforehand to load the certs from the smart card into this object. After calling FindAllCerts, the NumCerts property is set and each certificate can be retrieved by calling GetCert.- Parameters:
index- theindexargumentcert- thecertargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
importPrivateKey
Imports a private key onto the HSM. Returns the handle of the unwrapped key, or 0 if failed. See the linked example below for more details.- Parameters:
privKey- theprivKeyargument (notnull)jsonTemplate- thejsonTemplateargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
importSshKey
Imports an SSH private key onto the HSM. Returns the handle of the unwrapped key, or 0 if failed.- Parameters:
sshKey- thesshKeyargument (notnull)jsonTemplate- thejsonTemplateargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
initPin
Initializes the normal user's PIN. This must be called from the security officer's (SO) logged-in session.Note: To unblock a smart card, login to the SO (Security Officer) session using the PUK, and then call this with the new user PIN.
- Parameters:
pin- thepinargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
initToken
Initializes a token.slotIdis the slot ID of the token's slot.If the token has not been initialized (i.e. new from the factory), then the pPin parameter becomes the initial value of the SO (Security Officer) PIN. If the token is being reinitialized, the
pinparameter is checked against the existing SO PIN to authorize the initialization operation.When a token is initialized, all objects that can be destroyed are destroyed (i.e., all except for “indestructible” objects such as keys built into the token). Also, access by the normal user is disabled until the SO sets the normal user’s PIN. Depending on the token, some “default” objects may be created, and attributes of some objects may be set to default values.
- Parameters:
slotId- theslotIdargumentpin- thepinargument (notnull)tokenLabel- thetokenLabelargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
initialize
public void initialize()Initializes the PKCS#11 library. Should be called after specifying the SharedLibPath. The DLL (or .so/.dylib) is dynamically loaded and the PKCS#11 lib is initialized.- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
login
Authenticates a session with a PIN. TheuserTypecan be one of the following integer values:-
0>
- Security Officer (0)
- Normal User (1)
- Context Specific (2)
Except for special circumstances, you'll always login as the Normal User.
- Parameters:
userType- theuserTypeargumentpin- thepinargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
logout
public void logout()Logs out from a token (smart card).- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
openSession
public void openSession(int slotId, boolean readWrite)Opens a session on the token (i.e. smart card). TheslotIdis the ID of the slot (not the index). SetslotIdequal to -1 to choose the first available non-empty slot. ThereadWriteindicates whether the session should be read-only or read-write.The PKCS11 terminology is confusing:
- A
slotcorresponds to a connected smart card reader or USB hardware token, such as a Feitian ePass3003Auto token. - A
tokencorresponds to the smart card inserted into the reader. If we have a USB hardware token, such as the epass3003Auto (or many others), then technically there is always asmart cardinserted, because the USB hardware token is effectively both the reader and smart card wrapped in one inseparable device. - The PKCS11 DLL (or .so shared lib, or .dylib) is the vendor supplied PKCS11 implementation
(driver) that provides the low-level
CPKCS11 functions (called by Chilkat internally). - Generally, the number of slots will equal the number of connected smart cards or tokens belonging to the vendor of the DLL, or compatible with the DLL. In most cases you'll have your single reader with a single smart card inserted, and therefore only one slot exists.
- Some PKCS11 DLLs are provided by a 3rd party and support many smart cards.
For example, A.E.T. Europe B.V.'s
SafeSign Identity Client Standard Version 3.5DLL isaetpkss1.dll. It supports the following tokens:- Defensiepas
- Defensiepas 2
- G&D Convego Join 4.01 40k/80k
- G&D SkySIM Hercules
- G&D SkySIM Scorpius
- G&D Sm@rtCafé Expert 3.2
- G&D Sm@rtCafé Expert 4.0
- G&D Sm@rtCafé Expert 5.0
- G&D Sm@rtCafé Expert 6.0
- G&D Sm@rtCafé Expert 7.0
- G&D Sm@rtCafé Expert 64
- Gemalto Desineo ICP D72 FXR1 Java
- Gemalto IDCore 30
- Gemalto MultiApp ID v2.1
- Gemalto Optelio D72 FR1
- Gemalto TOP DL v2
- Infineon Oracle JCOS Ed.1
- JCOP21 v2.3
- Morpho IDealCitiz v2.1
- Morpho JMV ProCL V3.0
- NXP J2A080 / J2A081 (JCOP 2.4.1 R3)
- NXP JD081 (JCOP 2.4.1 R3)
- NXP J3A080 (JCOP 2.4.1 R3)
- NXP JCOP 2.4.2 R3
- NXP JCOP 3 SecID P60
- Oberthur IDOne Cosmo v7.0
- RDW ABR kaart
- Rijkspas
- Rijkspas 2
- Sagem YpsID s2
- Sagem YpsID s3
- StarSign Crypto USB Token S
- Swissbit PS-100u SE
- UZI-pas
- UZI-pas 2
- Parameters:
slotId- theslotIdargumentreadWrite- thereadWriteargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- A
-
quickSession
Quickly establishes a session on the 1st unempty slot, with or without login. If thepinis the empty string, then no login will take place. TheuserTypecan be one of the following integer values:-
0>
- Security Officer (0)
- Normal User (1)
- Context Specific (2)
Except for special circumstances, you should always select Normal User. If
pinis the empty string, then no login takes place anduserTypeis ignored.Calling this method takes the place of making separate calls to Initialize, OpenSession, and Login.
- Parameters:
userType- theuserTypeargumentpin- thepinargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setPin
Modifies the PIN of the user that is currently logged in, or the Normal User PIN if the session is not logged in.- Parameters:
oldPin- theoldPinargument (notnull)newPin- thenewPinargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-