Commands related to cryptographical operations
This package provides procedures related to cryptographic services provided by the Windows platforms.
This page describes the base commands related to the Win32 CryptoAPI (CAPI) which includes functions related to encryption, decryption, signatures and ancillary services.
Other functions provided by CAPI are documented in the Certificates and SSPI pages.
This documentation expects the reader is familiar with the use of cryptography. An overview of the concepts in CAPI is provided but the API itself is fairly complex and a series of blog posts on the use of these commands may prove useful. The reader may also wish to refer to the Windows SDK CryptoAPI documentation.
A Cryptographic Service Providers (CSP) on Windows is a software module that implements a set of cryptographical functions such as encryption or key storage. There may be multiple such modules on a system, each implementing one of more cryptographic algorithms for one or more cryptographic functions. Applications implement cryptographic operations by calling a standard interface defined by Windows and implemented by the CSPs.
Some CSP's come with the Windows operating system while others are implemented by third parties. The feature set implemented by each CSP is different and can depend on factors such as the operating system version, and because of US export restrictions, the country. Based on the supported features, CSP's have an associated CSP type. For example, a CSP of type PROV_RSA_FULL supports digital signatures and encryption using the RSA public key algorithm. On the other hand, a CSP of type PROV_DSS uses the DSA algorithm and only supports hashes and signatures. When creating a Cryptographic contexts, an application needs to specify a CSP type that supports the desired operations. The following types are recognized: prov_rsa_full, prov_rsa_sig, prov_dss, prov_fortezza, prov_ms_exchange, prov_ssl, prov_rsa_schannel, prov_dss_dh, prov_ec_ecdsa_sig, prov_ec_ecnra_sig, prov_ec_ecdsa_full, prov_ec_ecnra_full, prov_dh_schannel, prov_spyrus_lynks, prov_rng, prov_intel_sec, prov_replace_owf, prov_rsa_aes. Refer to the Windows SDK for details about the features provided by each. For most applications, the default prov_rsa_full is sufficient.
Two standard providers shipped as part of Windows are Microsoft Base Cryptographic Provider and the Microsoft Strong Cryptographic Provider. On most systems, the latter is the default when no specific CSP is selected and is sufficient in most cases unless some special functionality like hardware based cryptography is desired.
The commands csps and csp_types return the list of CSP's and CSP types on the system.
The keys used for cryptographic operations are stored in key containers within a CSP's control. The keys are not generally exposed directly to an application but rather the CSP carries out the operations using the keys on the application's behalf.
A CSP may be associated with multiple key containers, each identified by a name. The specific key container and the keys within that container that are used for an operation depends on the Cryptographic contexts is bound at the time the context is created via the crypt_acquire command. This command also allows creation of new key containers within a CSP if they do not exist.
Depending on the options specified and the account under which they are created, key containers are created with restricted access. The exact access depends on the account group membership (e.g. whether an adminitrator or not) and operating system version. Applications can set specific access rules by setting a DACL on the container using crypt_set_security_descriptor.
To delete key containers, use the crypt_key_container_delete command.
A key container may be created as a user key set or a computer key set. These are distinguished based on where they are stored and who has access to them. Refer to the Windows SDK CryptoAPI documentation for details. It is possible to change the default access permissions for a key container. The crypt_get_security_descriptor and crypt_set_security_descriptor commands can be used retrieve and change the security descriptor for a key container.
Depending on the CSP chosen, key containers may be empty when created. The command crypt_generate_key adds randomly generated keys to the container. On the other hand, the command crypt_derive_key will add a key derived from a passphrase. In both cases, the algorithm with which the key will be used and the purpose (encryption, signing etc.) can be specified so the appropriate type of key is generated. The container may contain multiple keys and appropriate key must be chosen when cryptographic operations are invoked. A raw key of a specified number of bits derived from a passphrase can be generated using the pbkdf2 command.
The properties for a key may be retrieved or set using the commands in the table below. Note that a key is always associated with a specific cryptographic algorithm.
capi_key_algid | Numeric id for the associated algorithm. |
capi_key_blocklen | Block length for the encryption algorithm. |
capi_key_certificate | Associated certificate. |
capi_key_dss_p | Modulus prime number P if the key is a DSS key. |
capi_key_dss_q | Modulus prime number Q if the key is a DSS key. |
capi_key_dss_g | Generator G if the key is a DSS key. |
capi_key_effective_keylen | Effective key length of the key. |
capi_key_iv | Initialization vector. |
capi_key_keylen | Actual key length. |
capi_key_mode | Cipher mode, such as CBC, ECB etc. |
capi_key_mode_bits | Number of feedback bits for OFB and CFB modes. |
capi_key_padding | Padding method. |
capi_key_permissions | Operations that are permitted for the key. |
capi_key_salt | Salt value. |
Keys received from other applications can be imported into a cryptographic context with the crypt_import_key command. Conversely, a key that needs to be communicated to another application can be exported with the capi_key_export command. Public keys can be imported and exported in a portable format with crypt_public_key_import and crypt_public_key_export respectively. When importing and exporting keys, the keys are passed around as _key blobs_. The type and format of a key blob is specified by one of the values in the table below.
concealed | The returned key blob is in the format returned by the TWAPI conceal command. |
opaque | The returned key blob is in a format is a vendor-specific format that can only be used with the same CSP. |
plaintext | The returned key blob is a PLAINTEXTKEYBLOB blob. |
privatekey | The returned key blob is a PRIVATEKEYBLOB containing the public and private keys. If the -wrapper option is specified, it must be the handle to a symmetric key in which case the blob is encrypted with that key. |
publickey | The returned key blob is a PUBLICKEYBLOB containing the public key of a key pair. |
rfc3217 | The returned key blob is in the format specified by RFC3217. Both HKEY and the wrapping key specified by the -wrapper option must be symmetric keys. |
simple | The returned key blob is a SIMPLEBLOB where the symmetric key specified by HKEY is wrapped by a key exchange key specified with the -wrapper option. |
The details of the format of each of the above, except concealed which is TWAPI-specific, are described in the SDK documentation. In addition to capi_key_export, key blobs can be explicitly constructed with the capi_keyblob_create command. The commands capi_keyblob_plaintext and capi_keyblob_concealed are shortcuts for making key blobs in plaintext and concealed formats. Individual fields of a key blob can be retrieved through the commands capi_keyblob_version, capi_keyblob_type, capi_keyblob_algid and capi_keyblob_blob.
In order to perform cryptographic operations, an application must choose a CSP, the algorithms to use and their parameters including keys. The command crypt_acquire takes these are parameters and returns a handle to a cryptographic context that binds the desired combination together. This handle can then be used in further cryptographic operation.
Once a context is created, the various parameters associated with it can be retrieved.
crypt_algorithms | Returns the list of algorithms implemented in the context. |
crypt_csp | Returns the name of the owning CSP. |
crypt_csp_type | Returns the type of the CSP. |
crypt_csp_version | Returns the version of the owning CSP. |
crypt_keyx_keysize_increment | Returns the valid increments for the key exchange key sizes. |
crypt_implementation_type | Returns the implementation type (hardware, software etc.) of the context. |
crypt_key_container_name | Returns the name of key container currently associated with the context. |
crypt_key_container_names | Returns the names of the other key containers owned by the CSP. |
crypt_key_specifiers | Returns the key specifiers supported by the context. |
crypt_keypair | Returns a handle to one of the key pairs in the container. |
crypt_keyset_type | Returns whether the key set in the container is per-user or per-machine. |
crypt_session_key_size | Returns the size of the session key. |
crypt_sig_keysize_increment | Returns the valid increments for the signature key sizes. |
crypt_symmetric_key_size | Returns the size of the symmetric key. |
When no longer needed, cryptographic contexts must be freed with the crypt_free command.
CAPI internally uses numeric identifiers for cryptographic algorithms. Algorithms can also be identified by ASN.1 OID's. In addition, TWAPI uses allows use of mnemonics to identify algorithms as per the table below. The command capi_algid can be used to map any of the above forms to the numeric algorithm identifier. Most commands that need algorithm identifiers to be supplied will also accept any of the forms.
3des | Triple DES |
3des_112 | Triple DES with 112-bit effective key length |
aes | Advanced Encryption Standard (AES) |
aes_128 | 128-bit AES |
aes_192 | 192-bit AES |
aes_256 | 256-bit AES |
at_keyexchange | Maps to the key exchange algorithm for the CSP in use |
at_signature | Maps to the signature algorithm for the CSP in use |
des | Data Encryption Standard (DES) |
desx | DES-X |
dh_ephem | Diffie-Hellman ephemeral key exchange |
dh_sf | Diffie-Hellman store and forward key exchange |
dss_sign | DSA public key signature |
ecdh | Elliptic curve Diffie-Hellman key exchange |
ecdsa | Elliptic curve digital signature |
hash_replace_owf | One way function hashing |
hughes_md5 | Hughes MD5 |
hmac | HMAC keyed hash |
mac | MAC keyed hash |
md2 | MD2 hashing |
md4 | MD4 hashing |
md5 | MD5 hashing |
no_sign | No signature algorithm |
rc2 | RC2 block encryption |
rc4 | RC4 block encryption |
rc5 | RC5 block encryption |
rsa_keyx | RSA public key exchange |
rsa_sign | RSA public key signature |
sha | SHA hashing |
sha1 | SHA-1 hashing |
sha_256 | 256-bit SHA-2 |
sha_384 | 384-bit SHA-2 |
sha_512 | 512-bit SHA-2 |
Note that not all algorithms are supported on all platforms.
An ASN.1 object identifier (OID) is a dotted decimal string such as 1.2.3.4 that represents a ASN.1 class or attribute. Many CAPI command arguments use OID's to represent types and values such as algorithm identifiers. OID's can be passed in their dotted decimal form, or, for some commonly used ones, a mnemonic identifer. The list of mnemonic identifiers can be obtained through the oids command. Mapping to and from a specific mnemonic can be done through the oidname and oid commands. The utility commands asn1_encode_string and asn1_decode_string can be used to convert OID's to and from binary formats.
CAPI supports functionality related to generating cryptographic hashes and message authentication codes (MAC). The related TWAPI commands are shown below.
capi_hash_bytes | Incrementally hashes a binary string. |
capi_hash_create | Creates a hash context. |
capi_hash_dup | Duplicates a hash context. |
capi_hash_free | Frees a hash context. |
capi_hash_session_key | Incrementally hashes the secret session key. |
capi_hash_string | Incrementally hashes a string. |
capi_hash_value | Returns the hashed value. |
hmac | Calculates the HMAC hash using a specified PRF. |
md5 | Calculates the MD5 hash. |
sha1 | Calculates the SHA1 hash. |
sha256 | Calculates the SHA-256 hash. |
sha384 | Calculates the SHA-384 hash. |
sha512 | Calculates the SHA-512 hash. |
The package implements the following commands related to encryption and signatures.
3des | Encrypts, decrypts or generates an IV (3DES algorithm) |
aes_128 | Encrypts, decrypts or generates an IV (AES 128-bits algorithm) |
aes_192 | Encrypts, decrypts or generates an IV (AES 192-bits algorithm) |
aes_256 | Encrypts, decrypts or generates an IV (AES 256-bits algorithm) |
capi_encrypt_bytes | Encrypts a binary string with optional hashing. |
capi_encrypt_string | Encrypts a string with optional hashing. |
capi_decrypt_bytes | Decrypts a binary string with optional hashing. |
capi_decrypt_string | Decrypts a string with optional hashing. |
capi_hash_sign | Signs a hash using a private key. |
capi_hash_verify | Verifies the signature of a hash. |
des | Encrypts, decrypts or generates an IV (DES algorithm) |
Windows provides facilities to encrypt and protect data based on the user credentials such that it can only be retrieved on the same system with the same credentials. The protect_data and unprotect_data commands provide access to this facility. The TWAPI base module also provides the conceal/reveal commands to protect data within the current process. See the base module reference for details.
Cryptographic objects such as certificates, stores signed messages etc. may be of different formats and encodings. The command capi_parse analyses and parses a binary string containing a serialized cryptographic object, possibly of an unknown type. The command capi_parse_file is similar except it reads the serialized data directly from a file.
-iv IV | A binary string to be used as the initialization vector of the operation. |
-mode MODE | The cipher mode to be used for the operation. See capi_key_mode. |
-iv IV | A binary string to be used as the initialization vector of the operation. |
-mode MODE | The cipher mode to be used for the operation. See capi_key_mode. |
-nohashoid BOOLEAN | If true, the hash object OID is not placed in the RSA public key encryption. If false (default), the hash OID in the default signature is as specified in the definition of DigestInfo in PKCS #1. |
-nohashoid BOOLEAN | If true, the hash object OID is not expected to the present and is not checked. If false (default), the hash OID in the default signature is expected to be as specified in the definition of DigestInfo in PKCS #1. |
pkcs5 | Padding as specified by PKCS #5 |
random | Random bytes of padding. |
zeroes | Padding filled with zeroes. |
archive | Key can be exported only on the initial key creation. |
decrypt | Usable for decryption. |
encrypt | Usable for encryption. |
export | Key can be exported. |
export_key | Key can be used to encrypt other exported keys. |
import_key | Key can be used decrypt keys being imported. |
mac | Key can be used with message authentication codes. |
read | Allow key values to be read. |
write | Allow key values to be written. |
-contenttype CONTENTTYPE | Specifies the type of cryptographic object expected. See below for the possible values. If unspecified, or if CONTENTTYPE is any, the command will attempt to guess the type of content. Otherwise, it will raise an error if the content is not of the specified type. |
-format FORMAT | Specifies the format of the data. FORMAT must be on of the values binary, base64, asn1hex or any. If the option is unspecified or any, the command will attempt to guess the format. Otherwise, it will raise an error if the data format is not that specified. |
-typesonly | If specified as true, the actual content is not included in the returned dictionary. Only the information related to format and object type is returned. Defaults to false. |
formattype | The associated value is one of binary, base64 or asn1hex depending on the format of the data. |
contenttype | The associated value indicates the type of data that was parsed. The parsed data is stored in additional keys in the returned dictionary that depend on this type. This is discussed below. |
cert | The data is a certificate. The returned dictionary has two additional keys store and certificate that contain handles to a certificate store and certificate context. These must be released after use with cert_store_release and cert_release respectively. |
certpair | TBD. |
crl | The data is a CRL. The returned dictionary has two additional keys store and crl that contain handles to a certificate store and CRL context. These must be released after use with cert_store_release and crl_release respectively. |
ctl | The data is a CTL. The returned dictionary has two additional keys store and ctl that contain handles to a certificate store and CTL context. These must be released after use with cert_store_release and ctl_release respectively. |
pfx | The data is a PFX (PKCS#12) packet. No additional keys are returned in the dictionary. The application can use the cert_temporary_store command to import the PFX packet. |
pkcs10 | The data is a PKCS#10 message. |
pkcs7signed | The data is a PKCS#7 signed message. The returned dictionary has two additional keys store and message that contain handles to a certificate store and signed message. These must be released after use with cert_store_release and capi_msg_release respectively. |
pkcs7signedembed | The data is an embedded PKCS#7 signed message. The returned dictionary has two additional keys store and message that contain handles to a certificate store and signed message. These must be released after use with cert_store_release and capi_msg_release respectively. |
pkcs7unsigned | The data is a PKCS#7 unsigned message. The returned dictionary has an additional key, message that contains a handle to a signed message. This must be released with capi_msg_release. |
rsapublickey | The data is RSA public key encoded as defined by the ASN.1 RSAPublicKey definition in RFC3279. The returned dictionary has the key rsapublickey containing the key in an internal form. |
serializedcert | The data is a serialized certificate. The returned dictionary has two additional keys store and certificate that contain handles to a certificate store and certificate context. These must be released after use with cert_store_release and cert_release respectively. |
serializedcrl | The data is a serialized CRL. The returned dictionary has two additional keys store and crl that contain handles to a certificate store and CRL context. These must be released after use with cert_store_release and crl_release respectively. |
serializedctl | The data is a serialized CTL. The returned dictionary has two additional keys store and ctl that contain handles to a certificate store and CTL context. These must be released after use with cert_store_release and ctl_release respectively. |
serializedstore | The data is a serialized certificate store. The returned dictionary has an additional key store that contains a handle to a certificate store created from the data. This must be released after use with cert_store_release. |
subjectpublickeyinfo | The data is as per ASN.1 SubjectPublicKeyInfo definition in RFC3279. The returned dictionary has the key subjectpublickeyinfo containing the key in an internal form that can be passed to crypt_public_key_import. |
-create BOOLEAN | If specified as true, the key container is created if it does not exist. If false (default) an error is generated if the key container does not exist. |
-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. |
-keycontainer KEYCONTAINER | Specifies the name of the key container. If unspecified or an empty string, the default container for the CSP is used. |
-keysettype KEYSETTYPE | KEYSETTYPE must be user (default) or machine. Normally the key container is stored in the user's profile. If KEYSETTYPE is machine, the key container is treated as a computer container. This is needed when an application must access the keys from a process where the user profile is not loaded. |
-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. |
-verifycontext BOOLEAN | If specified as true, the context is intended for use for operations that are using ephemeral keys or which do not need access to private keys. Such operations include hashing, encrypting and signature verification. Operations involving decryption and signing require private keys and should set this option to false. The default for this option depends on whether a named key container is specified or not. If -keycontainer is not specified or is specified as an empty string denoting the default key container, this option defaults to true. Otherwise it defaults to false. Note that some CSP's (including Microsoft's) raise an error if the option is set to true for named containers. See the Microsoft knowledgebase article for more details. |
algid | The numeric algorithm identifier. |
defkeylen | The default length of a key. |
description | Description of the algorithm. |
minkeylen | Minimum length of a key. |
maxkeylen | Maximum length of a key. |
name | Name of the algorithm. |
protocols | Cryptographic protocols supported by the algorithm. This is a list containing zero or more elements from amongst ipsec, pct1, signing, ssl2, ssl3 and tls1. |
-exportable BOOLEAN | If true (default), the key can be exported later with capi_key_export. If false, the derived key can be used in cryptographic operations with the containing CSP but cannot be exported. |
-iterations NUMITERS | Number of iterations to execute if -method option is specified as pbkdf2. Ignored otherwise. Default is 100000. |
-method KEYDERIVATIONMETHOD | Specifies the method by which the key is derived from the pass phrase. See description below for details. |
-prf ALGID | Specifies the pseudo-random function (PRF) to use in the key derivation. If specified, ALGID must be sha1 (default) or sha_256. Ignored if -method is not pbkdf2. |
-salt BINSTRING | Specifies a binary string to use as the salt value if -method option is specified as pbkdf2. Ignored otherwise. |
-size KEYSIZE | Specifies the desired number of bits in the derived key. If unspecified or 0, the derived key size is based on the specified algorithm. |
der | DER encoded ASN.1 type SubjectPublicKeyInfo. |
pem | PEM encoded ASN.1 type SubjectPublicKeyInfo. |
native | Internal Tcl string format. |
-archivable BOOLEAN | If true, the key can be exported until its handle is freed after which it is no longer exportable. |
-exportable BOOLEAN | If true, the key is exportable. If false, session keys and private keys are not exportable. |
-pregen BOOLEAN | If true, specifies an initial Diffie-Hellman or DSS key generation. Not applicable for other algorithms. |
-userprotected BOOLEAN | If true, the user is notified by some CSP-specific means for some uses of the key. |
-size KEYSIZE | Specifies the key size to override the default key size. Since default key sizes are platform dependent, Microsoft recommends key size be explicitly set. |
-exportable BOOLEAN | If true (default), the imported key can be exported at a later time. If false the key cannot be exported although it can be used for cryptographic operations. |
-ipsechmac BOOLEAN | TBD |
-oaep BOOLEAN | TBD |
-userprotected BOOLEAN | If specified as true, the user is notified in a CSP-dependent manner whenever the key is used. Default is false. |
-wrapper HWRAPPER | If KEYBLOB was in an encrypted form, this option must be specified and HWRAPPER should be the handle to the key that can decrypt the key blob. |
-csp CSP | Specifies the name of the CSP for the key 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. |
-force | Must be specified when deleting the default container. |
-keysettype KEYSETTYPE | KEYSETTYPE must be user (default) or machine. Normally the key container is stored in the user's profile. If KEYSETTYPE is machine, the key container is treated as a computer container. |
-iv IV | A binary string to be used as the initialization vector of the operation. |
-mode MODE | The cipher mode to be used for the operation. See capi_key_mode. |
-certvar CERTVAR | If specified and CERTVAR is not the empty string, a handle to a certificate context for the certificate used for decryption is stored in the variable CERTVAR in the caller's context. This must be released later by calling cert_release. |
-encoding ENCODING | If unspecified or the empty string, the command attempts to determine the encoding itself. Otherwise, ENCODING must be der or pem depending on whether PKCS7MSG uses DER- or PEM-encoding. For performance reasons, the encoding should be explicitly specified when possible. |
-silent BOOL | If the decryption key is user protected, the user is notified when the key is used. If -silent is true, the user is not notified for such keys and the command returns an error instead. Default is false. |
-encoding ENCODING | Specifies the encoding in which the encoded message is returned. ENCODING may be der or pem (default) for DER- and PEM-encoding respectively. |
-detached BOOL | If false (default), the content BINDATA is included in the message. If true, the PKCS7 packet is constructed as a detached packet without the content. |
-encoding ENCODING | Specifies the encoding in which the encoded message is returned. ENCODING may be der or pem (default) for DER- and PEM-encoding respectively. |
-includecerts none|leaf|all | If unspecified or all, the signing certificate HCERT along with all certificates in its certificate chain are included in the PKCS7 message. If leaf, only the signing certificate is included and if none, no certificates are included in the message. |
-silent BOOL | If the signing key is user protected, the user is notified when the key is used for signing. If -silent is true, the user is not notified for such keys and the command returns an error instead. Default is false. |
-usersignerkeyid BOOL | By default or if false, the certificate issuer and serial number is used to identify the signer. If this option is true, the key identifier is used for this purpose instead. |
-certvar CERTVAR | If specified and CERTVAR is not the empty string, a handle to a certificate context for the signing certificate is stored in the variable CERTVAR in the caller's context. This must be released later by calling cert_release. |
-contentvar CONTENTVAR | If specified and CONTENTVAR is not the empty string, the content of the message is stored in the variable CONTENTVAR in the caller's context. |
-encoding ENCODING | If unspecified or the empty string, the command attempts to determine the encoding itself. Otherwise, ENCODING must be der or pem depending on whether PKCS7MSG uses DER- or PEM-encoding. For performance reasons, the encoding should be explicitly specified when possible. |
-audit BOOLEAN | If true, an audit event is generated. Default is false. |
-description DESCRIPTION | A descriptive string that is stored with the encrypted data. |
-hwnd HWND | The handle to the parent window if a dialog is to be shown to the user. |
-localmachine BOOLEAN | If false (default), only the same user can decrypt the data. If true, any user on the same machine can do the decryption. |
-noui BOOLEAN | If true, the operation fails if any user dialog is required to be shown. Default is false. |
-prompt PROMPTSTRING | If specified, the user is shown a dialog with the specified PROMPTSTRING to set the security level of the encrypted data. The user will also be prompted at the time the data is decrypted. |
-withdescription BOOLEAN | By default the command returns just the decrypted data. If specified as true, the command returns a list of two elements - the decrypted data and a descriptive string that is stored with the encrypted data. |
-hwnd HWND | The handle to the parent window if a dialog is to be shown to the user. |
-noui BOOLEAN | If true, the operation fails if any user dialog is required to be shown. Default is false. |
-prompt PROMPTSTRING | If specified, the user is shown a dialog with the specified PROMPTSTRING. |
Copyright © 2007-2016 Ashok P. Nadkarni