Certificates

Commands related to certificate and PKI operations

SYNOPSIS

package require twapi_crypto
cert_blob_to_name ENCODEDBLOB ?options?
cert_create SUBJECT PUBKEY ISSUERCERT ?options?
cert_create_self_signed SUBJECT KEYCONTAINER KEYSPEC ?options?
cert_create_self_signed_from_crypt_context SUBJECT HCRYPT ?options?
cert_duplicate HCERT
cert_enhkey_usage HCERT ?SOURCE?
cert_enum_properties HCERT ?-names?
cert_export HCERT ?-encoding ENCODING?
cert_extension HCERT EXTENSION
cert_file_store_open PATH ?options?
cert_import ENCODEDCERT ?-encoding encoding?
cert_info HCERT
cert_issuer_name HCERT ?options?
cert_key_usage HCERT
cert_locate_private_key HCERT ?options?
cert_name_to_blob NAME ?options?
cert_physical_store_open NAME LOCATION ?options?
cert_physical_store_delete NAME LOCATION
cert_property HCERT PROPERTY
cert_property_delete HCERT PROPERTY
cert_property_set HCERT PROPERTY PROPVAL
cert_release HCERT
cert_request_create SUBJECT HCRYPT KEYSPEC ?options?
cert_request_parse CSR ?-encoding ENCODING?
cert_set_key_prov HCERT KEYCONTAINER KEYSPEC ?options?
cert_store_add_certificate HSTORE HCERT ?-disposition DISPOSITION?
cert_store_add_encoded_certificate HSTORE ENCODEDCERT ?options?
cert_store_commit HSTORE ?-force BOOLEAN?
cert_delete_from_store HCERT
cert_store_enum_contents HSTORE ?HCERT?
cert_store_export_pfx HSTORE PASSWORD ?options?
cert_store_export_pkcs12 HSTORE PASSWORD ?options?
cert_store_export_pkcs7 HSTORE ?-encoding ENCODING?
cert_store_find_certificate HSTORE ?SEARCHTYPE? ?SEARCHTERM? ?HCERT?
cert_store_release HSTORE
cert_store_serialize HSTORE
cert_subject_name HCERT ?options?
cert_system_store_open NAME ?LOCATION? ?options?
cert_system_store_delete NAME LOCATION
cert_system_store_locations LOCATION
cert_system_stores LOCATION
cert_temporary_store ?options?
cert_thumbprint HCERT
cert_tls_verify HCERT ?options?

DESCRIPTION

This module is still experimental and liable to change.

This package provides procedures for managing and operating on digital certificates.

Overview

This page describes the commands related to the Win32 CryptoAPI which deal with X.509 certificates and ancillary services.

For documentation on other cryptographic operations, see the CryptoAPI and SSPI pages.

This documentation expects the reader is familiar with digital certificates. Otherwise the reader may wish to refer to the Windows SDK CryptoAPI documentation for detailed guides and reference documentation.

Certificate stores

The CryptoAPI interface provides functions for handling and storage of X.509 digital certificates. A certificate store is a container for certificates. The container may be a physical store, for example on disk, or a logical store which is a collection of physical stores presented to the application as a single store. Certificate stores may also be created as in-memory temporary stores which are not persisted.

Certain certificate stores, called system stores are predefined by Windows. These include the stores MY, ROOT, Trust and CA. Most applications should store certificates in either the MY store, or in their own custom store.

Note that the system stores are relative to a system store location which must be specified when opening the store. To enumerate the locations of the system stores, use cert_system_store_locations. Optionally, the following predefined values may be used to specify a system store location:

user Certificates associated with the current user account.
users Certificates shared among all user accounts on the system.
service Certificates associated with the current service account.
services Certificates shared among all services on the system.
localmachine Certificates associated with the system.
localmachineenterprise Certificates downloaded from the global enterprise directory.
localmachinegrouppolicy Certificates associated with the group policy for the system.
usergrouppolicy Certificates associated with the group policy for the current user.

To enumerate system stores at a location, use the cert_system_stores.

Most certificate store operations require the store to be first opened or created. Persistent stores are opened or created using the one of the commands cert_system_store_open, cert_physical_store_open or cert_file_store_open as appropriate. Non-persistent stores are created using cert_temporary_store which includes various options for populating the store, for example with the contents of PFX/PKCS #12 or PKCS #7 packets.

The handle returned from these commands must be passed to any commands that operate on stores and released by calling cert_store_release when no longer required.

The returned handle from these commands refers to a cached copy of the store. Any changes made via this handle are made to the cached copy and must be explicitly saved if they need to persist. This can be done either via the -commitenable option when the store is opened, or by calling cert_store_commit.

Commands cert_store_export_pfx, cert_store_export_pkcs12, cert_store_export_pkcs7, and cert_store_serialize can be used to export certificate stores in various formats.

Existing certificate stores can be deleted using the commands cert_system_store_delete, cert_physical_store_delete and cert_file_store_delete. A in-memory certificate store is deleted when its handle is closed.

Certificate properties

When a certificate is placed in a store, it is associated with additional properties that are not part of the certificate itself, for example a private key associated with the certificate. These properties can be enumerated with cert_enum_properties and manipulated with the cert_property, cert_property_set and cert_property_delete commands.

Certificate contexts

Operating on a certificate requires a certificate context which encapsulates all information about the certificate. Most often, the certificate of interest is an existing certificate that is located in a certificate store. The commands for finding certificates in a store return a handle to a suitable certificate context. Similarly, commands that create new certificates or add certificates to a store return handles to certificate contexts as well.

When no longer needed, certificate contexts must be freed by calling cert_release.

Getting certificate contents

The cert_info command returns the fields in a certificate context. The cert_extension command retrieves specific extensions. Two extensions, Intended Key Usage and Enhanced Key Usage, can be also be retrieved with the cert_key_usage and cert_enhkey_usage command. These look up certificate context properties in addition to multiple related extensions in the certificate itself.

The encoded certificate associated with a certificate context can be retrieved with the cert_export command. This can be written to a file or otherwise distributed.

