Cert Lua Reference Documentation
chilkat.Cert
Current Version: 11.7.0
Markdown version of this page for AI tools (v 11.7.0) · all AI docs
Chilkat.Cert
Load public certificates from PEM, DER, Base64, files, strings, binary
data, certificate stores, PFX/P12 files, smart cards, and other sources.
Read subject and issuer fields, serial numbers, fingerprints, validity
dates, key usage, extensions, SAN values, and other X.509 information.
Work with certificates backed by private keys from PFX/P12 files, OS
certificate stores, smart cards, HSMs, PKCS#11 modules, or cloud signing
providers.
Build and inspect certificate chains, verify signatures, check expiration,
examine trust-related information, and work with revocation data.
Pass
Export certificate data in common formats and use detailed diagnostic
output to troubleshoot loading, validation, private-key, chain, or store
problems.
For an extended overview, see
Cert Class Overview.
Load, inspect, validate, and use X.509 certificates throughout Chilkat.
Chilkat.Cert is the central certificate object used throughout
Chilkat for TLS, S/MIME, PKCS7/CMS, PDF signing, XML signing, code signing,
decryption, certificate stores, smart cards, HSMs, PKCS#11, and cloud-based
signing. It provides a broad set of features for loading certificates,
inspecting certificate fields, checking validity, accessing private keys,
building chains, checking revocation status, exporting certificate data, and
diagnosing certificate-related problems.
Load certificates
Inspect certificate details
Private key access
Trust and validation
Use across Chilkat
Cert objects to other Chilkat classes for TLS client
authentication, S/MIME, signing, encryption, decryption, and verification.
Export and diagnostics
Object Creation
local chilkat = require("chilkat")
local cert = chilkat.Cert.new()Creates the object (chilkat.Cert() does the same). Lua's garbage collector frees it when it is no longer referenced; cert:dispose() frees it at once, and in Lua 5.4 and later local cert <close> = chilkat.Cert.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 = cert: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 (cert.verbose_logging = true) and methods use the colon (cert: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
AuthorityKeyId
local strVal = cert.authority_key_id
The authority key identifier of the certificate in base64 string format. This is only present if the certificate contains the extension OID 2.5.29.35.
topAvoidWindowsPkAccess
local boolVal = cert.avoid_windows_pk_access
cert.avoid_windows_pk_access = boolVal
Applies only when running on a Microsoft Windows operating system. If true, then any method that returns a certificate will not try to also access the associated private key, assuming one exists. This is useful if the certificate was installed with high-security such that a private key access would trigger the Windows OS to display a security warning dialog. The default value of this property is false.
CertVersion
local intVal = cert.cert_version
The version of the certificate (1, 2, or 3). A value of 0 indicates an error -- the most likely cause being that the certificate object is empty (i.e. was never loaded with a certificate). Note: This is not the version of the software, it is the version of the X.509 certificate object. The version of the Chilkat certificate software is indicated by the Version property.
topDebugLogFilePath
local strVal = cert.debug_log_file_path
cert.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.
Expired
local boolVal = cert.expired
Has a value of true if the certificate or any certificate in the chain of authority has expired. (This information is not available when running on Windows 95/98 computers.)
ExtendedKeyUsage
local strVal = cert.extended_key_usage
Returns a string containing a comma separated list of keywords with the extended key usages of the certificate. The list of possible extended key usages are:
- serverAuth - TLS WWW server authentication
- clientAuth - TLS WWW client authentication
- codeSigning - Signing of downloadable executable code
- emailProtection - Email protection
- timeStamping - Binding the hash of an object to a time
- OCSPSigning - Signing OCSP responses
ForClientAuthentication
local boolVal = cert.for_client_authentication
true if this certificate can be used for client authentication, otherwise false.
ForCodeSigning
local boolVal = cert.for_code_signing
true if this certificate can be used for code signing, otherwise false.
ForSecureEmail
local boolVal = cert.for_secure_email
true if this certificate can be used for sending secure email, otherwise false.
ForServerAuthentication
local boolVal = cert.for_server_authentication
true if this certificate can be used for server authentication, otherwise false.
ForTimeStamping
local boolVal = cert.for_time_stamping
true if this certificate can be used for time stamping, otherwise false.
IntendedKeyUsage
local intVal = cert.intended_key_usage
Bitflags indicating the intended usages of the certificate.
The flags are:
Digital Signature: 0x80
Non-Repudiation: 0x40
Key Encipherment: 0x20
Data Encipherment: 0x10
Key Agreement: 0x08
Certificate Signing: 0x04
CRL Signing: 0x02
Encipher-Only: 0x01
IsRoot
local boolVal = cert.is_root
true if this is the root certificate, otherwise false.
IssuerC
local strVal = cert.issuer_c
The certificate issuer's country.
topIssuerCN
local strVal = cert.issuer_cn
The certificate issuer's common name.
topIssuerDN
local strVal = cert.issuer_dn
The issuer's full distinguished name.
topIssuerE
local strVal = cert.issuer_e
The certificate issuer's email address.
topIssuerL
local strVal = cert.issuer_l
The certificate issuer's locality, which could be a city, count, township, or other geographic region.
topIssuerO
local strVal = cert.issuer_o
The certificate issuer's organization, which is typically the company name.
topIssuerOU
local strVal = cert.issuer_ou
The certificate issuer's organizational unit, which is the unit within the organization.
topIssuerS
local strVal = cert.issuer_s
The certificate issuer's state or province.
topLastErrorHtml
local strVal = cert.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.
topLastErrorText
local strVal = cert.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.
LastErrorXml
local strVal = cert.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.
topLastMethodSuccess
local boolVal = cert.last_method_success
cert.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.
OcspUrl
local strVal = cert.ocsp_url
If present in the certificate's extensions, returns the OCSP URL of the certificate. (The Online Certificate Status Protocol (OCSP) is an Internet protocol used for obtaining the revocation status of an X.509 digital certificate.)
PrivateKeyExportable
local boolVal = cert.private_key_exportable
(Relevant only when running on a Microsoft Windows operating system.) Indicates whether the private key was installed with security settings that allow it to be re-exported.
Revoked
local boolVal = cert.revoked
Deprecated: This property does not check the revocation status of the certificate, and always returns false. Do not use it to decide whether a certificate is revoked.
To check whether a certificate has been revoked, call CheckRevoked (Windows only), which returns 1 (revoked), 0 (not revoked), or -1 (unable to check). Applications on any operating system can also send an OCSP request to the certificate's OcspUrl, if the certificate has one.
(A property cannot do this work because checking revocation can require contacting a CRL distribution point or an OCSP responder over the network, which can take a long time. In some programming languages, properties are evaluated at design time in the IDE.)
Note: Chilkat does not check certificate revocation status during the TLS handshake. Settings such as RequireSslCertVerify verify signatures, expiration, and the chain to a trusted root, but not revocation. To reject a revoked server certificate, the application must check it after connecting.
Rfc822Name
local strVal = cert.rfc822_name
The RFC822 name of the certificate. (The RFC822 name is one part of the Subject Alternative Name extension of a certificate, if it exists. It is often the only part of the SAN.)
If the certificate contains a list of RFC822 names then this property will return the comma separated list of names.
Starting in Chilkat v9.5.0.85, to get the complete Subject Alternative Name extension as XML, use the SubjectAlternativeName property.
topSelfSigned
local boolVal = cert.self_signed
true if this is a self-signed certificate, otherwise false.
SerialDecimal
local strVal = cert.serial_decimal
The certificate's serial number as a decimal string.
topSerialNumber
local strVal = cert.serial_number
The certificate's serial number as a hexidecimal string.
topSha1Thumbprint
local strVal = cert.sha1_thumbprint
Hexidecimal string of the SHA-1 thumbprint for the certificate. (This is the SHA1 hash of the binary DER representation of the entire X.509 certificate.)
topSignatureVerified
local boolVal = cert.signature_verified
Returns true if the certificate and all certificates in the chain of authority have valid signatures, otherwise returns false.
SmartCardFailReason
local intVal = cert.smart_card_fail_reason
Set after calling LoadFromSmartcard. Possible values are:
- 0 - No failure. The call to LoadFromSmartcard was successful.
- 1 - No smartcard or USB token was detected.
- 2 - The SmartCardPin was provided and the PIN login failed. (Note: Chilkat only PIN authenticates if PKCS11 was the chosen means for communicating with the smartcard.)
- 3 - The certificate matching the specified criteria was not found.
- 99 - Some other undefined failure. Consult the LastErrorText for more information.
SmartCardNoDialog
local boolVal = cert.smart_card_no_dialog
cert.smart_card_no_dialog = boolVal
If set to true, then no dialog will automatically popup if the SmartCardPin is incorrect. Instead, the method requiring the private key on the smart card will fail. The default value of this property is false, which means that if the SmartCardPin property is incorrect, a dialog with prompt will be displayed.
SmartCardPin
local strVal = cert.smart_card_pin
cert.smart_card_pin = strVal
Can be set to the PIN value for a certificate / private key stored on a smart card.
SubjectAlternativeName
local strVal = cert.subject_alternative_name
The subject alternative name (SAN) name of the certificate returned as XML. See the examples linked below.
SubjectC
local strVal = cert.subject_c
The certificate subject's country.
topSubjectCN
local strVal = cert.subject_cn
The certificate subject's common name.
topSubjectDN
local strVal = cert.subject_dn
The certificate subject's full distinguished name.
topSubjectE
local strVal = cert.subject_e
The certificate subject's email address.
topSubjectKeyId
local strVal = cert.subject_key_id
The subject key identifier of the certificate in base64 string format. This is only present if the certificate contains the extension OID 2.5.29.14.
topSubjectL
local strVal = cert.subject_l
The certificate subject's locality, which could be a city, count, township, or other geographic region.
topSubjectO
local strVal = cert.subject_o
The certificate subject's organization, which is typically the company name.
topSubjectOU
local strVal = cert.subject_ou
The certificate subject's organizational unit, which is the unit within the organization.
topSubjectS
local strVal = cert.subject_s
The certificate subject's state or province.
topTrustedRoot
local boolVal = cert.trusted_root
Returns true if the certificate has a trusted root authority, otherwise returns false.
Note: As of version 9.5.0.41, the notion of what your application deems as trusted becomes more specific. The TrustedRoots class/object was added in v9.5.0.0. Prior to this, a certificate was considered to be anchored by a trusted root if the certificate chain could be established to a root (self-signed) certificate, AND if the root certificate was located somewhere in the Windows registry-based certificate stores. There are two problems with this: (1) it's a Windows-only solution. This property would always return false on non-Windows systems, and (2) it might be considered not a strong enough set of conditions for trusting a root certificate.
As of version 9.5.0.41, this property pays attention to the new TrustedRoots class/object, which allows for an application to specificallly indicate which root certificates are to be trusted. Certificates may be added to the TrustedRoots object via the LoadCaCertsPem or AddCert methods, and then activated by calling the TrustedRoots.Activate method. The activated trusted roots are deemed to be trusted in any Chilkat API method/property that needs to make this determination. In addition, the TrustedRoots object has a property named TrustSystemCaRoots, which defaults to true, which allows for backward compatibility. It will trust CA certificates stored in the Windows registry-based certificate stores, or if on Linux, will trust certificates found in /etc/ssl/certs/ca-certificates.crt.
UncommonOptions
local strVal = cert.uncommon_options
cert.uncommon_options = strVal
This is a catch-all property to be used for uncommon needs. This property defaults to the empty string, and should typically remain empty. Possible comma separated keywords can include:
CheckRevokedCacheOnly: Added inv11.2.0. In theCheckRevokedmethod, prevents network access and only checks the cached revocation information on the local computer.
ValidFromStr
local strVal = cert.valid_from_str
The date (in RFC822 string format) that this certificate becomes (or became) valid. It is a GMT/UTC date that is returned.
topValidToStr
local strVal = cert.valid_to_str
The date (in RFC822 string format) that this certificate expires. It is a GMT/UTC date that is returned.
topVerboseLogging
local boolVal = cert.verbose_logging
cert.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.
Version
local strVal = cert.version
Methods
BuildCertChain
-- ok is true, or nil and err on failure
local ok, err = cert:build_cert_chain(cert_chain)
Builds the certificate chain in cert_chain containing all the certificates (including this one), in the chain of authentication to the trusted root (if possible). If this certificate object was loaded from a PFX, then the certiicates contained in the PFX are automatically available for building the certificate chain. The UseCertVault method can be called to provide additional certificates that might be required to build the cert chain. Finally, the TrustedRoots object can be used to provide a way of making trusted root certificates available.
Note: Returns true even if certificate chain is not completed to the root. The certificate chain's ReachesRoot property can be examined to see if the chain was completed to the root.
On Windows systems, the registry-based certificate stores are automatically consulted if needed to locate intermediate or root certificates in the chain. Chilkat searches certificate stores in the following order. See System Store Locations for more information.
- Current-User
CACertificate Store - Local-Machine
CACertificate Store - Current-User
RootCertificate Store - Local-Machine
RootCertificate Store - Current-User
MYCertificate Store - Local-Machine
MYCertificate Store - Current-User
ADDRESSBOOKCertificate Store (if it exists) - Local-Machine
ADDRESSBOOKCertificate Store (if it exists)
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.
CheckRevoked
local n = cert:check_revoked()
Returns 1 if the certificate has been revoked, 0 if not revoked, and -1 if unable to check the revocation status.
Note: This method is only implemented on Windows systems. It uses the underlying Microsoft CertVerifyRevocation Platform SDK function to check the revocation status of a certificate. (Search CertVerifyRevocation to get information about it.) Starting in v11.2.0, the keyword "CheckRevokedCacheOnly" can be included in the UncommonOptions to prevent the Microsoft revocation handler from
accessing any network based resources for revocation checking. In other words, just check the cached revocation information on the local computer.
CertVerifyRevocation can use the certificate's CRL distribution points as well as OCSP. If it returns -1, see the LastErrorText. One cause is that the issuing intermediate CA certificate is not present in the Windows certificate store.
Non-Windows (and Windows) applications can send an OCSP request as shown in the example below. Note that some CAs publish revocation status only through CRLs, not OCSP. For example, Let's Encrypt removed the OCSP URL from its certificates in May 2025 and shut down its OCSP responders in August 2025, so an OCSP request is not possible for current Let's Encrypt certificates.
CheckSmartCardPin
local n = cert:check_smart_card_pin()
Verifies that the SmartCardPin property setting is correct. Returns 1 if correct, 0 if incorrect, and -1 if unable to check because the underlying CSP does not support the functionality.
ExportCertDerBd
-- ok is true, or nil and err on failure
local ok, err = cert:export_cert_der_bd(cer_data)
Exports the digital certificate in ASN.1 DER format to a BinData object.
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.
ExportCertDerFile
-- ok is true, or nil and err on failure
local ok, err = cert:export_cert_der_file(path)
Exports the digital certificate to ASN.1 DER format binary file.
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.
ExportCertPem
local str, err = cert:export_cert_pem()
Exports the digital certificate to an unencrypted PEM formatted string.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
ExportCertPemFile
-- ok is true, or nil and err on failure
local ok, err = cert:export_cert_pem_file(path)
Exports the digital certificate to an unencrypted PEM formatted file.
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.
ExportCertXml
local str, err = cert:export_cert_xml()
Exports a certificate to an XML format where the XML tags are the names of the ASN.1 objects that compose the X.509 certificate. Binary data is either hex or base64 encoded. (The binary data for a bits ASN.1 tag is hex encoded, whereas for all other ASN.1 tags, such as octets, it is base64.)
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
ExportToPfxBd
-- include_cert_chain is a boolean
-- pfx_data is a chilkat.BinData
-- ok is true, or nil and err on failure
local ok, err = cert:export_to_pfx_bd(password, include_cert_chain, pfx_data)
Exports the certificate and private key (if available) to pfx_data. The password is what will be required to access the PFX contents at a later time. If include_cert_chain is true, then the certificates in the chain of authority are also included in the PFX.
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.
ExportToPfxFile
-- pfx_password is a string
-- b_include_cert_chain is a boolean
-- ok is true, or nil and err on failure
local ok, err = cert:export_to_pfx_file(pfx_filename, pfx_password, b_include_cert_chain)
Exports the certificate and private key (if available) to a PFX (.pfx or .p12) file. The output PFX is secured using the pfx_password. If b_include_cert_chain is true, then the certificates in the chain of authority are also included in the PFX output file.
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.
FindIssuer
local cert2, err = cert:find_issuer()
Finds and returns the issuer certificate. If the certificate is a root or self-issued, then the certificate returned is a copy of the caller certificate. (The IsRoot property can be check to see if the certificate is a root (or self-issued) certificate.)
Returns a new object, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead. The returned object is independent of this one.
GetEncoded
local str, err = cert:get_encoded()
Returns a base64 encoded string representation of the certificate's binary DER format, which can be passed to SetFromEncoded to recreate the certificate object.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
GetExtensionAsText
-- str is a string, or nil and err on failure
local str, err = cert:get_extension_as_text(oid)
Returns the certificate extension data as a string. This method should only be called for those extensions with text values NOT stored as binary ASN.1. In most cases, applications should call GetExtensionAsXml because most extensions contain ASN.1 values that need to be decoded..
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
GetExtensionAsXml
-- str is a string, or nil and err on failure
local str, err = cert:get_extension_as_xml(oid)
Returns the certificate extension data in XML format (converted from ASN.1). The oid is an OID, such as the ones listed here: http://www.alvestrand.no/objectid/2.5.29.html
Note: In many cases, the data within the XML is returned base64 encoded. An application may need to take one further step to base64 decode the information contained within the XML.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
GetExtensionBd
-- bd is a chilkat.BinData
-- ok is true, or nil and err on failure
local ok, err = cert:get_extension_bd(oid, bd)
Returns the certificate extension data specified by oid in bd.
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.
GetIssuer
-- ok is true, or nil and err on failure
local ok, err = cert:get_issuer(issuer)
Finds and returns the issuer certificate in issuer. If the certificate is a root or self-issued, then the certificate returned is a copy of the caller certificate. (The IsRoot property can be check to see if the certificate is a root (or self-issued) certificate.)
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.
GetPrivateKey
-- ok is true, or nil and err on failure
local ok, err = cert:get_private_key(priv_key)
Loads the priv_key with the certificate's private key, if it exists. Returns false if the certificate has no associated private key.
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.
GetPrivateKeyPem
local str, err = cert:get_private_key_pem()
Exports the certificate's private key to a PEM string (if the private key is available).
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
GetPubKeyDer
-- bd is a chilkat.BinData
-- ok is true, or nil and err on failure
local ok, err = cert:get_pub_key_der(prefer_pkcs1, bd)
Loads the bd with the certificate's public key in ASN.1 DER format. If the key type (such as RSA) supports both PKCS1 and PKCS8 formats, then prefer_pkcs1 selects which format to return.
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.
GetPublicKey
-- ok is true, or nil and err on failure
local ok, err = cert:get_public_key(pub_key)
Loads the pub_key with the certificate's public key.
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.
GetSignature
-- ok is true, or nil and err on failure
local ok, err = cert:get_signature(bd)
Loads the bd with the certificate's signature.
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.
GetSpkiFingerprint
-- encoding is a string
-- str is a string, or nil and err on failure
local str, err = cert:get_spki_fingerprint(hash_alg, encoding)
Returns the SPKI Fingerprint suitable for use in pinning. (See RFC 7469.) An SPKI Fingerprint is defined as the output of a known cryptographic hash algorithm whose input is the DER-encoded ASN.1 representation of the Subject Public Key Info (SPKI) of an X.509 certificate. The hash_alg specifies the hash algorithm and may be sha256, sha384, sha512, sha1, md2, md5, haval, ripemd128, ripemd160,ripemd256, or ripemd320. The encoding specifies the encoding, and may be base64, hex, or any of the encoding modes specified in the article at the link below.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
GetSubjectPart
-- str is a string, or nil and err on failure
local str, err = cert:get_subject_part(part_name_or_oid)
Returns a part of the certificate's subject by name or OID. The part_name_or_oid can be a part name, such as CN, O, OU, E, S, L, C, or SERIALNUMBER, or it can be an OID such as 2.5.4.3.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
HashOf
-- hash_alg is a string
-- encoding is a string
-- str is a string, or nil and err on failure
local str, err = cert:hash_of(part, hash_alg, encoding)
Returns an encoded hash of a particular part of the certificate. The part may be one of the following:
- IssuerDN
- IssuerPublicKey
- SubjectDN
- SubjectPublicKey
The hash_alg is the name of the hash algorithm, such as sha1, sha256, sha384, sha512, md5, etc. The encoding is the format to return, such as hex, base64, etc.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
HasPrivateKey
local flag = cert:has_private_key()
Returns true if a private key associated with the certificate is available.
Returns true or false: an answer, not a success flag.
IsEcdsa
local flag = cert:is_ecdsa()
Returns true if certificate is ECDSA-based (i.e. has an ECDSA key).
Returns true or false: an answer, not a success flag.
IsRsa
local flag = cert:is_rsa()
Returns true if certificate is RSA-based (i.e. has an RSA key).
Returns true or false: an answer, not a success flag.
LinkPkcs11
-- ok is true, or nil and err on failure
local ok, err = cert:link_pkcs11(session)
Links to the certificate's private key located on an HSM (smart card, token, or cloud HSM). Once linked, the certificate can be used for signing where the signing occurs on the HSM. See the example below for more detailed information.
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.
LoadByCommonName
-- ok is true, or nil and err on failure
local ok, err = cert:load_by_common_name(cn)
This method searches for a certificate with the specified common name (CN) on different operating systems.
- On Windows, it searches the Local Machine and Current User certificate stores.
- On macOS and iOS, it searches the Default and System Keychains.
If the certificate is found, it is loaded and ready for use.
Note: Chilkat v10.0.0 or later is needed for Apple Keychain.
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.
LoadByEmailAddress
-- ok is true, or nil and err on failure
local ok, err = cert:load_by_email_address(email_address)
This method searches for a certificate with the specified email address on different operating systems.
- On Windows, it searches the Local Machine and Current User certificate stores.
- On macOS and iOS, it searches the Default and System Keychains.
If the certificate is found, it is loaded and ready for use.
Note: Chilkat v10.0.0 or later is needed for Apple Keychain.
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.
LoadByIssuerAndSerialNumber
-- serial_number is a string
-- ok is true, or nil and err on failure
local ok, err = cert:load_by_issuer_and_serial_number(issuer_cn, serial_number)
This method searches for a certificate with the specified issuer common name (issuer_cn) and serial number (serial_number) on different operating systems.
- On Windows, it searches the Local Machine and Current User certificate stores.
- On macOS and iOS, it searches the Default and System Keychains.
If the certificate is found, it is loaded and ready for use.
Note: Chilkat v10.0.0 or later is needed for Apple Keychain.
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.
LoadBySubjectOid
-- value is a string
-- ok is true, or nil and err on failure
local ok, err = cert:load_by_subject_oid(oid, value)
This method searches for a certificate containing a subject part matching the oid and value.
On Windows, it searches the Local Machine and Current User certificate stores.
- On macOS and iOS, it searches the Default and System Keychains.
If the certificate is found, it is loaded and ready for use.
Note: Chilkat v10.0.0 or later is needed for Apple Keychain.
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.
LoadByThumbprint
-- encoding is a string
-- ok is true, or nil and err on failure
local ok, err = cert:load_by_thumbprint(thumbprint, encoding)
This method searches for a certificate with the specified thumbprint. The thumbprint is passed as a string using the encoding specified by encoding (such as base64, hex, etc.).
On Windows, it searches the Local Machine and Current User certificate stores.
- On macOS and iOS, it searches the Default and System Keychains.
If the certificate is found, it is loaded and ready for use.
Note: Chilkat v10.0.0 or later is needed for Apple Keychain.
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.
LoadFromBase64
-- ok is true, or nil and err on failure
local ok, err = cert:load_from_base64(encoded_cert)
Loads an ASN.1 or DER encoded certificate represented in a Base64 string.
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.
LoadFromBd
-- ok is true, or nil and err on failure
local ok, err = cert:load_from_bd(cert_bytes)
Loads an X.509 certificate from data contained in cert_bytes.
Note: The cert_bytes may contain the certificate in any format. It can be binary DER (ASN.1), PEM, Base64, etc. Chilkat will automatically detect the format.
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.
LoadFromFile
-- ok is true, or nil and err on failure
local ok, err = cert:load_from_file(path)
Loads a certificate from a .cer, .crt, .p7b, or .pem file. This method accepts certificates from files in any of the following formats:
1. DER encoded binary X.509 (.CER)
2. Base-64 encoded X.509 (.CER)
3. Cryptographic Message Syntax Standard - PKCS #7 Certificates (.P7B)
4. PEM format
This method decodes the certificate based on the contents if finds within the file, and not based on the file extension. If your certificate is in a file having a different extension, try loading it using this method before assuming it won't work. This method does not load .p12 or .pfx (PKCS #12) files.
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.
LoadFromSmartcard
-- ok is true, or nil and err on failure
local ok, err = cert:load_from_smartcard(cert_spec)
Important: It's important to set the SmartCardPin property before calling this method.
Loads a certificate and its associated private key (if available) from a connected USB token or smart card. This function works on Windows, Linux, MacOS, iOS, and Alpine Linux. If multiple USB tokens and/or smartcards are connected to the system, then each will be searched and the first matching certificate will be loaded.
The cert_spec can have the following formats and values:
- Empty String: Passing the empty string is the most common way to call this function. Pass the empty string when only one HSM (USB token or smart card) is connected to the system, and it contains only one certificate with a private key. The HSM can contain other certificates, but Chilkat will automatically choose and load the certificate that has the associated private key also located on the HSM.
- cn=<cert subject common name>: Finds and loads the certificate having the specified subject common name (CN).
- subjectdn_withtags=<distinguished name with tags>: Finds and loads the certificate having the specified DN with tags. For example, subjectdn_withtags=C=US, O=Example Corporation, OU=IT Department, CN=www.example.com
- subjectdn=<distinguished name without tags>: Finds and loads the certificate having the specified DN without tags. For example, subjectdn=US, California, San Francisco, Example Corp, Engineering, www.example.com, support@example.com
- issuercn=<subject hex serial:issuer common name>: Finds and loads the certificate having the specified hex serial number and an issuer with the specified common name. For example,
01020304: Let's Encrypt Authority X1 - serial=<hex serial number>: Finds and loads the certificate having the specified hexidecimal serial number.
- thumbprint=<hex SHA1 thumbprint>: Finds and loads the certificate having the specified hexidecimal SHA1 thumbprint.
- policyoid=<certificate policy OID>: Finds and loads the certificate having a policy OID equal to the specified value, such as 2.16.840.1.101.2.1.11.39.
- o=<subject organization>: Finds and loads the certificate having the
Osubject part equal to the specified value. - c=<subject country>: Finds and loads the certificate having the
Csubject part equal to the specified value. - l=<subject locality>: Finds and loads the certificate having the
Lsubject part equal to the specified value. - ou=<subject organizational unit>: Finds and loads the certificate having the
OUsubject part equal to the specified value. - st=<subject state>: Finds and loads the certificate having the
STsubject part equal to the specified value. - e=<subject email>: Finds and loads the certificate having the
Esubject part equal to the specified value.
On Windows systems, cert_spec can specify a CSP (Cryptographic Service Provider) name, such as YubiHSM Key Storage Provider. This option is retained for legacy support, as Chilkat initially handled USB tokens and smartcards only on Windows via CSPs. Chilkat now supports HSMs across multiple platforms (Windows, Linux, macOS, iOS, Alpine Linux) and uses various methods to communicate with HSMs, including PKCS11, macOS Keychain services, Windows ScMinidriver, MsCNG, and legacy Windows CryptoAPI. Chilkat automatically detects the HSM make/model and selects the optimal communication method.
Some possible CSP values are:
- Microsoft Smart Card Key Storage Provider
- Microsoft Base Smart Card Crypto Provider
- Bit4id Universal Middleware Provider
- YubiHSM Key Storage Provider (starting in v9.5.0.83)
- SafeSign Standard Cryptographic Service Provider
- SafeSign Standard RSA and AES Cryptographic Service Provider
- eToken Base Cryptographic Provider
- cryptoCertum3 CSP
- FTSafe ePass1000 RSA Cryptographic Service Provider
- SecureStoreCSP
- EnterSafe ePass2003 CSP v2.0
- Gemalto Classic Card CSP
- PROXKey CSP India V1.0
- PROXKey CSP India V2.0
- TRUST KEY CSP V1.0
- Watchdata Brazil CSP V1.0
- Luna Cryptographic Services for Microsoft Windows
- Luna SChannel Cryptographic Services for Microsoft Windows
- Safenet RSA Full Cryptographic Provider
- nCipher Enhanced Cryptographic Provider
- MySmartLogon NFC CSP
- NFC Connector Enterprise
- ActivClient Cryptographic Service Provider
- EnterSafe ePass2003 CSP v1.0
- Oberthur Card Systems Cryptographic Provider
- Athena ASECard Crypto CSP
- many others...
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.
LoadPem
-- ok is true, or nil and err on failure
local ok, err = cert:load_pem(str_pem)
Loads the certificate from a PEM string.
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.
LoadPfxBd
-- password is a string
-- ok is true, or nil and err on failure
local ok, err = cert:load_pfx_bd(pfx_data, password)
Loads the certificate from the PFX contained in pfx_data. Note: If the PFX contains multiple certificates, the 1st certificate in the PFX is loaded.
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.
LoadPfxFile
-- password is a string
-- ok is true, or nil and err on failure
local ok, err = cert:load_pfx_file(pfx_path, password)
Loads a PFX file. Note: If the PFX contains multiple certificates, the 1st certificate in the PFX is loaded.
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.
PemFileToDerFile
-- to_path is a string
-- ok is true, or nil and err on failure
local ok, err = cert:pem_file_to_der_file(from_path, to_path)
Converts a PEM file to a DER file.
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.
SaveToFile
-- ok is true, or nil and err on failure
local ok, err = cert:save_to_file(path)
Saves a certificate object to a .cer file.
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.
SetCloudSigner
-- ok is true, or nil and err on failure
local ok, err = cert:set_cloud_signer(json)
Provides information for a cloud signing service to do the signing via a remote signing server. Current supported services are AWS KMS, Azure Key Vault, and ARSS (Aruba Remote Signing Service). See the examples 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.
SetFromEncoded
-- ok is true, or nil and err on failure
local ok, err = cert:set_from_encoded(encoded_cert)
Initializes the certificate object from a base64 encoded string representation of the certificate's binary DER format.
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.
SetPrivateKey
-- ok is true, or nil and err on failure
local ok, err = cert:set_private_key(priv_key)
Used to associate a private key with the certificate for subsequent (PKCS7) signature creation or decryption.
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.
SetPrivateKeyPem
-- ok is true, or nil and err on failure
local ok, err = cert:set_private_key_pem(priv_key_pem)
Same as SetPrivateKey, but the key is provided in unencrypted PEM format. (Note: The priv_key_pem is not a file path, it is the actual PEM text.)
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.
Unload
local ok, err = cert:unload()
Unload the certificate, which could mean closing a PKCS11 session if the certificate was loaded from a 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.
UploadToCloud
-- json_out is a chilkat.JsonObject
-- ok is true, or nil and err on failure
local ok, err = cert:upload_to_cloud(json_in, json_out)
This is an open-ended method to accomodate uploading the private key to a cloud service, such as AWS KMS, or Azure Key Vault. For details, see the examples 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.
UseCertVault
-- ok is true, or nil and err on failure
local ok, err = cert:use_cert_vault(vault)
Adds an XML certificate vault to the object's internal list of sources to be searched for certificates for help in building certificate chains and verifying the certificate signature to the trusted root.
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.
VerifySignature
local flag = cert:verify_signature()
Verifies the certificate signature, as well as the signatures of all certificates in the chain of authentication to the trusted root. Returns true if all signatures are verified to the trusted root. Otherwise returns false.
Returns true or false: an answer, not a success flag.
X509PKIPathv1
local str, err = cert:x509_pki_pathv1()
Returns the base64 representation of an X509PKIPathv1 containing just the calling certificate. This is typically used in an X.509 Binary Security Token. It is a PKIPath that contains an ordered list of X.509 public certificates packaged in a PKIPath. The X509PKIPathv1 token type may be used to represent a certificate path. (This is sometimes used in XAdES signatures.)
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, chilkat.Cert reports progress to the functions given to set_event_handler, in a table keyed by event name (plain functions, not methods: closures carry whatever state they need):
cert:set_event_handler({
percent_done = function(pct) print(pct .. "%") end, -- return true to abort
progress_info = function(name, value) print(name, value) end,
})Installs the handlers, replacing any installed before; cert:set_event_handler(nil) removes them. The event names are checked when the table is installed: a misspelled one raises an error.
The abort_check handler is called periodically during long operations; percent_done is called when an operation's completion percentage is known; progress_info delivers named progress values. A true return from abort_check or percent_done aborts the running method, which then fails in the usual way (nil, err). An error raised in a handler aborts the method and is raised again from the method call; the object remains usable.
AbortCheck
cert:set_event_handler({ abort_check = function() ... end })
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example
local deadline = os.time() + 30 -- give up after 30 seconds
cert:set_event_handler({ abort_check = function() return os.time() > deadline end })PercentDone
cert:set_event_handler({ percent_done = function(pct_done) ... end })
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
cert:set_event_handler({
percent_done = function(pct_done) -- 0 to 100
print("Percent done: " .. pct_done)
return false -- return true to abort the method in progress
end,
})ProgressInfo
cert:set_event_handler({ progress_info = function(name, value) ... end })
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example
cert:set_event_handler({
progress_info = function(name, value) print(name .. ": " .. value) end,
})