Pkcs11 Lua Reference Documentation

chilkat.Pkcs11

Current Version: 11.7.0

Markdown version of this page for AI tools (v 11.7.0) · all AI docs

Chilkat.Pkcs11

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.

Object Creation

local chilkat = require("chilkat")

local pkcs11 = chilkat.Pkcs11.new()
local pkcs11 = chilkat.Pkcs11.new()

Creates the object (chilkat.Pkcs11() does the same). Lua's garbage collector frees it when it is no longer referenced; pkcs11:dispose() frees it at once, and in Lua 5.4 and later local pkcs11 <close> = chilkat.Pkcs11.new() frees it when the block ends. Calling a method of a disposed object raises an error.

Errors

A method that fails returns nil followed by the error text, as io.open does: local body, err = pkcs11:method(...), where err is the object's last_error_text. Wrap the call in assert() to raise an error with that text instead. Methods that answer a question return true or false, numbers are returned as they are (check last_method_success where the description says a value means failure), and property reads and writes never fail for Chilkat reasons.

Misuse raises a Lua error: a wrong argument type or a missing argument (bad argument #1 to ...), an unknown property name, a write to a read-only property, an out-of-range integer, or an object of the wrong class.

Names are Chilkat's in snake_case: QuickGetStr is quick_get_str, LastErrorText is last_error_text. Properties are fields (pkcs11.verbose_logging = true) and methods use the colon (pkcs11:method(...)). Strings are UTF-8; binary data is a Lua string of bytes. Indexes are 0-based, as in every Chilkat API. Unlocking: call chilkat.unlock_bundle("...") once at startup.

Properties

DebugLogFilePath
-- strVal is a string
local strVal = pkcs11.debug_log_file_path
pkcs11.debug_log_file_path = strVal

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
LastErrorHtml
-- strVal is a string (read-only)
local strVal = pkcs11.last_error_html

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
-- strVal is a string (read-only)
local strVal = pkcs11.last_error_text

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
-- strVal is a string (read-only)
local strVal = pkcs11.last_error_xml

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastMethodSuccess
-- boolVal is a boolean
local boolVal = pkcs11.last_method_success
pkcs11.last_method_success = boolVal

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
NumCerts
-- intVal is an integer (read-only)
local intVal = pkcs11.num_certs
Introduced in version 9.5.0.88

The number of certificates contained on the smart card or USB token. This property is set when FindAllCerts is called.

top
SharedLibPath
-- strVal is a string
local strVal = pkcs11.shared_lib_path
pkcs11.shared_lib_path = strVal
Introduced in version 9.5.0.88

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.

On Linux, MacOSX, or other non-Windows systems, this can also be either the full path to the .so or .dylib, or just the .so or .dylib filename. On these systems, Chilkat calls the https://man7.org/linux/man-pages/man3/dlopen.3.html>dlopen system function to load the shared library. If just the filename is passed in, the directories searched are those indicated in the dlopen function description at https://man7.org/linux/man-pages/man3/dlopen.3.html

More Information and Examples
top
SigContextPin
-- strVal is a string
local strVal = pkcs11.sig_context_pin
pkcs11.sig_context_pin = strVal
Introduced in version 9.5.0.97

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.

More Information and Examples
top
UncommonOptions
-- strVal is a string
local strVal = pkcs11.uncommon_options
pkcs11.uncommon_options = strVal
Introduced in version 9.5.0.99

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.

top
VerboseLogging
-- boolVal is a boolean
local boolVal = pkcs11.verbose_logging
pkcs11.verbose_logging = boolVal

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
-- strVal is a string (read-only)
local strVal = pkcs11.version

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

CloseSession
-- ok is true, or nil and err on failure
local ok, err = pkcs11:close_session()
Introduced in version 9.5.0.88

Closes the session on the token (i.e. smart card).

Note: Memory leaks can occur if the session is not properly closed.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
CreatePkcs11Object
-- attrs is a chilkat.JsonObject
-- n is an integer
local n = pkcs11:create_pkcs11_object(attrs)
Introduced in version 9.5.0.96

Creates an object and returns the handle. The attrs specifies the attributes that define the object to be created. See the linked examples below for more information.

top
DestroyObject
-- h_object is an integer
-- ok is true, or nil and err on failure
local ok, err = pkcs11:destroy_object(h_object)
Introduced in version 9.5.0.96

Destroys an object (deletes it from the HSM). h_object is the object's handle.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
Discover
-- only_tokens_present is a boolean
-- json is a chilkat.JsonObject
-- ok is true, or nil and err on failure
local ok, err = pkcs11:discover(only_tokens_present, json)
Introduced in version 9.5.0.88

Discovers the readers, smart cards, and USB tokens accessible via PKCS11 on the computer (using the DLL/shared lib specified by SharedLibPath). The only_tokens_present specifies if only slots (readers) with tokens (smart cards) present should be returned. The information is written to the json. (For details, see the example below.)

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
ExportPublicKey
-- key_handle is an integer
-- pub_key is a chilkat.PublicKey
-- ok is true, or nil and err on failure
local ok, err = pkcs11:export_public_key(key_handle, pub_key)
Introduced in version 9.5.0.96

Export a public key given a public or private key handle. The pub_key is loaded with the exported public key.

See the example linked below for more details.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
FindAllCerts
-- ok is true, or nil and err on failure
local ok, err = pkcs11:find_all_certs()
Introduced in version 9.5.0.88

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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
FindAllKeys
-- key_class is a string
-- json is a chilkat.JsonObject
-- ok is true, or nil and err on failure
local ok, err = pkcs11:find_all_keys(key_class, json)
Introduced in version 9.5.0.96

Finds all keys contained on the smart card (or USB token). The key_class indicates 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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
FindCert
-- cert_part is a string
-- part_value is a string
-- cert is a chilkat.Cert
-- ok is true, or nil and err on failure
local ok, err = pkcs11:find_cert(cert_part, part_value, cert)
Introduced in version 9.5.0.88

Finds the certificate where the given cert_part equals the part_value. Possible values for cert_part are: privateKey, subjectDN, subjectDN_withTags, subjectCN, serial, or serial:issuerCN. If cert_part equals privateKey, then pass an empty string in part_value. Specifying privateKey means to return the first certificate having a private key.

The cert is 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 cert will 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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
FindObject
-- json_template is a chilkat.JsonObject
-- n is an integer
local n = pkcs11:find_object(json_template)
Introduced in version 9.5.0.96

General function for finding an object such as a private key. Returns the handle of the first matching object, or 0 if not found.

More Information and Examples
top
GenEcKey
-- public_attrs is a chilkat.JsonObject
-- private_attrs is a chilkat.JsonObject
-- json_out is a chilkat.JsonObject
-- pub_key is a chilkat.PublicKey
-- ok is true, or nil and err on failure
local ok, err = pkcs11:gen_ec_key(public_attrs, private_attrs, json_out, pub_key)
Introduced in version 9.5.0.96

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 in pub_key. The public_attrs and private_attrs contain attributes for the public and private keys respectively. The PKCS11 public and private key handles are returned in json_out. 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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GenRsaKey
-- public_attrs is a chilkat.JsonObject
-- private_attrs is a chilkat.JsonObject
-- json_out is a chilkat.JsonObject
-- pub_key is a chilkat.PublicKey
-- ok is true, or nil and err on failure
local ok, err = pkcs11:gen_rsa_key(public_attrs, private_attrs, json_out, pub_key)
Introduced in version 9.5.0.96

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 in pub_key. The public_attrs and private_attrs contain attributes for the public and private keys respectively. The PKCS11 public and private key handles are returned in json_out. 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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GenSecretKey
-- key_type is a string
-- json_template is a chilkat.JsonObject
-- n is an integer
local n = pkcs11:gen_secret_key(key_type, json_template)
Introduced in version 9.5.0.96

Generates a symmetric encryption key. The key_type is the key type, which can be one of the following values:

  • AES
  • AES XTS
  • Blowfish
  • Twofish
  • ChaCha20

The json_template is 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.

More Information and Examples
top
GetCert
-- index is an integer
-- cert is a chilkat.Cert
-- ok is true, or nil and err on failure
local ok, err = pkcs11:get_cert(index, cert)
Introduced in version 9.5.0.88

Loads cert with the Nth certificate indicated by index. 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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
ImportPrivateKey
-- priv_key is a chilkat.PrivateKey
-- json_template is a chilkat.JsonObject
-- n is an integer
local n = pkcs11:import_private_key(priv_key, json_template)
Introduced in version 9.5.0.96

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.

More Information and Examples
top
ImportSshKey
-- ssh_key is a chilkat.SshKey
-- json_template is a chilkat.JsonObject
-- n is an integer
local n = pkcs11:import_ssh_key(ssh_key, json_template)
Introduced in version 9.5.0.96

Imports an SSH private key onto the HSM. Returns the handle of the unwrapped key, or 0 if failed.

More Information and Examples
top
Initialize
-- ok is true, or nil and err on failure
local ok, err = pkcs11:initialize()
Introduced in version 9.5.0.88

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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
InitPin
-- pin is a string
-- ok is true, or nil and err on failure
local ok, err = pkcs11:init_pin(pin)
Introduced in version 9.5.0.89

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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
InitToken
-- slot_id is an integer
-- pin is a string
-- token_label is a string
-- ok is true, or nil and err on failure
local ok, err = pkcs11:init_token(slot_id, pin, token_label)
Introduced in version 9.5.0.89

Initializes a token. slot_id is 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 pin parameter 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.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
Login
-- user_type is an integer
-- pin is a string
-- ok is true, or nil and err on failure
local ok, err = pkcs11:login(user_type, pin)
Introduced in version 9.5.0.88

Authenticates a session with a PIN. The user_type can be one of the following integer values:

    0>
  1. Security Officer (0)
  2. Normal User (1)
  3. Context Specific (2)

Except for special circumstances, you'll always login as the Normal User.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
Logout
-- ok is true, or nil and err on failure
local ok, err = pkcs11:logout()
Introduced in version 9.5.0.88

Logs out from a token (smart card).

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
OpenSession
-- slot_id is an integer
-- read_write is a boolean
-- ok is true, or nil and err on failure
local ok, err = pkcs11:open_session(slot_id, read_write)
Introduced in version 9.5.0.88

Opens a session on the token (i.e. smart card). The slot_id is the ID of the slot (not the index). Set slot_id equal to -1 to choose the first available non-empty slot. The read_write indicates whether the session should be read-only or read-write.

The PKCS11 terminology is confusing:

  • A slot corresponds to a connected smart card reader or USB hardware token, such as a Feitian ePass3003Auto token.
  • A token corresponds 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 a smart card inserted, 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 C PKCS11 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.5 DLL is aetpkss1.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

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
QuickSession
-- user_type is an integer
-- pin is a string
-- ok is true, or nil and err on failure
local ok, err = pkcs11:quick_session(user_type, pin)
Introduced in version 9.5.0.96

Quickly establishes a session on the 1st unempty slot, with or without login. If the pin is the empty string, then no login will take place. The user_type can be one of the following integer values:

    0>
  1. Security Officer (0)
  2. Normal User (1)
  3. Context Specific (2)

Except for special circumstances, you should always select Normal User. If pin is the empty string, then no login takes place and user_type is ignored.

Calling this method takes the place of making separate calls to Initialize, OpenSession, and Login.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SetPin
-- old_pin is a string
-- new_pin is a string
-- ok is true, or nil and err on failure
local ok, err = pkcs11:set_pin(old_pin, new_pin)
Introduced in version 9.5.0.89

Modifies the PIN of the user that is currently logged in, or the Normal User PIN if the session is not logged in.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top