set fd [open MyCert.cer w]
chan configure $fd -translation binary
puts -nonewline $fd [cert_export $hcert]
close $fd

The cert_locate_private_key command locates the private key corresponding to the public key in a certificate.

Finding a certificate in a store

An existing certificate in a store can be retrieved in one of two ways:

Both these commands return a handle to a certificate context that can be used for further operations on the certificate.

Creating a new certificate

New certificates can be created by commands such as cert_create_self_signed, cert_create_signed_from_crypt_context and cert_create. These return handles to certificate contexts that are not associated with any store. The certificates must be explicitly placed in a certificate store if desired.

Creating a new certificate involves several steps. As always, first a cryptographic context is needed that defines the algorithms, keys etc. that will be used to create the certificate.

set crypt [crypt_acquire -keycontainer twapi_test_container -csp {Microsoft Strong Cryptographic Provider} -csptype prov_rsa_full -create 1]

This assumes a key container called twapi_test_container does not exist. All the options specified above happen to be the defaults if unspecified.

The key container is created without any keys so we need to generate public/private key pairs. As we will use the certificate for both signing only, we specify signature for the second parameter.

crypt_key_free [crypt_key_generate $crypt signature -exportable 1]

Note we immediately release the key handles as they are not needed. This does not destroy the underlying keys. We have marked the keys as exportable because we want to later save them to a file for pedagogic purposes. In a real application, signature keys should not and need be exportable.

Next, we create a self signed certificate from the cryptographic context we created. This will use the keys we just added.

set cert [cert_create_self_signed_from_crypt_context "CN=TwapiTestCA" $crypt]

We now have a certificate context for a new self signed certificate. In most cases, we will want to either store it in a certificate store for future use or export it to a file. This is illustrated in succeeding sections of this document.

The cryptographic context is not needed any more and can be released.

crypt_free $crypt

Certificates that are not self-signed are created through cert_create. The private key for the signing certificate must be accessible to the application. The data for the new certificate, such as the subject name, the certificate public key, extensions etc. may be provided by the application itself but more often come from a certificate signing request which is generated elsewhere, possibly even on a different system. The command cert_request_parse can be used to parse such a request and the extracted fields passed to cert_create. The request itself can be created by cert_request_create.

On the requester's side, assuming the key container for the requestor has been already created as in the example above,

set crypt [crypt_acquire -keycontainer twapi_requestor_container -csp {Microsoft Strong Cryptographic Provider} -csptype prov_rsa_full]
set req [cert_request_create "CN=My Subject Name" $crypt keyexchange -keyusage {key_agreement key_encipherment} -enhkeyusage client_auth]
crypt_free $crypt

The above will create a binary which can be sent to the remote signing authority where the certificate request contents can be retrieved:

set parsed_req [cert_request_parse $req]

After verifying the validity of the request (how this is done is entirely up to the application), a certificate for the requestor can be created:

# Assume cissuer is certificate context of signing certificate
set subject [dict get $parsed_req subject]
set pubkey [dict get $parsed_req pubkey]
set opts {}
foreach optname {-basicconstraints -keyusage -enhkeyusage} {
    if {[dict exists $parsed_req extensions $optname]} {
        lappend opts $optname [dict get $parsed_req extensions $optname]
    }
}
set reqcert [cert_create $subject $pubkey $cissuer {*}$opts]

The encoded new certificate returned can be sent back to the requesting client.

Adding and deleting certificates from a store

Certificates can be added and deleted from certificate stores with the commands cert_store_add_certificate and cert_store_delete_certificate respectively. These commands take a certificate context. A certificate that is in encoded form can be added to a store with cert_store_add_encoded_certificate.

Note that adding a certificate to a store creates a copy of the certificate. The original certificate (context) is unmodified.

The sample code below adds the certificate we created in the previous section to a temporary in-memory store. First we create the memory store.

set store [cert_temporary_open]

Then we add the certificate to it.

set mcert [cert_store_add_certificate $store $cert]

This creates a copy of the certificate we created earlier. Since we no longer need the original, we need to free it.

cert_release $cert

There is now one crucial additional step. The association between a certificate and its private key is maintained by the store and is not part of the certificate. We therefore have to explicitly make the association between the CSP key container and the new certificate context for the temporary store.

cert_set_key_prov $mcert twapi_test_container signature -csp {Microsoft Strong Cryptographic Provider} -csptype prov_rsa_full

Notice we have specified exactly the key container we had created earlier.

The certificate is now stored in the temporary store and will be available as long as the volatile temporary store is not closed. As a final step we will export the certificate and the private keys to a file. This step is only necessary if we want to move the certificate elsewhere. (Note if we only wanted to export the certificate without private keys, we would follow the procedure in Getting certificate contents.

set fd [open MyCert.pfx w]
chan configure $fd -translation binary
puts -nonewline $fd [cert_store_export_pfx $store [password] -exportprivate]
close $fd

Note that because we are exporting private keys, a password is required to protect the exported file.

Finally, assuming we have no need to hold on to the certificate, we can free up the resources.

cert_release $mcert
cert_store_release $store

Certificate validation

There are several aspects to validating a certificate. At the very least, the following must be checked:

  • the certificate must have a complete chain to a trusted root certificate authority,
  • the current time must lie in the certificate validity period,
  • none of the certificates in the chain have been revoked,
  • the intended use of the certificate matches that in the certificate
  • the identity specified in the certificate is what is expected

The cert_tls_verify command can be used for this purpose. Currently, TWAPI only supports certificate verification for use in SSL connections.

X.509 alternative names

The X.509 certificate extensions allow for a list of alternative names to be specified for both the certificate subject and issuer. When passed to commands, this list is formatted as a list of alternating name format and name value elements. The allowed name formats and corresponding values are specified in the following table:

other The value is a pair of elements, the first being an OID and the second a binary.
email The value is a RFC 822 email address string.
dns The value is a DNS name string.
directory The value is directory name in binary format.
url The value is a URL string.
ip The value is a binary octet string containing an IP address.
registered The value is a registered OID in string format.

Commands

cert_blob_to_name ENCODEDBLOB ?options?
Converts the encoded X.509 ASN encoded name in ENCODEDBLOB to a string. The following options control how the returned name is formatted.
-format FORMAT Specifies how the output is to be formatted. FORMAT must be one of x500 (default), oid or simple.
-noplus BOOLEAN If true, the plus sign in names is replaced with a single space. Default is false.
-noquote BOOLEAN If true, quoting of special characters in RDN names is disabled. Default is false.
-reverse BOOLEAN If true, order of RDN components is reversed. Default is false.
-separator SEPARATOR Specifies the separator to use between RDN components. SEPARATOR must be one of comma (default), semicolon or newline.
See cert_name_to_blob for the reverse operation.
cert_create SUBJECT PUBKEY ISSUERCERT ?options?
Creates a certificate and returns it in ASN.1 DER-encoded or PEM base-64 encoded format (not as a certificate context). SUBJECT is the name of the subject in X.500 format. PUBKEY is the public key for the certificate subject. ISSUERCERT is the certificate context that will be used to sign the created certificate. The private key associated with this certificate must be accessible to the current process context. The subject name, and alternate name extension if present, from ISSUERCERT will be stored as the issuer name and issuer alternate name extension in the generated certificate.

The following options can be specified for the command:
-altnames ALTNAMES Specifies X.509 Alternative Name values to include in the certificate. ALTNAMES is a pair of one or two elements. The first is a list of pairs containing the name type and name value as described in X.509 alternative names. The second element, which is optional and defaults to false, is a boolean indicating whether the corresponding certificate extension should be marked critical or not.
-basicconstraints BASICCONSTRAINTS Specifies a basic constraints extension to be included in the certificate. BASICCONSTRAINTS is a pair of one or two elements. The first is a triplet consisting of a boolean which should be true if the certificate is to be used for a certificate authority, a boolean that indicates whether the path length value is to be enforced, and a non-negative integer which is the path length value itself. These last are only relevant if the first is true. The second element of BASICCONSTRAINTS, which is optional and defaults to true, is a boolean indicating whether the corresponding certificate extension should be marked critical or not. This element cannot be specified if the -purpose option is specified and contains the value ca.
-capathlen CAPATHLENGTH Specifies the limit on the certificate chain path length during verification. Ignored unless the -purpose option includes ca.
-end ENDTIME Specifies the end of the certificate validity period. ENDTIME must be of the form Year-Month-Day Hour:Minutes:Seconds. Defaults to one year beyond the start time.
-enhkeyusage ENHKEYUSAGE Specifies values to use for the X.509 enhanced key usage extension. ENHKEYUSAGE is a pair of one or two elements, the first of which is a list containing one or more values from client_auth, code_signing, email_protection, ipsec_endsystem, ipsec_tunnel, ipsec_user, server_auth, ocsp_signing, timestamp_signing or a valid OID. The second element, which is optional and defaults to false, is a boolean indicating whether the corresponding certificate extension should be marked critical or not.
-encoding ENCODING Specifies the encoding in which the encoded certificate is returned. ENCODING may be der or pem (default) for DER- and PEM-encoding respectively.
-keyusage KEYUSAGE Specifies values to use for the X.509 key usage extension. KEYUSAGE is a pair of one or two elements, the first of which is a list containing one or more values from crl_sign, data_encipherment, decipher_only digital_signature, encipher_only, key_agreement, key_cert_sign, key_encipherment and non_repudiation. The second element, which is optional and defaults to false, is a boolean indicating whether the corresponding certificate extension should be marked critical or not.
-purpose PURPOSELIST Specifies the purposes for which the certificate is to be used. This is a more convenient method of specifying common extensions. Use of this adds appropriate extensions but does not preclude caller from specifying other extension-based options. PURPOSELIST must be a list containing zero or more items from the following:
ca Indicates that the certificate may be used to sign other certificates as a certificate authority. Sets the basic_constraints extension and the key_cert_sign and crl_sign bits of the keyusage extension. The -basicconstraints option can be specified in this case.
client Indicates the certificate will be used for a SSL/TLS client. Sets digital_signature, key_encipherment and key_agreement in the key usage extension and oid_pkix_kp_client_auth in the enhanced key extension.
server Indicates the certificate will be used for a SSL/TLS server. Sets digital_signature, key_encipherment and key_agreement in the key usage extension and oid_pkix_kp_server_auth in the enhanced key extension.
-signaturealgorithm SIGLAGORITHM Specifies the signature algorithm to use for signing the certificate.
-start STARTTIME Specifies the start of the certificate validity period. STARTTIME must be of the form Year-Month-Day Hour:Minutes:Seconds. Defaults to the current time.
cert_create_self_signed SUBJECT KEYCONTAINER KEYSPEC ?options?
Creates a new certificate context for a self-signed certificate and returns a handle to it. KEYCONTAINER specifies the name of the key container containing the private key to use for signing. KEYSPEC, which must be either keyexchange or signature, specifies the key within that container.

SUBJECT is the name of the subject (and issuer) in X.500 format.

The following options may be specified:
-altnames ALTNAMES See cert_create
-capathlen CAPATHLENGTH See cert_create
-csp CSP Specifies the name of the CSP to be used. If unspecified, the default Microsoft CSP for the system is used.
-csptype CSPTYPE Indicates the type of CSP. Defaults to prov_rsa_full. See Cryptographic Service Providers for all possible types.
-end ENDTIME See cert_create
-enhkeyusage ENHKEYUSAGE See cert_create
-keysettype KEYSETTYPE KEYSETTYPE type must be user (default) or machine depending on whether the key container is user-specific or not.
-keyusage KEYUSAGE See cert_create
-purpose PURPOSELIST See cert_create
-silent BOOLEAN Normally, the CSP may prompt the user for any information that may be required to retrieve the keys. If this option is specified as true, the user is never prompted. Instead the command will raise an error if a user prompt would have been required.
-signaturealgorithm SIGLAGORITHM Specifies the signature algorithm to use for signing the certificate. SIGLAGORITHM is the OID (see ASN.1 Object Identifiers) corresponding to a signature algorithm. Defaults to the SHA1RSA algorithm if unspecified.
-start STARTTIME See cert_create
The returned certificate handle must be freed by calling cert_release. Alternatively, the cert_create_self_signed_from_crypt_context may be used instead if a handle to a cryptographic context is already available.
cert_create_self_signed_from_crypt_context SUBJECT HCRYPT ?options?
Creates a new certificate context for a self-signed certificate and returns a handle to it. The certificate is signed using the cryptographic context referenced by HCRYPT. Alternatively, the cert_create_self_signed may be used instead to explicitly specify the CSP and key container.

SUBJECT is the name of the subject (and issuer) in X.500 format.

The following options may be specified:
-altnames ALTNAMES See cert_create
-capathlen CAPATHLENGTH See cert_create
-end ENDTIME See cert_create
-enhkeyusage ENHKEYUSAGE See cert_create
-keyusage KEYUSAGE See cert_create
-purpose PURPOSES See cert_create
-silent BOOLEAN See cert_create_self_signed.
-signaturealgorithm SIGLAGORITHM See cert_create_self_signed.
-start STARTTIME See cert_create
The returned certificate handle must be freed by calling cert_release.
cert_duplicate HCERT
Duplicates a certificate context and returns a handle to it. The returned certificate context handle may be the same as HCERT with its reference count increased.

The returned certificate context must be freed by calling cert_release.
cert_enhkey_usage HCERT ?SOURCE?
Returns a list of OID's based on the Enhanced Key Usage (EKU) certificate extension content and/or the EKU certificate property. If SOURCE is not specified or is both, the OID's present in both the extension and the property are returned. If SOURCE is extension or property only those corresponding values are returned, the other is not considered. In the case where neither the extension nor the property is present, the string * is returned indicating the certificate is considered valid for all uses. If the returned list is empty, the certificate is considered invalid for any use.
cert_enum_properties HCERT ?-names?
Returns a list of properties defined for the certificate context HCERT. By default, the returned list contains integer property ids. If -names is specified, the returned list contains the mnenomic for the property id (see cert_property) if defined, and the integer value otherwise.
cert_export HCERT ?-encoding ENCODING?
Returns the certificate content for the specified certificate context. The -encoding option controls the encoding of the returned content. ENCODING may be der or pem (default) for DER- and PEM-encoding respectively.
cert_extension HCERT EXTENSION
Returns a certificate extension as a two element list. The first element is a boolean indicating whether the extension is marked critical. The second element is the value of the extension. EXTENSION is the OID for the extension, either in dotted decimal or mnemonic form.
cert_file_store_open PATH ?options?
Opens a certificate store from a file PATH and returns a handle to a cached copy of it. The following options may be specified:
-backupprivilege BOOLEAN If true, specifies that the thread's SE_BACKUP_NAME and SE_RESTORE_NAME privileges must be used to open the store. Default is false.
-commitenable BOOLEAN If true, any changes made to the store are persisted to PATH when the store is closed. Default is false.
-create BOOLEAN If true, a new store is opened only if it did not exist. An error is raised if the store already existed. Default is false so no error is raised in the latter case.
-deferclose BOOLEAN Normally changes to any certificate contexts made after the associated store is closed are not persisted. Setting this option to true will defer the closing of the store until all associated certificate contexts have been released. Default is false.
-existing BOOLEAN If true, when PATH does not already exist, it is not created. An exception is raised instead. Default is false.
-includearchived BOOLEAN By default, enumeration of certificates in a store will not include any that are marked as archived. Setting this option to true will cause those certificates to be included. Default is false.
-maxpermissions BOOLEAN If true, the store is opened with the maximum set of access permissions possible. Default is false.
-readonly BOOLEAN If true, the underlying file is opened in read-only mode. However, changes can still be made to the in-memory cache. Default is false.
The certificate store is written to the file in PKCS #7 format if the file name extension is .p7c or .spc, or if the file was empty. Otherwise the file is written as a serialized certificate store.

The store must be closed with cert_store_release when no longer needed.
cert_import ENCODEDCERT ?-encoding encoding?
Creates and returns a certificate context from encoded data in ENCODEDCERT. ENCODING may be der or pem depending on whether ENCODEDCERT uses DER- or PEM-encoding. If unspecified, the command attempts to determine the encoding itself.
cert_info HCERT
Returns the following fields from a certificate context as a dictionary.
-end The end of the certificate's validity period in the format Year-Month-Day Hour:Minutes:Seconds
-extensions A list of extensions in the certificate. Each element is a triplet containing the OID of the extension, a boolean indicating whether the extension is marked critical or not, and the extension value.
-issuer The name of the certificate issuer.
-issuerid A binary containing unique id for the certificate issuer. This is generally not used and should not be relied on.
-publickey The public key of the subject. This is a pair consisting of the algorithm identifier (in the same format as -signaturealgorithm) and a binary containing the public key.
-serialnumber A binary containing the serial number of the certificate.
-signaturealgorithm A pair consisting of the OID for the algorithm used to sign the certificate and a binary containing any associated parameters.
-start The start of the certificate's validity period in the format Year-Month-Day Hour:Minutes:Seconds.
-subject The name of the certificate subject.
-subjectid A binary containing unique id for the certificate subject. This is generally not used and should not be relied on.
-version The X.509 version of the certificate. Note this is 0-based on V3 certificates will have a value of 2.
cert_issuer_name HCERT ?options?
Returns an issuer name field from the certificate context HCERT. The field may be from the certificate itself or a certificate property in the context. The command returns an empty string if the specified name field does not exist in the certificate.

Refer to cert_subject_name for a list of options.
cert_key_usage HCERT
Returns a list of the Intended Key Usage values in a certificate. The command looks for both the extensions 2.5.29.2 and 2.5.29.15. In the case where the extension is not present, the string * is returned indicating the certificate may be used for any purpose.
cert_locate_private_key HCERT ?options?
Searches key containers to locate the private key corresponding to the public key in the certificate context HCERT. Returns a boolean indicating if it was found. In addition, the located key is associated as a property of the certificate and can be retrieved as the key_prov_info property using the cert_property command.

The following options may be specified:
-keysettype any|user|machine Specifies which key sets are to be searched for the private key. If user or machine, the search is restricted to the containers for the current user or the machine respectively. If any (default), both user and machine containers are searched.
-silent BOOLEAN Normally, the CSP may prompt the user for any information that may be required to access key containers. If this option is specified as true, the user is never prompted. Instead the command will return 0 indicating no key could be found.
cert_name_to_blob NAME ?options?
Converts the string NAME to an X.509 ASN encoded binary. The following options control the allowed format for NAME.
-format FORMAT Specifies how NAME is formatted. FORMAT must be one of x500 (default), oid or simple.
-noplus BOOLEAN If true, the plus sign in NAME is not treated as a value separator. Default is false.
-noquote BOOLEAN If true, quoting is not supported in NAME. Default is false.
-reverse BOOLEAN If true, order of RDN components in NAME is reversed before encoding. Default is false.
-separator SEPARATOR If unspecified, commans and semicolons are parsed as separators. If specified, only SEPARATOR is treated as a separator. SEPARATOR must be one of comma (default), semicolon or newline. In the case of newline, carriage return and linefeed characters are treated as separators.
See cert_blob_to_name for the reverse operation.
cert_physical_store_open NAME LOCATION ?options?
Opens a certificate physical store that is part of a logical system store and returns a handle to a cached copy. NAME is the name of the physical store including the system store component, e.g. Root\.Default. LOCATION specifies the location of the system store and must be one of the values listed in Certificate stores.

Refer to the documentation of cert_system_store_open of a description of options.

The store must be closed with cert_store_release when no longer needed.
cert_physical_store_delete NAME LOCATION
Deletes a certificate physical store that is part of a logical system store. NAME is the name of the physical store including the system store component, e.g. Root\.Default. LOCATION specifies the location of the system store and must be one of the values listed in Certificate stores.
cert_property HCERT PROPERTY
Returns the value of a certificate property in the certificate context referenced by HCERT. Raises an error if the property does not exist in the certificate context. PROPERTY must be one of the following:
access_state A non-0 integer if write operations to the certificate context are persisted and 0 if they are not.
archived If this property exists, the certificate is an archived certificate.
auto_enroll The certificate type for which this certificate has been auto-enrolled.
date_stamp The date and time that the certificate was added to the store.
description The description associated with the certificate for display purposes.
enhkey_usage A list of enhanced key usage OID's.
extended_error_info Any extended error information for the certificate context.
friendly_name The display name for the certificate.
issuer_public_key_md5_hash The MD5 hash of the issuer's public key used to sign the certificate.
issuer_serial_number_md5_hash The MD5 hash of the issuer name and serial number.
key_context A list of two elements containing a handle to the cryptographic context for the certificate and the key type.
key_identifier A binary containing the Subject Key Identifier value if it exists else the SHA1 hash on the certificate Subject Public Key.
key_prov_handle A handle to the associated cryptographic context.
key_prov_info A list containing the following elements: the name of the key container, the name of the CSP, the CSP type, attributes, key container parameters and the key type.
key_spec Specifies the private key.
md5_hash Binary containing the MD5 hash of the certificate.
pvk_file File path of the private key file corresponding to the certificate's public key.
sha1_hash Binary containing the SHA1 hash of the certificate. This can also be retrieved as a hexadecimal string with cert_thumbprint.
signature_hash Signature hash.
subject_name_md5_hash Binary containing the MD5 hash of the encoded subject name.
subject_public_key_md5_hash Binary containing the MD5 hash of the certificate public key.
cert_property_delete HCERT PROPERTY
Deletes a certificate property in the certificate context referenced by HCERT. No error is raised if the property does not exist. PROPERTY must be one of the property names listed in the documentation for cert_property.
cert_property_set HCERT PROPERTY PROPVAL
Sets the value of a certificate property in the certificate context referenced by HCERT. PROPERTY must be one of description, friendly_name or pvk_file (see cert_property).
cert_release HCERT
Decreases the reference count for a certificate context and frees it if the result is 0.
cert_request_create SUBJECT HCRYPT KEYSPEC ?options?
SUBJECT is the name of the subject in X.500 format. Returns an encoded certificate signing request (CSR) that can be sent to a certificate authority. HCRYPT and KEYSPEC together select the public/private key pair for which a certificate is to be requested. HCRYPT is a handle to a cryptographic context and KEYSPEC must be signature or keyexhange to select the appropriate key pair in the context.

The following options may be specified:
-altnames ALTNAMES See cert_create
-capathlen CAPATHLENGTH See cert_create
-encoding ENCODING Specifies the encoding of the returned CSR. ENCODING may be der or pem (default) for DER- and PEM-encoding respectively.
-enhkeyusage ENHKEYUSAGE See cert_create
-keyusage KEYUSAGE See cert_create
-purpose PURPOSES See cert_create
cert_request_parse CSR ?-encoding ENCODING?
Parses a certificate signing request CSR and returns a dictionary with its contents. ENCODING may be der or pem depending on whether ENCODEDCERT uses DER- or PEM-encoding. If unspecified, the command attempts to determine the encoding itself.

The returned dictionary has the following keys:
attributes The attribute field in the CSR. This is a list each element of which is a pair consisting of an OID and a list of corresponding values.
extensions A subset of the attributes key, formatted for easier processing. See the discussion below. This key may be absent if the attributes do not contain any extensions.
pubkey The public key of the requestor. This should be passed to cert_create as the public key argument.
subject The subject name of the requestor. This should be passed to cert_create as the subject argument.
version The CSR format version number.
One of the potential attribute fields in a CSR is OID 1.2.840.113549.1.9.14 through which the requestor can indicate certain certificate extensions to be included in the returned certificate. This specific attribute is parsed and returned as the value of the extensions dictionary element above. This value is itself a dictionary which may contain zero or more of the keys -basicconstraints, -keyusage and -enhkeyusage. The corresponding values have the same format as the corresponding options to the cert_create command.
cert_set_key_prov HCERT KEYCONTAINER KEYSPEC ?options?
Associates the certificate context HCERT with the CSP key container KEYCONTAINER. KEYSPEC must be one of keyexchange (default) or signature and identifies the key within the container. The following options may be specified.
-csp CSP Specifies the name of the CSP for the container. If unspecified, the default Microsoft CSP for the system is used.
-csptype CSPTYPE Indicates the type of CSP. Defaults to prov_rsa_full. See Cryptographic Service Providers for all possible types.
-keysettype KEYSETTYPE KEYSETTYPE must be user (default) or machine.
-silent BOOLEAN Normally, the CSP may prompt the user for any information that may be required to create the context. If this option is specified as true, the user is never prompted. Instead the command will raise an error if a user prompt was required.
cert_store_add_certificate HSTORE HCERT ?-disposition DISPOSITION?
Adds a new certificate to a certificate store. HSTORE is the handle to the store and HCERT is a handle to a certificate context. The new certificate is a copy of HCERT. The command returns a handle to the new certificate context which must be freed with cert_release when no longer needed. Note that the new certificate is not persisted until the store is saved.

Any properties associated with HCERT are also copied to the new certificate context with the exception of any key associations. These must be explicitly added to the new context if desired using cert_set_key_prov.

The -disposition option controls what happens if a matching certificate already exists in the store. DISPOSITION may take one of the following values:
duplicate Creates the new certificate while keeping the existing one. This will create duplicates in the store.
overwrite Overwrites the existing certificate with the new one.
preserve (default) If a matching certificate exists, it is preserved and a error raised. Otherwise, the new certificate is added.
update The new certificate is added if there is no matching certificate or the matching certificate's validity period start time is less than that of the new certificate. Otherwise an error is raised.
cert_store_add_encoded_certificate HSTORE ENCODEDCERT ?options?
Adds a new certificate to a certificate store. HSTORE is the handle to the store. ENCODEDCERT is a binary value containing the certificate encoded in X.509 ASN.1 format. The command returns a handle to the new certificate context which must be freed with cert_release when no longer needed. Note that the new certificate is not persisted until the store is saved.

Supported options are:
-disposition DISPOSITION Controls what happens if a matching certificate already exists in the store. DISPOSITION may take one of the following values:
duplicate Creates the new certificate while keeping the existing one. This will create duplicates in the store.
overwrite Overwrites the existing certificate with the new one.
preserve (default) If a matching certificate exists, it is preserved and a error raised. Otherwise, the new certificate is added.
update The new certificate is added if there is no matching certificate or the matching certificate's validity period start time is less than that of the new certificate. Otherwise an error is raised.
-encoding ENCODING Specifies the encoding of ENCODEDCERT. ENCODING should be der or pem depending on whether ENCODEDCERT uses DER- or PEM-encoding. If unspecified or the empty string, the command will attempt to make the determination itself.
cert_store_commit HSTORE ?-force BOOLEAN?
Commits any changes made to a certificate store. If -force is specified as true, the store is written out even if no changes have been made to the in-memory copy.
cert_delete_from_store HCERT
Deletes the specified certificate context from its containing store. Also decreases the reference count on the certificate context.
cert_store_enum_contents HSTORE ?HCERT?
The command returns a handle to a certificate context for the next certificate in the store specified by the handle HSTORE. When HCERT is not specified or is specified as NULL, the enumeration starts from the first certificate in the store. If HCERT is specified, it must be a handle to a certificate context returned by a previous call to the command. The command then returns the next certificate in the store. The command also frees HCERT (even in case of errors) so caller must not access it after the command returns. If HCERT needs to be accessed later, use the cert_duplicate command to make a copy first.

A certificate context handle returned by the command that is not passed back in as HCERT in a subsequent call, must be released by calling cert_release.

The command returns an empty string when there are no more certificates in the store.

The command cert_store_find_certificate offers another means for retrieving certificates from a store.
cert_store_export_pfx HSTORE PASSWORD ?options?
Returns a binary containing all the certificates in a certificate store in PFX (PKCS #12) format. HSTORE is a handle to the store and PASSWORD is the password to be used for encrypting the returned content. PASSWORD itself must be an empty string (if the returned data is not to be encrypted), or the encryption password in encrypted form as returned by the read_credentials or conceal commands.

The following options may be specified with the command:
-exportprivatekeys BOOLEAN If true, any private keys associated with the exported certificates are included in the returned binary. Default is false.
-failonmissingkey BOOLEAN If true, the command raises an error if any certificate claims to have an associated private key but does actually have one. Default is false.
-failonunexportablekey BOOLEAN If true, the command raises an error if any certificate claims to have an associated private key but does actually have one that is exportable. Default is false.
cert_store_export_pkcs12 HSTORE PASSWORD ?options?
Alias for cert_store_export_pfx.
cert_store_export_pkcs7 HSTORE ?-encoding ENCODING?
Returns a binary in PKCS #7 format containing all the certificates in a certificate store. HSTORE is a handle to the store. External properties associated with certificate are not exported. The -encoding option specifies the encoding for the returned certificate. ENCODING should be der or pem (default) for DER- and PEM-encoding respectively.
cert_store_find_certificate HSTORE ?SEARCHTYPE? ?SEARCHTERM? ?HCERT?
The command returns a handle to a certificate context for the next matching certificate in the store specified by the handle HSTORE. When HCERT is not specified or is specified as NULL, the search starts from the first certificate in the store. If HCERT is specified, it must be a handle to a certificate context returned by a previous call to the command. The search then begins with the next certificate in the store. The command also frees HCERT (even in case of errors) so caller must not access it after the command returns. If HCERT needs to be accessed later, use the cert_duplicate command to make a copy first.

A certificate context handle returned by the command that is not passed back in as HCERT in a subsequent call, must be released by calling cert_release.

The command returns an empty string when there are no more certificates in the store.

The criteria for matching are specified by the SEARCHTYPE and SEARCHTERM arguments as in the table below where the first column specifies possible values of SEARCHTYPE.
any Returns every certificate in the store. SEARCHTERM is ignored.
certificate Returns certificates that exactly match the certificate context whose handle is specified as SEARCHTERM.
issuer_name Returns certificates whose issuer exactly matches SEARCHTERM. SEARCHTERM is a X.509 name in encoded form as returned by cert_name_to_blob.
issuer_substring Returns certificates whose issuer contains the string SEARCHTERM. Note SEARCHTERM is a string, not in X.509 encoded form.
key_identifier Returns certificates with a matching value for the subject key identifier (OID 2.5.29.14) extension.
md5_hash Returns certificates that have a MD5 hash which matches the binary SEARCHTERM.
property Returns certificates that have a property with id SEARCHTERM (see cert_property).
pubkey_md5_hash Returns certificates whose MD5-hashed public key matches the binary SEARCHTERM. The hash should be calculated over the public key in the format returned by crypt_key_export.
public_key Returns certificates containing the specified public key SEARCHTERM. This is a pair consisting of the algorithm identifier (in the same format as -signaturealgorithm) and a binary containing the public key. This binary should be in the format returned by crypt_key_export.
sha1_hash Returns certificates that have a SHA1 hash which matches the binary SEARCHTERM.
signature_hash Returns certificates that have a signature hash which matches the binary SEARCHTERM.
subject_name Returns certificates whose subject exactly matches SEARCHTERM. SEARCHTERM is a X.509 name in encoded form as returned by cert_name_to_blob.
subject_substring Returns certificates whose subject contains the string SEARCHTERM. Note SEARCHTERM is a string, not in X.509 encoded form.
cert_store_release HSTORE
Decreases the reference count for the specified handle to a certificate store and releases associated resources when it reaches 0.
cert_store_serialize HSTORE
Returns a binary containing all the certificates in a certificate store along with their external properties. HSTORE is a handle to the store to be serialized. The returned data may be stored in a file that can be opened with cert_file_store_open.
cert_subject_name HCERT ?options?
Returns a subject name field from the certificate context HCERT. The field may be from the certificate itself or a certificate property in the context.

By default the common name in the certificate is returned. The -name option can be specified to retrieve a different field. The value of the option can be a OID string identifying a certificate name attribute or one of the values in the table below:
dns Returns the DNSName choice in the Alternative Name extension if there is one, or the the CN OID 2.5.4.3 from the Subject Name field. If neither is found returns an empty string.
email Returns the first rfc822Name choice in the Alternative Name extension. If not found, returns the name field for the Email OID. Otherwise returns an empty string.
friendlydisplay Returns the CERT_FRIENDLY_NAME_PROP_ID property if there is one. Otherwise behaves as simpledisplay.
simpledisplay Returns the first attribute suitable for display purposes from Name or Alternative Name extension.
oid_common_name Returns the Common Name (Default).
rdn Returns the Subject Name RDN if there is one. If not found, returns the first Directory Name choice from the Alternative Name extension if there is one. Otherwise returns an empty string. The format for this option can be further controlled as described later.
upn Returns the UPN from the OID 1.3.6.1.4.1.311.20.2.3 in the OtherName choices from the Alternative Name extension and an empty string if not found.
url Returns the URL choice in the Alternative Name extension if there is one. If not found, returns an empty string.
When the -name option is rdn, the following options may be further specified to control the returned format.
-format FORMAT Specifies how the output is to be formatted. FORMAT must be one of x500 (default), oid or simple.
-noplus BOOLEAN If true, the plus sign in names is replaced with a single space. Default is false.
-noquote BOOLEAN If true, quoting of special characters in RDN names is disabled. Default is false.
-reverse BOOLEAN If true, order of RDN components is reversed. Default is false.
-separator SEPARATOR Specifies the separator to use between RDN components. SEPARATOR must be one of comma (default), semicolon or newline.
The command returns an empty string if the specified name does not exist in the certificate.
cert_system_store_open NAME ?LOCATION? ?options?
Opens a logical system store and returns a handle to a cached copy. NAME is the name of the logical store such as Root or My. LOCATION specifies the location of the system store and must be one of the values listed in Certificate stores.

The following options may be specified:
-backupprivilege BOOLEAN If true, specifies that the thread's SE_BACKUP_NAME and SE_RESTORE_NAME privileges must be used to open the store. Default is false.
-create BOOLEAN If true, a new store is opened only if it did not exist. An error is raised if the store already existed. Default is false so no error is raised in the latter case.
-deferclose BOOLEAN Normally changes to any certificate contexts made after the associated store is closed are not persisted. Setting this option to true will defer the closing of the store until all associated certificate contexts have been released. Default is false.
-existing BOOLEAN If true, when PATH does not already exist, it is not created. An exception is raised instead. Default is false.
-includearchived BOOLEAN By default, enumeration of certificates in a store will not include any that are marked as archived. Setting this option to true will cause those certificates to be included. Default is false.
-maxpermissions BOOLEAN If true, the store is opened with the maximum set of access permissions possible. Default is false.
-readonly BOOLEAN If true, the store is opened in read-only mode. Depending on the provider, the effect may be to either disallow all changes to the store, or to allow changes to the in-memory cache but not persisting them. Default is false.
The store must be closed with cert_store_release when no longer needed.
cert_system_store_delete NAME LOCATION
Deletes a certificate system store. NAME is the name of the store and LOCATION specifies its location which must be one of the values listed in Certificate stores.
cert_system_store_locations LOCATION
Returns a list of system store locations. See Certificate stores.
cert_system_stores LOCATION
Returns a list of system stores at the system store location LOCATION. LOCATION specifies the location of the system store and must be one of the values listed in Certificate stores.
cert_temporary_store ?options?
Creates a temporary, non-persistent certificate store in memory and returns a handle to it. The store must be closed with cert_store_release when no longer needed. All contents of the store are deleted when it is closed. The cert_store_save command can be used to save the contents to a persistent store if desired.

By default, the created store is empty. The following mutually exclusive options may be specified to initialize the store with certificates.
-pfx PFXBLOB Initializes the temporary store with certificates imported from a PFX (also known as PKCS #12) formatted packet. In addition to the certificates, any private keys present are also imported into the system. Unlike the store itself, these keys are persisted. The following additional options may be used with -pfx and -pkcs12:
-exportableprivatekeys BOOLEAN If specified as true, private keys in the created certificate store may be exported. Default is false.
-keysettype user|machine Without this option, keys are imported as per-user or per-machine as specified in the PFX blob. This option can be used to override this.
-password PASSWORD Specifies the password used to decrypt PFXBLOB. If the option is not specified, or if PASSWORD is the empty string, the command assumes PFXBLOB is in unencrypted form. If not the empty string, PASSWORD must be in encrypted form as returned by by the read_credentials or conceal commands.
-userprotected BOOLEAN If specified as true, the private keys are protected such that the user is notified on operations that use that key. The specific operations that will trigger notifications depend on the CSP being used.
-pkcs12 PKCS12BLOB This an alias for the -pfx option.
-pkcs7 PKCS7BLOB PKCS7BLOB is a PKCS #7 packet containing certificates. The additional option "-encoding ENCODING" may be used with -pkcs7 where ENCODING may be der, or pem to indicate the packet is DER- or PEM-encoded. If unspecified, the command will attempt to guess the encoding.
-serialized SERIALIZEDBLOB SERIALIZEDBLOB is a serialized certificate store, such as returned from cert_store_serialize.
The temporary store must be closed with cert_store_release when no longer needed.
cert_thumbprint HCERT
Returns a SHA-1 based thumbprint for the specified certificate. This is returned as a hexadecimal string and can be used for a quick comparison to check if two certificates are identical.
cert_tls_verify HCERT ?options?
Verifies a certificate context HCERT for use in an SSL/TLS connection. The following options may be specified:
-cacheendcert BOOLEAN If BOOLEAN is true, the end (leaf) certificate is cached. Default is false.
-disableauthrootautoupdate BOOLEAN If BOOLEAN is true, auto-update of third party roots from the Windows update server is disabled. Default is false.
-engine ENGINE Specifies the chain engine to be used for verification. ENGINE must be user (default) or machine. The engine indicates the namespace and cache to be used for building the verification chain.
-hstore HSTORE Allows specification of another certificate store to be searched for supporting certificates. HSTORE is a handle to a certificate store as returned by commands like cert_system_store_open.
-ignoreerrors ERRORLIST Specifies that certain errors in verification are to be ignored. See description later.
-revocationcheck REVOCATIONSPEC Specifies which certificates in the chain are checked for revocation. REVOCATIONSPEC must be one of all (default) indicating all certificates are to be checked, leaf indicating only the leaf certificate is to be checked, none which disables revocation checks, and excluderoot which indicates all certificates other than the root are to be checked.
-revocationcheckcacheonly BOOLEAN If BOOLEAN is true, only cached revocation lists are checked when verifying revocation. Default is false.
-server SERVER Specifies that the certificate being verified is for a server with name SERVER. If this option is not specified, the verification is done assuming the certificate represents a client. In the former case, it also verifies that the name in the certificate matches SERVER. The command does not verify names in the case of client certificates.

If neither of the options -usageall or -usageany is explicitly specified, they default to server_auth and client_auth respectively depending on whether -server is specified or not.
-trustedroots HCERTLIST Windows requires the root of the certificate verification chain belong to one the Windows' trusted stores. Under some circumstances, such as use of a private certificate authority whose root certificate is not in the Windows trusted store list, the command will return a status of untrustedroot. Instead of ignoring this error through the -ignoreerrors unknownca option, the caller can provide a list of certificate contexts HCERTLIST that are acceptable as trusted root certificates in addition to those in the Windows trusted store.
-urlretrievalcacheonly BOOLEAN If BOOLEAN is true, only cached URLs are used in building the certificate chain without searching the network. Default is false.
-usageall USAGELIST Specifies that the certificate enhanced key usage field must include all the values for USAGELIST. USAGELIST is a list containing OID's or the following values: server_auth, client_auth, code_signing, email_protection, ipsec_end_system, ipsec_tunnel, ipsec_user, timestamp_signing or ipsec_ike_intermediate.
-usageany USAGELIST Specifies that the certificate enhanced key usage field must include any of the values for USAGELIST. USAGELIST is as described for the -usageall option above.
The -ignoreerrors option allows the caller to specify certain error types that are to be ignored in the verification process. This option must be used with great care and only in special circumstances. The argument to the option is a list with one or more of the following values:
basicconstraints Ignore errors in basic constraints.
criticalextensions Ignore errors pertaining to extensions marked as critical that are not understood by CryptoAPI.
name Ignore errors in name validation.
policy Ignore invalid policy errors.
revocation Ignore errors related to certificate revocation.
time Ignore errors in validity period checks.
unknownca Allow the root certificate to not be in the trusted roots list.
usage Ignore errors related to the -usageall and -usageany options.
The command returns ok if the certificate was verified successfully. If the certificate verification process could not be executed, a Tcl exception is raised. If the verification process completed but the certificate did not successfully pass, the command does not raise an exception but returns a Win32 error code or one of the following values:
signature Signature verification failed
revoked Certificate has been revoked
untrustedroot The root certificate is not in the Windows trusted root list
chaining Invalid certificate chain
wrongusage Certificate usage extension did not match specified usage.
expired Certificate has expired.
name Name does not match
policy Certificate did not match policy conditions
basicconstraints Basic constraints check failed
criticalextension Certificate includes an unsupported extension marked as critical
validityperiodnesting Time periods for certificates in the chain are not nested.
norevocationcheck Revocation status of one of the certificates in the chain is unknown.
revocationoffline Revocation checks could not be done because the revocation server was offline.
cnmatch Common name does not match -server option.
purpose The specified purpose is different from the one specified by the issuing CA.
carole The certificate that can be marked for use as a CA is being used as a leaf or vice-versa.

COPYRIGHT

Copyright © 2007-2016 Ashok P. Nadkarni

Tcl Windows API 4.2a5