using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Vanara.Extensions;
using Vanara.InteropServices;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace Vanara.PInvoke
{
/// Methods and data types found in Crypt32.dll.
public static partial class Crypt32
{
private const int CERT_COMPARE_SHIFT = 16;
///
public const uint CERT_V1 = 0;
///
public const uint CERT_V2 = 1;
///
public const uint CERT_V3 = 2;
/// The class of an ALG_ID.
[PInvokeData("wincrypt.h")]
public enum ALG_CLASS
{
///
ALG_CLASS_ANY = (0),
///
ALG_CLASS_SIGNATURE = (1 << 13),
///
ALG_CLASS_MSG_ENCRYPT = (2 << 13),
///
ALG_CLASS_DATA_ENCRYPT = (3 << 13),
///
ALG_CLASS_HASH = (4 << 13),
///
ALG_CLASS_KEY_EXCHANGE = (5 << 13),
///
ALG_CLASS_ALL = (7 << 13),
}
///
/// The ALG_ID data type specifies an algorithm identifier. Parameters of this data type are passed to most of the functions in CryptoAPI.
///
public enum ALG_ID : uint
{
/// Triple DES encryption algorithm.
CALG_3DES = 0x00006603,
/// Two-key triple DES encryption with effective key length equal to 112 bits.
CALG_3DES_112 = 0x00006609,
/// Advanced Encryption Standard (AES). This algorithm is supported by the Microsoft AES Cryptographic Provider.
CALG_AES = 0x00006611,
/// 128 bit AES. This algorithm is supported by the Microsoft AES Cryptographic Provider.
CALG_AES_128 = 0x0000660e,
/// 192 bit AES. This algorithm is supported by the Microsoft AES Cryptographic Provider.
CALG_AES_192 = 0x0000660f,
/// 256 bit AES. This algorithm is supported by the Microsoft AES Cryptographic Provider.
CALG_AES_256 = 0x00006610,
/// Temporary algorithm identifier for handles of Diffie-Hellman–agreed keys.
CALG_AGREEDKEY_ANY = 0x0000aa03,
///
/// An algorithm to create a 40-bit DES key that has parity bits and zeroed key bits to make its key length 64 bits. This
/// algorithm is supported by the Microsoft Base Cryptographic Provider.
///
CALG_CYLINK_MEK = 0x0000660c,
/// DES encryption algorithm.
CALG_DES = 0x00006601,
/// DESX encryption algorithm.
CALG_DESX = 0x00006604,
/// Diffie-Hellman ephemeral key exchange algorithm.
CALG_DH_EPHEM = 0x0000aa02,
/// Diffie-Hellman store and forward key exchange algorithm.
CALG_DH_SF = 0x0000aa01,
/// DSA public key signature algorithm.
CALG_DSS_SIGN = 0x00002200,
///
/// Elliptic curve Diffie-Hellman key exchange algorithm.
/// [!Note]
/// This algorithm is supported only through Cryptography API: Next Generation.
/// Windows Server 2003 and Windows XP: This algorithm is not supported.
///
CALG_ECDH = 0x0000aa05,
///
/// Ephemeral elliptic curve Diffie-Hellman key exchange algorithm.
/// [!Note]
/// This algorithm is supported only through Cryptography API: Next Generation.
/// Windows Server 2003 and Windows XP: This algorithm is not supported.
///
CALG_ECDH_EPHEM = 0x0000ae06,
///
/// Elliptic curve digital signature algorithm.
/// [!Note]
/// This algorithm is supported only through Cryptography API: Next Generation.
/// Windows Server 2003 and Windows XP: This algorithm is not supported.
///
CALG_ECDSA = 0x00002203,
/// Elliptic curve Menezes, Qu, and Vanstone (MQV) key exchange algorithm. This algorithm is not supported.
CALG_ECMQV = 0x0000a001,
/// One way function hashing algorithm.
CALG_HASH_REPLACE_OWF = 0x0000800b,
/// Hughes MD5 hashing algorithm.
CALG_HUGHES_MD5 = 0x0000a003,
/// HMAC keyed hash algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_HMAC = 0x00008009,
/// KEA key exchange algorithm (FORTEZZA). This algorithm is not supported.
CALG_KEA_KEYX = 0x0000aa04,
/// MAC keyed hash algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_MAC = 0x00008005,
/// MD2 hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_MD2 = 0x00008001,
/// MD4 hashing algorithm.
CALG_MD4 = 0x00008002,
/// MD5 hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_MD5 = 0x00008003,
/// No signature algorithm.
CALG_NO_SIGN = 0x00002000,
///
/// The algorithm is only implemented in CNG. The macro, IS_SPECIAL_OID_INFO_ALGID, can be used to determine whether a
/// cryptography algorithm is only supported by using the CNG functions.
///
CALG_OID_INFO_CNG_ONLY = 0xffffffff,
///
/// The algorithm is defined in the encoded parameters. The algorithm is only supported by using CNG. The macro,
/// IS_SPECIAL_OID_INFO_ALGID, can be used to determine whether a cryptography algorithm is only supported by using the CNG functions.
///
CALG_OID_INFO_PARAMETERS = 0xfffffffe,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_PCT1_MASTER = 0x00004c04,
/// RC2 block encryption algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_RC2 = 0x00006602,
/// RC4 stream encryption algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_RC4 = 0x00006801,
/// RC5 block encryption algorithm.
CALG_RC5 = 0x0000660d,
/// RSA public key exchange algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_RSA_KEYX = 0x0000a400,
/// RSA public key signature algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_RSA_SIGN = 0x00002400,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_SCHANNEL_ENC_KEY = 0x00004c07,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_SCHANNEL_MAC_KEY = 0x00004c03,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_SCHANNEL_MASTER_HASH = 0x00004c02,
/// SEAL encryption algorithm. This algorithm is not supported.
CALG_SEAL = 0x00006802,
/// SHA hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_SHA = 0x00008004,
/// Same as CALG_SHA. This algorithm is supported by the Microsoft Base Cryptographic Provider.
CALG_SHA1 = 0x00008004,
///
/// 256 bit SHA hashing algorithm. This algorithm is supported by Microsoft Enhanced RSA and AES Cryptographic Provider..Windows
/// XP with SP3: This algorithm is supported by the Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype).
/// Windows XP with SP2, Windows XP with SP1 and Windows XP: This algorithm is not supported.
///
CALG_SHA_256 = 0x0000800c,
///
/// 384 bit SHA hashing algorithm. This algorithm is supported by Microsoft Enhanced RSA and AES Cryptographic Provider.Windows
/// XP with SP3: This algorithm is supported by the Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype).
/// Windows XP with SP2, Windows XP with SP1 and Windows XP: This algorithm is not supported.
///
CALG_SHA_384 = 0x0000800d,
///
/// 512 bit SHA hashing algorithm. This algorithm is supported by Microsoft Enhanced RSA and AES Cryptographic Provider.Windows
/// XP with SP3: This algorithm is supported by the Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype).
/// Windows XP with SP2, Windows XP with SP1 and Windows XP: This algorithm is not supported.
///
CALG_SHA_512 = 0x0000800e,
/// Skipjack block encryption algorithm (FORTEZZA). This algorithm is not supported.
CALG_SKIPJACK = 0x0000660a,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_SSL2_MASTER = 0x00004c05,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_SSL3_MASTER = 0x00004c01,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_SSL3_SHAMD5 = 0x00008008,
/// TEK (FORTEZZA). This algorithm is not supported.
CALG_TEK = 0x0000660b,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_TLS1_MASTER = 0x00004c06,
/// Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
CALG_TLS1PRF = 0x0000800a,
}
/// The type of an ALG_ID.
[PInvokeData("wincrypt.h")]
public enum ALG_TYPE
{
///
ALG_TYPE_ANY = (0),
///
ALG_TYPE_DSS = (1 << 9),
///
ALG_TYPE_RSA = (2 << 9),
///
ALG_TYPE_BLOCK = (3 << 9),
///
ALG_TYPE_STREAM = (4 << 9),
///
ALG_TYPE_DH = (5 << 9),
///
ALG_TYPE_SECURECHANNEL = (6 << 9),
///
ALG_TYPE_ECDH = (7 << 9),
///
ALG_TYPE_THIRDPARTY = (8 << 9),
}
/// Indicates which nested union member of CERT_STRONG_SIGN_PARA points to the strong signature information.
public enum CERT_INFO_CHOICE : uint
{
/// Specifies the pSerializedInfo member of CERT_STRONG_SIGN_PARA.
CERT_STRONG_SIGN_SERIALIZED_INFO_CHOICE = 1,
/// Specifies the pszOID member of CERT_STRONG_SIGN_PARA.
CERT_STRONG_SIGN_OID_INFO_CHOICE = 2,
}
/// Values used by CertFindType.
public enum CertCompareFunction : ushort
{
/// No search criteria used. Returns the next certificate in the store.
CERT_COMPARE_ANY = 0,
/// Searches for a certificate with a SHA1 hash that matches the hash in the CRYPT_HASH_BLOB structure.
CERT_COMPARE_SHA1_HASH = 1,
///
/// Searches for a certificate with an exact match of the entire subject name with the name in the CERT_NAME_BLOB structure. The
/// search is restricted to certificates that match the value of dwCertEncodingType.
///
CERT_COMPARE_NAME = 2,
///
/// Searches for a certificate with specified subject attributes that match attributes in the CERT_RDN structure. If RDN values
/// are set, the function compares attributes of the subject in a certificate with elements of the CERT_RDN_ATTR array in this
/// CERT_RDN structure. Comparisons iterate through the CERT_RDN_ATTR attributes looking for a match with the certificate's
/// subject's attributes.
/// If the pszObjId member of CERT_RDN_ATTR is NULL, the attribute object identifier is ignored.
/// If the dwValueType member of CERT_RDN_ATTR is CERT_RDN_ANY_TYPE, the value type is ignored.
/// If the pbData member of CERT_RDN_VALUE_BLOB is NULL, any value is a match.
/// Currently only an exact, case-sensitive match is supported.
///
/// For information about Unicode options, see Remarks. When these values are set, the search is restricted to certificates
/// whose encoding type matches dwCertEncodingType.
///
///
CERT_COMPARE_ATTR = 3,
/// Searches for a certificate with an MD5 hash that matches the hash in CRYPT_HASH_BLOB.
CERT_COMPARE_MD5_HASH = 4,
///
/// Searches for a certificate with a property that matches the property identifier specified by the DWORD value in pvFindPara.
///
CERT_COMPARE_PROPERTY = 5,
/// Searches for a certificate with a public key that matches the public key in the CERT_PUBLIC_KEY_INFO structure.
CERT_COMPARE_PUBLIC_KEY = 6,
/// Searches for a certificate with a SHA1 hash that matches the hash in the CRYPT_HASH_BLOB structure.
CERT_COMPARE_HASH = CERT_COMPARE_SHA1_HASH,
///
/// Searches for a certificate that contains the specified subject name string. The certificate's subject member is converted to
/// a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a
/// case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to
/// certificates whose encoding type matches dwCertEncodingType.
///
CERT_COMPARE_NAME_STR_A = 7,
///
/// Searches for a certificate that contains the specified subject name string. The certificate's subject member is converted to
/// a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a
/// case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to
/// certificates whose encoding type matches dwCertEncodingType.
///
CERT_COMPARE_NAME_STR_W = 8,
/// Searches for a certificate that has a CERT_KEY_SPEC_PROP_ID property that matches the key specification in pvFindPara.
CERT_COMPARE_KEY_SPEC = 9,
///
/// Searches for a certificate in the store that has either an enhanced key usage extension or an enhanced key usage property
/// and a usage identifier that matches the cUsageIdentifier member in the CERT_ENHKEY_USAGE structure.
///
/// A certificate has an enhanced key usage extension if it has a CERT_EXTENSION structure with the pszObjId member set to szOID_ENHANCED_KEY_USAGE.
///
/// A certificate has an enhanced key usage property if its CERT_ENHKEY_USAGE_PROP_ID identifier is set.
///
/// If CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG is set in dwFindFlags, certificates without the key usage extension or property are
/// also matches. Setting this flag takes precedence over passing NULL in pvFindPara.
///
/// If CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG is set, a match is done only on the key usage extension.
///
CERT_COMPARE_ENHKEY_USAGE = 10,
///
/// Searches for a certificate in the store that has either an enhanced key usage extension or an enhanced key usage property
/// and a usage identifier that matches the cUsageIdentifier member in the CERT_ENHKEY_USAGE structure.
///
/// A certificate has an enhanced key usage extension if it has a CERT_EXTENSION structure with the pszObjId member set to szOID_ENHANCED_KEY_USAGE.
///
/// A certificate has an enhanced key usage property if its CERT_ENHKEY_USAGE_PROP_ID identifier is set.
///
/// If CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG is set in dwFindFlags, certificates without the key usage extension or property are
/// also matches. Setting this flag takes precedence over passing NULL in pvFindPara.
///
/// If CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG is set, a match is done only on the key usage extension.
///
CERT_COMPARE_CTL_USAGE = CERT_COMPARE_ENHKEY_USAGE,
///
/// Searches for a certificate with both an issuer and a serial number that match the issuer and serial number in the CERT_INFO structure.
///
CERT_COMPARE_SUBJECT_CERT = 11,
///
/// Searches for a certificate with an subject that matches the issuer [In] PCCERT_CONTEXT. Instead of using
/// CertFindCertificateInStore with this value, use the CertGetCertificateChain function.
///
CERT_COMPARE_ISSUER_OF = 12,
/// Searches for a certificate that is an exact match of the specified certificate context.
CERT_COMPARE_EXISTING = 13,
/// Searches for a certificate with a signature hash that matches the signature hash in the CRYPT_HASH_BLOB structure.
CERT_COMPARE_SIGNATURE_HASH = 14,
/// Searches for a certificate with a CERT_KEY_IDENTIFIER_PROP_ID property that matches the key identifier in CRYPT_HASH_BLOB.
CERT_COMPARE_KEY_IDENTIFIER = 15,
/// Find the certificate identified by the specified CERT_ID.
CERT_COMPARE_CERT_ID = 16,
/// Find a certificate that has either a cross certificate distribution point extension or property.
CERT_COMPARE_CROSS_CERT_DIST_POINTS = 17,
/// Find a certificate whose MD5-hashed public key matches the specified hash.
CERT_COMPARE_PUBKEY_MD5_HASH = 18,
///
CERT_COMPARE_SUBJECT_INFO_ACCESS = 19,
///
CERT_COMPARE_HASH_STR = 20,
///
/// Searches for a certificate that has a private key. The key can be ephemeral or saved on disk. The key can be a legacy
/// Cryptography API (CAPI) key or a CNG key.
///
CERT_COMPARE_HAS_PRIVATE_KEY = 21,
}
/// A certificate encoding type.
[PInvokeData("wincrypt.h")]
public enum CertEncodingType : uint
{
///
CRYPT_ASN_ENCODING = 0x00000001,
///
CRYPT_NDR_ENCODING = 0x00000002,
///
X509_ASN_ENCODING = 0x00000001,
///
X509_NDR_ENCODING = 0x00000002,
///
PKCS_7_ASN_ENCODING = 0x00010000,
///
PKCS_7_NDR_ENCODING = 0x00020000
}
/// Values used by .
[PInvokeData("wincrypt.h", MSDNShortId = "20b3fcfb-55df-46ff-80a5-70f31a3d03b2")]
public enum CertFindType : uint
{
/// No search criteria used. Returns the next certificate in the store.
CERT_FIND_ANY = (uint)CertCompareFunction.CERT_COMPARE_ANY << CERT_COMPARE_SHIFT,
/// Searches for a certificate with a SHA1 hash that matches the hash in the CRYPT_HASH_BLOB structure.
[CorrespondingType(typeof(CRYPTOAPI_BLOB))]
CERT_FIND_SHA1_HASH = (uint)CertCompareFunction.CERT_COMPARE_SHA1_HASH << CERT_COMPARE_SHIFT,
/// Searches for a certificate with an MD5 hash that matches the hash in CRYPT_HASH_BLOB.
[CorrespondingType(typeof(CRYPTOAPI_BLOB))]
CERT_FIND_MD5_HASH = (uint)CertCompareFunction.CERT_COMPARE_MD5_HASH << CERT_COMPARE_SHIFT,
/// Searches for a certificate with a signature hash that matches the signature hash in the CRYPT_HASH_BLOB structure.
[CorrespondingType(typeof(CRYPTOAPI_BLOB))]
CERT_FIND_SIGNATURE_HASH = (uint)CertCompareFunction.CERT_COMPARE_SIGNATURE_HASH << CERT_COMPARE_SHIFT,
/// Searches for a certificate with a CERT_KEY_IDENTIFIER_PROP_ID property that matches the key identifier in CRYPT_HASH_BLOB.
[CorrespondingType(typeof(CRYPTOAPI_BLOB))]
CERT_FIND_KEY_IDENTIFIER = (uint)CertCompareFunction.CERT_COMPARE_KEY_IDENTIFIER << CERT_COMPARE_SHIFT,
/// Searches for a certificate with a SHA1 hash that matches the hash in the CRYPT_HASH_BLOB structure.
[CorrespondingType(typeof(CRYPTOAPI_BLOB))]
CERT_FIND_HASH = CERT_FIND_SHA1_HASH,
///
/// Searches for a certificate with a property that matches the property identifier specified by the DWORD value in pvFindPara.
///
[CorrespondingType(typeof(uint))]
CERT_FIND_PROPERTY = (uint)CertCompareFunction.CERT_COMPARE_PROPERTY << CERT_COMPARE_SHIFT,
/// Searches for a certificate with a public key that matches the public key in the CERT_PUBLIC_KEY_INFO structure.
[CorrespondingType(typeof(CERT_PUBLIC_KEY_INFO))]
CERT_FIND_PUBLIC_KEY = (uint)CertCompareFunction.CERT_COMPARE_PUBLIC_KEY << CERT_COMPARE_SHIFT,
///
/// Searches for a certificate with an exact match of the entire subject name with the name in the CERT_NAME_BLOB structure. The
/// search is restricted to certificates that match the value of dwCertEncodingType.
///
[CorrespondingType(typeof(CRYPTOAPI_BLOB))]
CERT_FIND_SUBJECT_NAME = (uint)CertCompareFunction.CERT_COMPARE_NAME << CERT_COMPARE_SHIFT | CertInfoFlags.CERT_INFO_SUBJECT_FLAG,
///
/// Searches for a certificate with specified subject attributes that match attributes in the CERT_RDN structure. If RDN values
/// are set, the function compares attributes of the subject in a certificate with elements of the CERT_RDN_ATTR array in this
/// CERT_RDN structure. Comparisons iterate through the CERT_RDN_ATTR attributes looking for a match with the certificate's
/// subject's attributes.
/// If the pszObjId member of CERT_RDN_ATTR is NULL, the attribute object identifier is ignored.
/// If the dwValueType member of CERT_RDN_ATTR is CERT_RDN_ANY_TYPE, the value type is ignored.
/// If the pbData member of CERT_RDN_VALUE_BLOB is NULL, any value is a match.
/// Currently only an exact, case-sensitive match is supported.
///
/// For information about Unicode options, see Remarks. When these values are set, the search is restricted to certificates
/// whose encoding type matches dwCertEncodingType.
///
///
[CorrespondingType(typeof(CERT_RDN))]
CERT_FIND_SUBJECT_ATTR = (uint)CertCompareFunction.CERT_COMPARE_ATTR << CERT_COMPARE_SHIFT | CertInfoFlags.CERT_INFO_SUBJECT_FLAG,
///
/// Search for a certificate with an exact match of the entire issuer name with the name in CERT_NAME_BLOB The search is
/// restricted to certificates that match the dwCertEncodingType.
///
[CorrespondingType(typeof(CRYPTOAPI_BLOB))]
CERT_FIND_ISSUER_NAME = (uint)CertCompareFunction.CERT_COMPARE_NAME << CERT_COMPARE_SHIFT | CertInfoFlags.CERT_INFO_ISSUER_FLAG,
///
/// Searches for a certificate with specified issuer attributes that match attributes in the CERT_RDN structure. If these values
/// are set, the function compares attributes of the issuer in a certificate with elements of the CERT_RDN_ATTR array in this
/// CERT_RDN structure. Comparisons iterate through the CERT_RDN_ATTR attributes looking for a match with the certificate's
/// issuer attributes.
/// If the pszObjId member of CERT_RDN_ATTR is NULL, the attribute object identifier is ignored.
/// If the dwValueType member of CERT_RDN_ATTR is CERT_RDN_ANY_TYPE, the value type is ignored.
/// If the pbData member of CERT_RDN_VALUE_BLOB is NULL, any value is a match.
///
/// Currently only an exact, case-sensitive match is supported.For information about Unicode options, see Remarks. When these
/// values are set, the search is restricted to certificates whose encoding type matches dwCertEncodingType.
///
///
[CorrespondingType(typeof(CERT_RDN))]
CERT_FIND_ISSUER_ATTR = (uint)CertCompareFunction.CERT_COMPARE_ATTR << CERT_COMPARE_SHIFT | CertInfoFlags.CERT_INFO_ISSUER_FLAG,
///
/// Searches for a certificate that contains the specified subject name string. The certificate's subject member is converted to
/// a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a
/// case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to
/// certificates whose encoding type matches dwCertEncodingType.
///
[CorrespondingType(typeof(string))]
CERT_FIND_SUBJECT_STR_A = (uint)CertCompareFunction.CERT_COMPARE_NAME_STR_A << CERT_COMPARE_SHIFT | CertInfoFlags.CERT_INFO_SUBJECT_FLAG,
///
/// Searches for a certificate that contains the specified subject name string. The certificate's subject member is converted to
/// a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a
/// case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to
/// certificates whose encoding type matches dwCertEncodingType.
///
[CorrespondingType(typeof(string))]
CERT_FIND_SUBJECT_STR_W = (uint)CertCompareFunction.CERT_COMPARE_NAME_STR_W << CERT_COMPARE_SHIFT | CertInfoFlags.CERT_INFO_SUBJECT_FLAG,
///
/// Searches for a certificate that contains the specified subject name string. The certificate's subject member is converted to
/// a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a
/// case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to
/// certificates whose encoding type matches dwCertEncodingType.
///
[CorrespondingType(typeof(string))]
CERT_FIND_SUBJECT_STR = CERT_FIND_SUBJECT_STR_W,
///
/// Searches for a certificate that contains the specified subject name string. The certificate's subject member is converted to
/// a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a
/// case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to
/// certificates whose encoding type matches dwCertEncodingType.
///
[CorrespondingType(typeof(string))]
CERT_FIND_ISSUER_STR_A = (uint)CertCompareFunction.CERT_COMPARE_NAME_STR_A << CERT_COMPARE_SHIFT | CertInfoFlags.CERT_INFO_ISSUER_FLAG,
///
/// Searches for a certificate that contains the specified subject name string. The certificate's subject member is converted to
/// a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a
/// case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to
/// certificates whose encoding type matches dwCertEncodingType.
///
[CorrespondingType(typeof(string))]
CERT_FIND_ISSUER_STR_W = (uint)CertCompareFunction.CERT_COMPARE_NAME_STR_W << CERT_COMPARE_SHIFT | CertInfoFlags.CERT_INFO_ISSUER_FLAG,
///
/// Searches for a certificate that contains the specified issuer name string. The certificate's issuer member is converted to a
/// name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a
/// case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to
/// certificates whose encoding type matches dwCertEncodingType.
///
/// If the substring match fails and the subject contains an email RDN with Punycode encoded string,
/// CERT_NAME_STR_ENABLE_PUNYCODE_FLAG is used to convert the subject to a Unicode string and the substring match is performed again.
///
///
[CorrespondingType(typeof(string))]
CERT_FIND_ISSUER_STR = CERT_FIND_ISSUER_STR_W,
/// Searches for a certificate that has a CERT_KEY_SPEC_PROP_ID property that matches the key specification in pvFindPara.
[CorrespondingType(typeof(uint))]
CERT_FIND_KEY_SPEC = (uint)CertCompareFunction.CERT_COMPARE_KEY_SPEC << CERT_COMPARE_SHIFT,
///
/// Searches for a certificate in the store that has either an enhanced key usage extension or an enhanced key usage property
/// and a usage identifier that matches the cUsageIdentifier member in the CERT_ENHKEY_USAGE structure.
///
/// A certificate has an enhanced key usage extension if it has a CERT_EXTENSION structure with the pszObjId member set to szOID_ENHANCED_KEY_USAGE.
///
/// A certificate has an enhanced key usage property if its CERT_ENHKEY_USAGE_PROP_ID identifier is set.
///
/// If CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG is set in dwFindFlags, certificates without the key usage extension or property are
/// also matches. Setting this flag takes precedence over passing NULL in pvFindPara.
///
/// If CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG is set, a match is done only on the key usage extension.
///
[CorrespondingType(typeof(CTL_USAGE))]
CERT_FIND_ENHKEY_USAGE = (uint)CertCompareFunction.CERT_COMPARE_ENHKEY_USAGE << CERT_COMPARE_SHIFT,
///
/// Searches for a certificate that has a szOID_ENHANCED_KEY_USAGE extension or a CERT_CTL_PROP_ID that matches the
/// pszUsageIdentifier member of the CTL_USAGE structure.
///
[CorrespondingType(typeof(CTL_USAGE))]
CERT_FIND_CTL_USAGE = CERT_FIND_ENHKEY_USAGE,
///
/// Searches for a certificate with both an issuer and a serial number that match the issuer and serial number in the CERT_INFO structure.
///
[CorrespondingType(typeof(CERT_INFO))]
CERT_FIND_SUBJECT_CERT = (uint)CertCompareFunction.CERT_COMPARE_SUBJECT_CERT << CERT_COMPARE_SHIFT,
///
/// Searches for a certificate with an subject that matches the issuer [In] PCCERT_CONTEXT. Instead of using
/// CertFindCertificateInStore with this value, use the CertGetCertificateChain function.
///
[CorrespondingType(typeof(CERT_CONTEXT))]
CERT_FIND_ISSUER_OF = (uint)CertCompareFunction.CERT_COMPARE_ISSUER_OF << CERT_COMPARE_SHIFT,
/// Searches for a certificate that is an exact match of the specified certificate context.
[CorrespondingType(typeof(CERT_CONTEXT))]
CERT_FIND_EXISTING = (uint)CertCompareFunction.CERT_COMPARE_EXISTING << CERT_COMPARE_SHIFT,
/// Find the certificate identified by the specified CERT_ID.
[CorrespondingType(typeof(CERT_ID))]
CERT_FIND_CERT_ID = (uint)CertCompareFunction.CERT_COMPARE_CERT_ID << CERT_COMPARE_SHIFT,
/// Find a certificate that has either a cross certificate distribution point extension or property.
CERT_FIND_CROSS_CERT_DIST_POINTS = (uint)CertCompareFunction.CERT_COMPARE_CROSS_CERT_DIST_POINTS << CERT_COMPARE_SHIFT,
/// Find a certificate whose MD5-hashed public key matches the specified hash.
CERT_FIND_PUBKEY_MD5_HASH = (uint)CertCompareFunction.CERT_COMPARE_PUBKEY_MD5_HASH << CERT_COMPARE_SHIFT,
///
CERT_FIND_SUBJECT_INFO_ACCESS = (uint)CertCompareFunction.CERT_COMPARE_SUBJECT_INFO_ACCESS << CERT_COMPARE_SHIFT,
///
CERT_FIND_HASH_STR = (uint)CertCompareFunction.CERT_COMPARE_HASH_STR << CERT_COMPARE_SHIFT,
///
/// Searches for a certificate that has a private key. The key can be ephemeral or saved on disk. The key can be a legacy
/// Cryptography API (CAPI) key or a CNG key.
///
CERT_FIND_HAS_PRIVATE_KEY = (uint)CertCompareFunction.CERT_COMPARE_HAS_PRIVATE_KEY << CERT_COMPARE_SHIFT
}
/// Flags used by .
public enum CertInfoFlags : uint
{
/// Gets the version.
CERT_INFO_VERSION_FLAG = 1,
/// Gets the serial number.
CERT_INFO_SERIAL_NUMBER_FLAG = 2,
/// Gets the signature.
CERT_INFO_SIGNATURE_ALGORITHM_FLAG = 3,
/// Gets the issuer.
CERT_INFO_ISSUER_FLAG = 4,
/// Gets values before.
CERT_INFO_NOT_BEFORE_FLAG = 5,
/// Gets values after.
CERT_INFO_NOT_AFTER_FLAG = 6,
/// Gets the subject.
CERT_INFO_SUBJECT_FLAG = 7,
/// Gets the subject's public key.
CERT_INFO_SUBJECT_PUBLIC_KEY_INFO_FLAG = 8,
/// Gets the issuer's UID.
CERT_INFO_ISSUER_UNIQUE_ID_FLAG = 9,
/// Gets the subject's UID.
CERT_INFO_SUBJECT_UNIQUE_ID_FLAG = 10,
/// Gets the extended info.
CERT_INFO_EXTENSION_FLAG = 11,
}
/// The specification of the private key to retrieve.
public enum CertKeySpec : uint
{
/// Keys used to encrypt/decrypt session keys. The handle to the CSP is contained in the hCryptProv member.
AT_KEYEXCHANGE = 1,
/// Keys used to create and verify digital signatures. The handle to the CSP is contained in the hCryptProv member.
AT_SIGNATURE = 2,
///
/// Keys associated with a CNG CSP. The handle to the CNG CSP is set in the hNCryptProv member. Windows Server 2003 and Windows
/// XP: This value is not used.
///
CERT_NCRYPT_KEY_SPEC = 0xFFFFFFFF
}
/// A set of flags that modify the behavior of .
[PInvokeData("wincrypt.h", MSDNShortId = "53c9aec9-701d-4c21-9814-d344a8dde0c1")]
[Flags]
public enum CryptAcquireFlags
{
///
/// If a handle is already acquired and cached, that same handle is returned. Otherwise, a new handle is acquired and cached by
/// using the certificate's CERT_KEY_CONTEXT_PROP_ID property.
///
/// When this flag is set, the pfCallerFreeProvOrNCryptKey parameter receives FALSE and the calling application must not release
/// the handle. The handle is freed when the certificate context is freed; however, you must retain the certificate context
/// referenced by the pCert parameter as long as the key is in use, otherwise operations that rely on the key will fail.
///
///
CRYPT_ACQUIRE_CACHE_FLAG = 0x00000001,
///
/// Uses the certificate's CERT_KEY_PROV_INFO_PROP_ID property to determine whether caching should be accomplished. For more
/// information about the CERT_KEY_PROV_INFO_PROP_ID property, see CertSetCertificateContextProperty.
///
/// This function will only use caching if during a previous call, the dwFlags member of the CRYPT_KEY_PROV_INFO structure
/// contained CERT_SET_KEY_CONTEXT_PROP.
///
///
CRYPT_ACQUIRE_USE_PROV_INFO_FLAG = 0x00000002,
///
/// The public key in the certificate is compared with the public key returned by the cryptographic service provider (CSP). If
/// the keys do not match, the acquisition operation fails and the last error code is set to NTE_BAD_PUBLIC_KEY. If a cached
/// handle is returned, no comparison is made.
///
CRYPT_ACQUIRE_COMPARE_KEY_FLAG = 0x00000004,
///
/// This function will not attempt to re-create the CERT_KEY_PROV_INFO_PROP_ID property in the certificate context if this
/// property cannot be retrieved.
///
CRYPT_ACQUIRE_NO_HEALING = 0x00000008,
///
/// The CSP should not display any user interface (UI) for this context. If the CSP must display UI to operate, the call fails
/// and the NTE_SILENT_CONTEXT error code is set as the last error.
///
CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040,
///
/// Any UI that is needed by the CSP or KSP will be a child of the HWND that is supplied in the pvParameters parameter. For a
/// CSP key, using this flag will cause the CryptSetProvParam function with the flag PP_CLIENT_HWND using this HWND to be called
/// with NULL for HCRYPTPROV. For a KSP key, using this flag will cause the NCryptSetProperty function with the
/// NCRYPT_WINDOW_HANDLE_PROPERTY flag to be called using the HWND.
/// Do not use this flag with CRYPT_ACQUIRE_SILENT_FLAG.
///
CRYPT_ACQUIRE_WINDOW_HANDLE_FLAG = 0x00000080,
///
CRYPT_ACQUIRE_NCRYPT_KEY_FLAGS_MASK = 0x00070000,
///
/// This function will attempt to obtain the key by using CryptoAPI. If that fails, this function will attempt to obtain the key
/// by using the Cryptography API: Next Generation (CNG).
/// The pdwKeySpec variable receives the CERT_NCRYPT_KEY_SPEC flag if CNG is used to obtain the key.
///
CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG = 0x00010000,
///
/// This function will attempt to obtain the key by using CNG. If that fails, this function will attempt to obtain the key by
/// using CryptoAPI.
/// The pdwKeySpec variable receives the CERT_NCRYPT_KEY_SPEC flag if CNG is used to obtain the key.
/// CryptoAPI does not support the CNG Diffie-Hellman or DSA asymmetric algorithms. CryptoAPI only supports Diffie-Hellman
/// and DSA public keys through the legacy CSPs.If this flag is set for a certificate that contains a Diffie-Hellman or DSA
/// public key, this function will implicitly change this flag to CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG to first attempt to use
/// CryptoAPI to obtain the key.
///
CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG = 0x00020000,
///
/// This function will only attempt to obtain the key by using CNG and will not use CryptoAPI to obtain the key.
/// The pdwKeySpec variable receives the CERT_NCRYPT_KEY_SPEC flag if CNG is used to obtain the key.
///
CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = 0x00040000,
}
/// A set of flags that modify the behavior of .
[PInvokeData("wincrypt.h", MSDNShortId = "79d121df-0699-424e-a8de-5fc2b396afc2")]
[Flags]
public enum CryptDefaultContextFlags
{
///
/// The provider handle specified by the hCryptProv parameter is released automatically when the process or thread ends. If this
/// flag is not specified, it is the caller's responsibility to release the provider handle by using the CryptReleaseContext
/// function when the handle is no longer needed. The provider handle is not released if the CryptUninstallDefaultContext
/// function is called before the process or thread exits.
///
CRYPT_DEFAULT_CONTEXT_AUTO_RELEASE_FLAG = 0x00000001,
///
/// The provider applies to all threads in the process. If this flag is not specified, the provider only applies to the calling
/// thread. The pvDefaultPara parameter cannot be NULL when this flag is set.
///
CRYPT_DEFAULT_CONTEXT_PROCESS_FLAG = 0x00000002,
}
/// Specifies the type of context to install.
[PInvokeData("wincrypt.h", MSDNShortId = "79d121df-0699-424e-a8de-5fc2b396afc2")]
public enum CryptDefaultContextType
{
///
/// Installs the default provider used to verify a single certificate signature type.
///
/// The pvDefaultPara parameter is the address of a null-terminated ANSI string that contains the object identifier of the
/// certificate signature algorithm to install the provider for, for example, szOID_OIWSEC_md5RSA.If the pvDefaultPara parameter
/// is NULL, the specified provider is used to verify all certificate signatures.The pvDefaultPara parameter cannot be NULL when
/// the CRYPT_DEFAULT_CONTEXT_PROCESS_FLAG flag is set.
///
///
CRYPT_DEFAULT_CONTEXT_CERT_SIGN_OID = 1,
///
/// Installs the default provider used to verify multiple certificate signature types.
///
/// The pvDefaultPara parameter is the address of a CRYPT_DEFAULT_CONTEXT_MULTI_OID_PARA structure that contains an array of
/// object identifiers that identify the certificate signature algorithms to install the specified provider for.
///
///
CRYPT_DEFAULT_CONTEXT_MULTI_CERT_SIGN_OID = 2,
}
/// Private key pair type.
[PInvokeData("wincrypt.h")]
public enum PrivateKeyType
{
/// Key exchange
AT_KEYEXCHANGE = 1,
/// Digital signature
AT_SIGNATURE = 2
}
/// A set of flags that specify how the time stamp is retrieved.
[PInvokeData("wincrypt.h", MSDNShortId = "68ba3d40-08b0-4261-ab2f-6deb1795f830")]
[Flags]
public enum TimeStampRetrivalFlags
{
/// Inhibit hash calculation on the array of bytes pointed to by the pbData parameter.
TIMESTAMP_DONT_HASH_DATA = 0x00000001,
///
/// Enforce signature validation on the retrieved time stamp. The TIMESTAMP_VERIFY_CONTEXT_SIGNATURE flag is valid only if
/// the fRequestCerts member of the CRYPT_TIMESTAMP_PARA pointed to by the pPara parameter is set to TRUE.
///
TIMESTAMP_VERIFY_CONTEXT_SIGNATURE = 0x00000020,
/// Set this flag to inhibit automatic authentication handling.
TIMESTAMP_NO_AUTH_RETRIEVAL = 0x00020000,
}
/// Gets the ALG_CLASS from an ALG_ID.
/// The ALG_ID.
/// The associated ALG_CLASS.
public static ALG_CLASS GET_ALG_CLASS(ALG_ID algId) => (ALG_CLASS)((int)algId & (7 << 13));
/// Gets the ALG_TYPE from an ALG_ID.
/// The ALG_ID.
/// The associated ALG_TYPE.
public static ALG_TYPE GET_ALG_TYPE(ALG_ID algId) => (ALG_TYPE)((int)algId & (15 << 9));
/// Gets the ALG_CLASS from an ALG_ID.
/// The ALG_ID.
/// The associated ALG_CLASS.
public static ALG_CLASS GetClass(this ALG_ID algId) => GET_ALG_CLASS(algId);
/// Gets the ALG_TYPE from an ALG_ID.
/// The ALG_ID.
/// The associated ALG_TYPE.
public static ALG_TYPE GetType(this ALG_ID algId) => GET_ALG_TYPE(algId);
///
/// The CertAddEncodedCertificateToSystemStore function opens the specified system store and adds the encoded certificate to it.
///
/// A null-terminated string that contains the name of the system store for the encoded certificate.
/// A pointer to a buffer that contains the encoded certificate to add.
/// The size, in bytes, of the pbCertEncoded buffer.
///
/// If the function succeeds, the return value is TRUE.
///
/// If the function fails, the return value is FALSE. CertAddEncodedCertificateToSystemStore depends on the functions
/// listed in the following remarks for error handling. Refer to those function topics for their respective error handling
/// behaviors. For extended error information, call GetLastError.
///
///
///
///
/// Internally, CertAddEncodedCertificateToSystemStore calls CertOpenSystemStore and CertAddEncodedCertificateToStore with
/// the following parameters.
///
///
///
/// CertOpenSystemStore Parameter
/// Value
///
/// -
/// szSubsystemProtocol
/// szCertStoreName
///
///
///
/// If CertAddEncodedCertificateToSystemStore obtains a handle to the specified system store, it calls CertCloseStore to
/// close the handle before it returns.
///
///
///
/// CertAddEncodedCertificateToStore Parameter
/// Value
///
/// -
/// dwCertEncodingType
/// X509_ASN_ENCODING
///
/// -
/// dwAddDisposition
/// CERT_STORE_ADD_USE_EXISTING
///
/// -
/// ppCertContext
/// NULL
///
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certaddencodedcertificatetosystemstorea BOOL
// CertAddEncodedCertificateToSystemStoreA( LPCSTR szCertStoreName, const BYTE *pbCertEncoded, DWORD cbCertEncoded );
[DllImport(Lib.Crypt32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("wincrypt.h", MSDNShortId = "72ff1bcc-eb94-4d97-89fa-d95ed9eb460e")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CertAddEncodedCertificateToSystemStore([MarshalAs(UnmanagedType.LPTStr)] string szCertStoreName, [In] IntPtr pbCertEncoded, uint cbCertEncoded);
///
///
/// The CertFreeCertificateContext function frees a certificate context by decrementing its reference count. When the
/// reference count goes to zero, CertFreeCertificateContext frees the memory used by a certificate context.
///
///
/// To free a context obtained by a get, duplicate, or create function, call the appropriate free function. To free a context
/// obtained by a find or enumerate function, either pass it in as the previous context parameter to a subsequent invocation of the
/// function, or call the appropriate free function. For more information, see the reference topic for the function that obtains the context.
///
///
/// A pointer to the CERT_CONTEXT to be freed.
/// The function always returns nonzero.
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certfreecertificatecontext BOOL
// CertFreeCertificateContext( PCCERT_CONTEXT pCertContext );
[DllImport(Lib.Crypt32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("wincrypt.h", MSDNShortId = "7d2f3237-3f8b-4234-b6db-3057384cd89b")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CertFreeCertificateContext(PCCERT_CONTEXT pCertContext);
///
/// Resyncs the certificate chain engine, which resynchronizes the stores the store's engine and updates the engine caches.
///
/// The chain engine to resynchronize.
///
/// If the function succeeds, the function returns nonzero.
/// If the function fails, it returns zero. For extended error information, call GetLastError.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certresynccertificatechainengine BOOL
// CertResyncCertificateChainEngine( HCERTCHAINENGINE hChainEngine );
[DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("wincrypt.h", MSDNShortId = "D8674AD1-0407-4D1E-9E21-60CAC6D01FC5")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CertResyncCertificateChainEngine(HCERTCHAINENGINE hChainEngine);
///
///
/// The CryptAcquireCertificatePrivateKey function obtains the private key for a certificate. This function is used to obtain
/// access to a user's private key when the user's certificate is available, but the handle of the user's key container is not
/// available. This function can only be used by the owner of a private key and not by any other user.
///
///
/// If a CSP handle and the key container containing a user's private key are available, the CryptGetUserKey function should be used instead.
///
///
///
/// The address of a CERT_CONTEXT structure that contains the certificate context for which a private key will be obtained.
///
///
///
/// A set of flags that modify the behavior of this function. This can be zero or a combination of one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// CRYPT_ACQUIRE_CACHE_FLAG
///
/// If a handle is already acquired and cached, that same handle is returned. Otherwise, a new handle is acquired and cached by
/// using the certificate's CERT_KEY_CONTEXT_PROP_ID property. When this flag is set, the pfCallerFreeProvOrNCryptKey parameter
/// receives FALSE and the calling application must not release the handle. The handle is freed when the certificate context is
/// freed; however, you must retain the certificate context referenced by the pCert parameter as long as the key is in use,
/// otherwise operations that rely on the key will fail.
///
///
/// -
/// CRYPT_ACQUIRE_COMPARE_KEY_FLAG
///
/// The public key in the certificate is compared with the public key returned by the cryptographic service provider (CSP). If the
/// keys do not match, the acquisition operation fails and the last error code is set to NTE_BAD_PUBLIC_KEY. If a cached handle is
/// returned, no comparison is made.
///
///
/// -
/// CRYPT_ACQUIRE_NO_HEALING
///
/// This function will not attempt to re-create the CERT_KEY_PROV_INFO_PROP_ID property in the certificate context if this property
/// cannot be retrieved.
///
///
/// -
/// CRYPT_ACQUIRE_SILENT_FLAG
///
/// The CSP should not display any user interface (UI) for this context. If the CSP must display UI to operate, the call fails and
/// the NTE_SILENT_CONTEXT error code is set as the last error.
///
///
/// -
/// CRYPT_ACQUIRE_USE_PROV_INFO_FLAG
///
/// Uses the certificate's CERT_KEY_PROV_INFO_PROP_ID property to determine whether caching should be accomplished. For more
/// information about the CERT_KEY_PROV_INFO_PROP_ID property, see CertSetCertificateContextProperty. This function will only use
/// caching if during a previous call, the dwFlags member of the CRYPT_KEY_PROV_INFO structure contained CERT_SET_KEY_CONTEXT_PROP.
///
///
/// -
/// CRYPT_ACQUIRE_ WINDOWS_HANDLE_FLAG
///
/// Any UI that is needed by the CSP or KSP will be a child of the HWND that is supplied in the pvParameters parameter. For a CSP
/// key, using this flag will cause the CryptSetProvParam function with the flag PP_CLIENT_HWND using this HWND to be called with
/// NULL for HCRYPTPROV. For a KSP key, using this flag will cause the NCryptSetProperty function with the
/// NCRYPT_WINDOW_HANDLE_PROPERTY flag to be called using the HWND. Do not use this flag with CRYPT_ACQUIRE_SILENT_FLAG.
///
///
///
///
/// The following flags determine which technology is used to obtain the key. If none of these flags is present, this function will
/// only attempt to obtain the key by using CryptoAPI.
///
/// Windows Server 2003 and Windows XP: These flags are not supported.
///
///
/// Value
/// Meaning
///
/// -
/// CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG
///
/// This function will attempt to obtain the key by using CryptoAPI. If that fails, this function will attempt to obtain the key by
/// using the Cryptography API: Next Generation (CNG). The pdwKeySpec variable receives the CERT_NCRYPT_KEY_SPEC flag if CNG is used
/// to obtain the key.
///
///
/// -
/// CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG
///
/// This function will only attempt to obtain the key by using CNG and will not use CryptoAPI to obtain the key. The pdwKeySpec
/// variable receives the CERT_NCRYPT_KEY_SPEC flag if CNG is used to obtain the key.
///
///
/// -
/// CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
///
/// This function will attempt to obtain the key by using CNG. If that fails, this function will attempt to obtain the key by using
/// CryptoAPI. The pdwKeySpec variable receives the CERT_NCRYPT_KEY_SPEC flag if CNG is used to obtain the key.
///
///
///
///
///
///
/// If the CRYPT_ACQUIRE_WINDOWS_HANDLE_FLAG is set, then this is the address of an HWND. If the
/// CRYPT_ACQUIRE_WINDOWS_HANDLE_FLAG is not set, then this parameter must be NULL.
///
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This parameter
/// was named pvReserved and reserved for future use and must be NULL.
///
///
///
///
/// The address of an HCRYPTPROV_OR_NCRYPT_KEY_HANDLE variable that receives the handle of either the CryptoAPI provider or the CNG
/// key. If the pdwKeySpec variable receives the CERT_NCRYPT_KEY_SPEC flag, this is a CNG key handle of type
/// NCRYPT_KEY_HANDLE; otherwise, this is a CryptoAPI provider handle of type HCRYPTPROV.
///
///
/// For more information about when and how to release this handle, see the description of the pfCallerFreeProvOrNCryptKey parameter.
///
///
///
///
/// The address of a DWORD variable that receives additional information about the key. This can be one of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// AT_KEYEXCHANGE
/// The key pair is a key exchange pair.
///
/// -
/// AT_SIGNATURE
/// The key pair is a signature pair.
///
/// -
/// CERT_NCRYPT_KEY_SPEC
/// The key is a CNG key. Windows Server 2003 and Windows XP: This value is not supported.
///
///
///
///
///
/// The address of a BOOL variable that receives a value that indicates whether the caller must free the handle returned in
/// the phCryptProvOrNCryptKey variable. This receives FALSE if any of the following is true:
///
///
/// -
/// Public key acquisition or comparison fails.
///
/// -
/// The dwFlags parameter contains the CRYPT_ACQUIRE_CACHE_FLAG flag.
///
/// -
///
/// The dwFlags parameter contains the CRYPT_ACQUIRE_USE_PROV_INFO_FLAG flag, the certificate context property is set to
/// CERT_KEY_PROV_INFO_PROP_ID with the CRYPT_KEY_PROV_INFO structure, and the dwFlags member of the
/// CRYPT_KEY_PROV_INFO structure is set to CERT_SET_KEY_CONTEXT_PROP_ID.
///
///
///
/// If this variable receives
/// FALSE
/// , the calling application must not release the handle returned in the
/// phCryptProvOrNCryptKey
/// variable. The handle will be released on the last free action of the
/// certificate context
/// .
///
/// If this variable receives TRUE, the caller is responsible for releasing the handle returned in the phCryptProvOrNCryptKey
/// variable. If the pdwKeySpec variable receives the CERT_NCRYPT_KEY_SPEC flag, the handle must be released by passing it to
/// the NCryptFreeObject function; otherwise, the handle is released by passing it to the CryptReleaseContext function.
///
///
///
/// If the function succeeds, the return value is nonzero ( TRUE).
///
/// If the function fails, the return value is zero ( FALSE). For extended error information, call GetLastError. One possible
/// error code is the following.
///
///
///
/// Return code
/// Description
///
/// -
/// NTE_BAD_PUBLIC_KEY
///
/// The public key in the certificate does not match the public key returned by the CSP. This error code is returned if the
/// CRYPT_ACQUIRE_COMPARE_KEY_FLAG is set and the public key in the certificate does not match the public key returned by the
/// cryptographic provider.
///
///
/// -
/// NTE_SILENT_CONTEXT
///
/// The dwFlags parameter contained the CRYPT_ACQUIRE_SILENT_FLAG flag and the CSP could not continue an operation without
/// displaying a user interface.
///
///
///
///
///
///
/// When CRYPT_ACQUIRE_WINDOWS_HANDLE_FLAG is set, the caller must ensure the HWND is valid. If the HWND is no
/// longer valid, for CSP the caller should call CryptSetProvParam using flag PP_CLIENT_HWND with NULL for the HWND
/// and NULL for the HCRYPTPROV. For KSP, the caller should set the NCRYPT_WINDOW_HANDLE_PROPERTY of the ncrypt key to be
/// NULL. When CRYPT_ACQUIRE_WINDOWS_HANDLE_FLAG flag is set for KSP, the NCRYPT_WINDOW_HANDLE_PROPERTY is set on the
/// storage provider and the key. If both calls fail, then the function fails. If only one fails, the function succeeds. Note that
/// setting HWND to NULL effectively removes HWND from the HCRYPTPROV or ncrypt key.
///
/// Examples
/// For an example that uses this function, see Example C Program: Sending and Receiving a Signed and Encrypted Message.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecertificateprivatekey BOOL
// CryptAcquireCertificatePrivateKey( PCCERT_CONTEXT pCert, DWORD dwFlags, void *pvParameters, HCRYPTPROV_OR_NCRYPT_KEY_HANDLE
// *phCryptProvOrNCryptKey, DWORD *pdwKeySpec, BOOL *pfCallerFreeProvOrNCryptKey );
[DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("wincrypt.h", MSDNShortId = "53c9aec9-701d-4c21-9814-d344a8dde0c1")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptAcquireCertificatePrivateKey([In] PCCERT_CONTEXT pCert, CryptAcquireFlags dwFlags, [In, Optional] IntPtr pvParameters, out IntPtr phCryptProvOrNCryptKey,
out CertKeySpec pdwKeySpec, [MarshalAs(UnmanagedType.Bool)] out bool pfCallerFreeProvOrNCryptKey);
///
///
/// The handle of the cryptographic service provider to be used as the default context. This handle is obtained by using the
/// CryptAcquireContext function.
///
/// Specifies the type of context to install. This must be one of the following values.
///
///
/// Value
/// Meaning
///
/// -
/// CRYPT_DEFAULT_CONTEXT_CERT_SIGN_OID
///
/// Installs the default provider used to verify a single certificate signature type. The pvDefaultPara parameter is the address of
/// a null-terminated ANSI string that contains the object identifier of the certificate signature algorithm to install the provider
/// for, for example, szOID_OIWSEC_md5RSA. If the pvDefaultPara parameter is NULL, the specified provider is used to verify all
/// certificate signatures. The pvDefaultPara parameter cannot be NULL when the CRYPT_DEFAULT_CONTEXT_PROCESS_FLAG flag is set.
///
///
/// -
/// CRYPT_DEFAULT_CONTEXT_MULTI_CERT_SIGN_OID
///
/// Installs the default provider used to verify multiple certificate signature types. The pvDefaultPara parameter is the address of
/// a CRYPT_DEFAULT_CONTEXT_MULTI_OID_PARA structure that contains an array of object identifiers that identify the certificate
/// signature algorithms to install the specified provider for.
///
///
///
///
/// Specifies the object or objects to install the default context provider for. The format of this parameter depends on the
/// contents of the dwDefaultType parameter.
///
///
/// A set of flags that modify the behavior of this function. This can be zero or a combination of one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// CRYPT_DEFAULT_CONTEXT_AUTO_RELEASE_FLAG
///
/// The provider handle specified by the hCryptProv parameter is released automatically when the process or thread ends. If this
/// flag is not specified, it is the caller's responsibility to release the provider handle by using the CryptReleaseContext
/// function when the handle is no longer needed. The provider handle is not released if the CryptUninstallDefaultContext function
/// is called before the process or thread exits.
///
///
/// -
/// CRYPT_DEFAULT_CONTEXT_PROCESS_FLAG
///
/// The provider applies to all threads in the process. If this flag is not specified, the provider only applies to the calling
/// thread. The pvDefaultPara parameter cannot be NULL when this flag is set.
///
///
///
/// This parameter is reserved for future use.
///
/// The address of an HCRYPTDEFAULTCONTEXT variable that receives the default context handle. This handle is passed to the
/// CryptUninstallDefaultContext function to uninstall the default context provider.
///
///
///
/// The handle of the cryptographic service provider to be used as the default context. This handle is obtained by using the
/// CryptAcquireContext function.
///
///
/// Specifies the type of context to install. This must be one of the following values.
///
///
/// Value
/// Meaning
///
/// -
/// CRYPT_DEFAULT_CONTEXT_CERT_SIGN_OID
///
/// Installs the default provider used to verify a single certificate signature type. The pvDefaultPara parameter is the address of
/// a null-terminated ANSI string that contains the object identifier of the certificate signature algorithm to install the provider
/// for, for example, szOID_OIWSEC_md5RSA. If the pvDefaultPara parameter is NULL, the specified provider is used to verify all
/// certificate signatures. The pvDefaultPara parameter cannot be NULL when the CRYPT_DEFAULT_CONTEXT_PROCESS_FLAG flag is set.
///
///
/// -
/// CRYPT_DEFAULT_CONTEXT_MULTI_CERT_SIGN_OID
///
/// Installs the default provider used to verify multiple certificate signature types. The pvDefaultPara parameter is the address of
/// a CRYPT_DEFAULT_CONTEXT_MULTI_OID_PARA structure that contains an array of object identifiers that identify the certificate
/// signature algorithms to install the specified provider for.
///
///
///
///
///
/// Specifies the object or objects to install the default context provider for. The format of this parameter depends on the
/// contents of the dwDefaultType parameter.
///
///
///
/// A set of flags that modify the behavior of this function. This can be zero or a combination of one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// CRYPT_DEFAULT_CONTEXT_AUTO_RELEASE_FLAG
///
/// The provider handle specified by the hCryptProv parameter is released automatically when the process or thread ends. If this
/// flag is not specified, it is the caller's responsibility to release the provider handle by using the CryptReleaseContext
/// function when the handle is no longer needed. The provider handle is not released if the CryptUninstallDefaultContext function
/// is called before the process or thread exits.
///
///
/// -
/// CRYPT_DEFAULT_CONTEXT_PROCESS_FLAG
///
/// The provider applies to all threads in the process. If this flag is not specified, the provider only applies to the calling
/// thread. The pvDefaultPara parameter cannot be NULL when this flag is set.
///
///
///
///
/// This parameter is reserved for future use.
///
/// The address of an HCRYPTDEFAULTCONTEXT variable that receives the default context handle. This handle is passed to the
/// CryptUninstallDefaultContext function to uninstall the default context provider.
///
///
/// If the function succeeds, the return value is nonzero (TRUE). If the function fails, the return value is zero (FALSE). For
/// extended error information, call GetLastError.
///
///
///
/// The installed default context providers are stack ordered, thus when searching for a default context provider, the system starts
/// with the most recently installed provider. The per-thread list of providers is searched before the per-process list of
/// providers. After a match is found, the system does not continue to search for other matches.
///
///
/// The installed provider handle must remain available for use until CryptUninstallDefaultContext is called, or the thread or
/// process exits.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptinstalldefaultcontext BOOL
// CryptInstallDefaultContext( HCRYPTPROV hCryptProv, DWORD dwDefaultType, const void *pvDefaultPara, DWORD dwFlags, void
// *pvReserved, HCRYPTDEFAULTCONTEXT *phDefaultContext );
[DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("wincrypt.h", MSDNShortId = "79d121df-0699-424e-a8de-5fc2b396afc2")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptInstallDefaultContext(HCRYPTPROV hCryptProv, CryptDefaultContextType dwDefaultType, [In] IntPtr pvDefaultPara,
CryptDefaultContextFlags dwFlags, [Optional] IntPtr pvReserved, out HCRYPTDEFAULTCONTEXT phDefaultContext);
///
/// The CryptRetrieveTimeStamp function encodes a time stamp request and retrieves the time stamp token from a location
/// specified by a URL to a Time Stamping Authority (TSA).
///
///
/// A pointer to a null-terminated wide character string that contains the URL of the TSA to which to send the request.
///
///
/// A set of flags that specify how the time stamp is retrieved.
///
///
/// Value
/// Meaning
///
/// -
/// TIMESTAMP_DONT_HASH_DATA 0x00000001
/// Inhibit hash calculation on the array of bytes pointed to by the pbData parameter.
///
/// -
/// TIMESTAMP_VERIFY_CONTEXT_SIGNATURE 0x00000020
/// Enforce signature validation on the retrieved time stamp.
///
/// -
/// TIMESTAMP_NO_AUTH_RETRIEVAL 0x00020000
/// Set this flag to inhibit automatic authentication handling.
///
///
///
///
/// A DWORD value that specifies the maximum number of milliseconds to wait for retrieval. If this parameter is set to zero,
/// this function does not time out.
///
///
/// A pointer to a null-terminated character string that contains the hash algorithm object identifier (OID).
///
/// A pointer to a CRYPT_TIMESTAMP_PARA structure that contains additional parameters for the request.
/// A pointer to an array of bytes to be time stamped.
/// The size, in bytes, of the array pointed to by the pbData parameter.
///
/// A pointer to a PCRYPT_TIMESTAMP_CONTEXT structure. When you have finished using the context, you must free it by calling the
/// CryptMemFree function.
///
///
///
/// A pointer to a PCERT_CONTEXT that receives the certificate of the signer. When you have finished using this structure, you must
/// free it by passing this pointer to the CertFreeCertificateContext function.
///
/// Set this parameter to NULL if the TSA signer's certificate is not needed.
///
///
///
/// The handle of a certificate store initialized with certificates from the time stamp response. This store can be used for
/// validating the signer certificate of the time stamp response.
///
///
/// This parameter can be NULL if the TSA supporting certificates are not needed. When you have finished using this handle,
/// release it by passing it to the CertCloseStore function.
///
///
///
/// If the function is unable to retrieve, decode, and validate the time stamp context, it returns FALSE. For extended error
/// information, call the GetLastError function.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptretrievetimestamp BOOL CryptRetrieveTimeStamp(
// LPCWSTR wszUrl, DWORD dwRetrievalFlags, DWORD dwTimeout, LPCSTR pszHashId, const CRYPT_TIMESTAMP_PARA *pPara, const BYTE *pbData,
// DWORD cbData, PCRYPT_TIMESTAMP_CONTEXT *ppTsContext, PCCERT_CONTEXT *ppTsSigner, HCERTSTORE *phStore );
[DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("wincrypt.h", MSDNShortId = "68ba3d40-08b0-4261-ab2f-6deb1795f830")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptRetrieveTimeStamp([MarshalAs(UnmanagedType.LPWStr)] string wszUrl, TimeStampRetrivalFlags dwRetrievalFlags, uint dwTimeout, SafeOID pszHashId,
in CRYPT_TIMESTAMP_PARA pPara, [In] IntPtr pbData, uint cbData, out SafeCryptMem ppTsContext, out SafePCCERT_CONTEXT ppTsSigner, out SafeHCERTSTORE phStore);
///
/// Handle of the context to be released.
/// Reserved for future use.
/// Reserved for future use.
///
/// Handle of the context to be released.
/// Reserved for future use.
/// Reserved for future use.
///
/// If the function succeeds, the return value is nonzero (TRUE) .If the function fails, the return value is zero (FALSE). For
/// extended error information, call GetLastError.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptuninstalldefaultcontext BOOL
// CryptUninstallDefaultContext( HCRYPTDEFAULTCONTEXT hDefaultContext, DWORD dwFlags, void *pvReserved );
[DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("wincrypt.h", MSDNShortId = "ad7be5cf-f078-4a9f-81c4-959e4203dba8")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptUninstallDefaultContext(HCRYPTDEFAULTCONTEXT hDefaultContext, uint dwFlags = 0, IntPtr pvReserved = default);
/// The CryptVerifyTimeStampSignature function validates the time stamp signature on a specified array of bytes.
/// A pointer to a buffer that contains time stamp content.
/// The size, in bytes, of the buffer pointed to by the pbTSContentInfo parameter.
/// A pointer to an array of bytes on which to validate the time stamp signature.
/// The size, in bytes, of the array pointed to by the pbData parameter.
///
/// The handle of an additional store to search for supporting Time Stamping Authority (TSA) signing certificates and certificate
/// trust lists (CTLs). This parameter can be NULL if no additional store is to be searched.
///
///
/// A pointer to a PCRYPT_TIMESTAMP_CONTEXT structure. When you have finished using the context, you must free it by calling the
/// CryptMemFree function.
///
///
///
/// A pointer to a PCERT_CONTEXT that receives the certificate of the signer. When you have finished using this structure, you must
/// free it by passing this pointer to the CertFreeCertificateContext function.
///
/// Set this parameter to NULL if the TSA signer's certificate is not needed.
///
///
/// A pointer to a handle that receives the certificate store opened on CMS to search for supporting certificates.
///
/// This parameter can be NULL if the TSA supporting certificates are not needed. When you have finished using this handle,
/// you must release it by passing it to the CertCloseStore function.
///
///
///
/// If the function succeeds, the function returns TRUE. For extended error information, call the GetLastError function.
///
///
/// The caller should validate the pszTSAPolicyId member of the CRYPT_TIMESTAMP_INFO structure when it is returned by the
/// CryptRetrieveTimeStamp function. If a TSA policy was specified in the request and the ftTime member contains a valid
/// value, the caller should build a certificate context chain with which to populate the ppTsSigner parameter and validate the trust.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptverifytimestampsignature BOOL
// CryptVerifyTimeStampSignature( const BYTE *pbTSContentInfo, DWORD cbTSContentInfo, const BYTE *pbData, DWORD cbData, HCERTSTORE
// hAdditionalStore, PCRYPT_TIMESTAMP_CONTEXT *ppTsContext, PCCERT_CONTEXT *ppTsSigner, HCERTSTORE *phStore );
[DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("wincrypt.h", MSDNShortId = "791b1500-98e3-49d5-97aa-be91f5edb7c2")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptVerifyTimeStampSignature([In] IntPtr pbTSContentInfo, uint cbTSContentInfo, [In, Optional] IntPtr pbData, uint cbData,
[In, Optional] HCERTSTORE hAdditionalStore, out SafeCryptMem ppTsContext, out SafePCCERT_CONTEXT ppTsSigner, out SafeHCERTSTORE phStore);
/// Determines whether a cryptography algorithm is only supported by using the CNG functions.
/// The cryptography algorithm.
/// if algorithm is only supported by using the CNG functions; otherwise, .
public static bool IS_SPECIAL_OID_INFO_ALGID(ALG_ID Algid) => Algid >= ALG_ID.CALG_OID_INFO_PARAMETERS;
///
/// The CERT_CONTEXT structure contains both the encoded and decoded representations of a certificate. A certificate context
/// returned by one of the functions defined in Wincrypt.h must be freed by calling the CertFreeCertificateContext function. The
/// CertDuplicateCertificateContext function can be called to make a duplicate copy (which also must be freed by calling CertFreeCertificateContext).
///
[PInvokeData("wincrypt.h")]
[StructLayout(LayoutKind.Sequential)]
public struct CERT_CONTEXT
{
///
/// Type of encoding used. It is always acceptable to specify both the certificate and message encoding types by combining them
/// with a bitwise-OR operation.
///
public CertEncodingType dwCertEncodingType;
/// A pointer to a buffer that contains the encoded certificate.
public IntPtr pbCertEncoded;
/// The size, in bytes, of the encoded certificate.
public uint cbCertEncoded;
/// The address of a CERT_INFO structure that contains the certificate information.
public IntPtr pCertInfo;
/// A handle to the certificate store that contains the certificate context.
public HCERTSTORE hCertStore;
/// The address of a CERT_INFO structure that contains the certificate information.
public unsafe CERT_INFO* pUnsafeCertInfo => (CERT_INFO*)(void*)pCertInfo;
}
///
/// The CERT_EXTENSION structure contains the extension information for a certificate, Certificate Revocation List (CRL) or
/// Certificate Trust List (CTL).
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_extension typedef struct _CERT_EXTENSION { LPSTR
// pszObjId; BOOL fCritical; CRYPT_OBJID_BLOB Value; } CERT_EXTENSION, *PCERT_EXTENSION;
[PInvokeData("wincrypt.h", MSDNShortId = "787a4df0-c0e3-46b9-a7e6-eb3bee3ed717")]
[StructLayout(LayoutKind.Sequential)]
public struct CERT_EXTENSION
{
///
/// Object identifier (OID) that specifies the structure of the extension data contained in the Value member. For
/// specifics on extension OIDs and their related structures, see X.509 Certificate Extension Structures.
///
public StrPtrAnsi pszObjId;
///
/// If TRUE, any limitations specified by the extension in the Value member of this structure are imperative. If
/// FALSE, limitations set by this extension can be ignored.
///
[MarshalAs(UnmanagedType.Bool)] public bool fCritical;
///
/// A CRYPT_OBJID_BLOB structure that contains the encoded extension data. The cbData member of Value indicates
/// the length in bytes of the pbData member. The pbData member byte string is the encoded extension.
///
public CRYPTOAPI_BLOB Value;
}
/// The CERT_EXTENSIONS structure contains an array of extensions.
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_extensions typedef struct _CERT_EXTENSIONS { DWORD
// cExtension; PCERT_EXTENSION rgExtension; } CERT_EXTENSIONS, *PCERT_EXTENSIONS;
[PInvokeData("wincrypt.h", MSDNShortId = "b393ef08-cedb-4840-a427-10ead315d6ea")]
[StructLayout(LayoutKind.Sequential)]
public struct CERT_EXTENSIONS
{
/// Number of elements in the array rgExtension.
public uint cExtension;
/// Array of structures, each holding information of type CERT_EXTENSION about a certificate or CRL.
public IntPtr rgExtension;
}
/// The CERT_ID structure is used as a flexible means of uniquely identifying a certificate.
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_id typedef struct _CERT_ID { DWORD dwIdChoice; union
// { CERT_ISSUER_SERIAL_NUMBER IssuerSerialNumber; CRYPT_HASH_BLOB KeyId; CRYPT_HASH_BLOB HashId; } DUMMYUNIONNAME; } CERT_ID, *PCERT_ID;
[PInvokeData("wincrypt.h", MSDNShortId = "9e33f661-c365-4725-8c3f-27b6cdd9a84e")]
[StructLayout(LayoutKind.Explicit)]
public struct CERT_ID
{
///
/// A DWORD value that indicates which member of the union is being used. This can be one of the following values.
///
///
/// Value
/// Meaning
///
/// -
/// CERT_ID_ISSUER_SERIAL_NUMBER
/// IssuerSerialNumber
///
/// -
/// CERT_ID_KEY_IDENTIFIER
/// KeyId
///
/// -
/// CERT_ID_SHA1_HASH
/// HashId
///
///
///
[FieldOffset(0)]
public uint dwIdChoice;
/// A CERT_ISSUER_SERIAL_NUMBER structure that uniquely identifies a certificate.
[FieldOffset(4)]
public CERT_ISSUER_SERIAL_NUMBER IssuerSerialNumber;
/// A CRYPT_HASH_BLOB structure that contains a certificate key identifier.
[FieldOffset(4)]
public CRYPTOAPI_BLOB KeyId;
/// A CRYPT_HASH_BLOB that contains a SHA1 hash of the certificate to be used as a unique identifier of the certificate.
[FieldOffset(4)]
public CRYPTOAPI_BLOB HashId;
}
/// The CERT_INFO structure contains the information of a certificate.
[PInvokeData("wincrypt.h")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CERT_INFO
{
/// The version number of a certificate.
public uint dwVersion;
///
/// A BLOB that contains the serial number of a certificate. The least significant byte is the zero byte of the pbData member of
/// SerialNumber. The index for the last byte of pbData, is one less than the value of the cbData member of SerialNumber. The
/// most significant byte is the last byte of pbData. Leading 0x00 or 0xFF bytes are removed. For more information, see CertCompareIntegerBlob.
///
public CRYPTOAPI_BLOB SerialNumber;
///
/// A CRYPT_ALGORITHM_IDENTIFIER structure that contains the signature algorithm type and encoded additional encryption parameters.
///
public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;
/// The name, in encoded form, of the issuer of the certificate.
public CRYPTOAPI_BLOB Issuer;
///
/// Date and time before which the certificate is not valid. For dates between 1950 and 2049 inclusive, the date and time is
/// encoded Coordinated Universal Time (Greenwich Mean Time) format in the form YYMMDDHHMMSS. This member uses a two-digit year
/// and is precise to seconds. For dates before 1950 or after 2049, encoded generalized time is used. Encoded generalized time
/// is in the form YYYYMMDDHHMMSSMMM, using a four-digit year, and is precise to milliseconds. Even though generalized time
/// supports millisecond resolution, the NotBefore time is only precise to seconds.
///
public FILETIME NotBefore;
///
/// Date and time after which the certificate is not valid. For dates between 1950 and 2049 inclusive, the date and time is
/// encoded Coordinated Universal Time format in the form YYMMDDHHMMSS. This member uses a two-digit year and is precise to
/// seconds. For dates before 1950 or after 2049, encoded generalized time is used. Encoded generalized time is in the form
/// YYYYMMDDHHMMSSMMM, using a four-digit year, and is precise to milliseconds. Even though generalized time supports
/// millisecond resolution, the NotAfter time is only precise to seconds.
///
public FILETIME NotAfter;
/// The encoded name of the subject of the certificate.
public CRYPTOAPI_BLOB Subject;
///
/// A CERT_PUBLIC_KEY_INFO structure that contains the encoded public key and its algorithm. The PublicKey member of the
/// CERT_PUBLIC_KEY_INFO structure contains the encoded public key as a CRYPT_BIT_BLOB, and the Algorithm member contains the
/// encoded algorithm as a CRYPT_ALGORITHM_IDENTIFIER.
///
public CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo;
/// A BLOB that contains a unique identifier of the issuer.
public CRYPT_BIT_BLOB IssuerUniqueId;
/// A BLOB that contains a unique identifier of the subject.
public CRYPT_BIT_BLOB SubjectUniqueId;
/// The number of elements in the rgExtension array.
public uint cExtension;
/// An array of pointers to CERT_EXTENSION structures, each of which contains extension information about the certificate.
public IntPtr rgExtension;
}
///
/// The CERT_ISSUER_SERIAL_NUMBER structure acts as a unique identifier of a certificate containing the issuer and issuer's
/// serial number for a certificate.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_issuer_serial_number typedef struct
// _CERT_ISSUER_SERIAL_NUMBER { CERT_NAME_BLOB Issuer; CRYPT_INTEGER_BLOB SerialNumber; } CERT_ISSUER_SERIAL_NUMBER, *PCERT_ISSUER_SERIAL_NUMBER;
[PInvokeData("wincrypt.h", MSDNShortId = "4e44113f-81e7-4551-bf4d-50986d6d57bb")]
[StructLayout(LayoutKind.Sequential)]
public struct CERT_ISSUER_SERIAL_NUMBER
{
/// A BLOB structure that contains the name of the issuer.
public CRYPTOAPI_BLOB Issuer;
///
/// A CRYPT_INTEGER_BLOB structure that contains the serial number of the certificate. The combination of the issuer name and
/// the serial number is a unique identifier of a certificate.
///
public CRYPTOAPI_BLOB SerialNumber;
}
/// The CERT_KEY_CONTEXT structure contains data associated with a CERT_KEY_CONTEXT_PROP_ID property.
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_key_context typedef struct _CERT_KEY_CONTEXT { DWORD
// cbSize; union { HCRYPTPROV hCryptProv; NCRYPT_KEY_HANDLE hNCryptKey; } DUMMYUNIONNAME; DWORD dwKeySpec; } CERT_KEY_CONTEXT, *PCERT_KEY_CONTEXT;
[PInvokeData("wincrypt.h", MSDNShortId = "796adb9c-ec38-41d0-8f8b-ea1053e9f9f0")]
[StructLayout(LayoutKind.Sequential)]
public struct CERT_KEY_CONTEXT
{
/// The size, in bytes, of this structure.
public uint cbSize;
///
/// A cryptographic service provider (CSP) handle. This member is used when the dwKeySpec member contains
/// AT_KEYEXCHANGE or AT_SIGNATURE.
/// OR
/// A CNG CSP handle. This member is used when the dwKeySpec member contains CERT_NCRYPT_KEY_SPEC.
/// Windows Server 2003 and Windows XP: This member is not available.
///
public IntPtr hCryptProv_or_hNCryptKey;
///
/// The specification of the private key to retrieve.
///
public CertKeySpec dwKeySpec;
}
/// The CERT_PUBLIC_KEY_INFO structure contains a public key and its algorithm.
[PInvokeData("wincrypt.h")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CERT_PUBLIC_KEY_INFO
{
/// CRYPT_ALGORITHM_IDENTIFIER structure that contains the public key algorithm type and associated additional parameters.
public CRYPT_ALGORITHM_IDENTIFIER Algorithm;
/// BLOB containing an encoded public key.
public CRYPT_BIT_BLOB PublicKey;
}
///
/// The CERT_RDN structure contains a relative distinguished name (RDN) consisting of an array of CERT_RDN_ATTR structures.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_rdn typedef struct _CERT_RDN { DWORD cRDNAttr;
// PCERT_RDN_ATTR rgRDNAttr; } CERT_RDN, *PCERT_RDN;
[PInvokeData("wincrypt.h", MSDNShortId = "e84254b9-e9a7-4689-a12f-2772282c5433")]
[StructLayout(LayoutKind.Sequential)]
public struct CERT_RDN
{
/// Number of elements in the rgRDNAttr array.
public uint cRDNAttr;
/// Array of CERT_RDN_ATTR structures.
public IntPtr rgRDNAttr;
}
///
/// The CERT_RDN_ATTR structure contains a single attribute of a relative distinguished name (RDN). A whole RDN is expressed
/// in a CERT_RDN structure that contains an array of CERT_RDN_ATTR structures.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_rdn_attr
// typedef struct _CERT_RDN_ATTR { LPSTR pszObjId; DWORD dwValueType; CERT_RDN_VALUE_BLOB Value; } CERT_RDN_ATTR, *PCERT_RDN_ATTR;
[PInvokeData("wincrypt.h", MSDNShortId = "NS:wincrypt._CERT_RDN_ATTR")]
[StructLayout(LayoutKind.Sequential)]
public struct CERT_RDN_ATTR
{
///
///
/// Object identifier (OID) for the type of the attribute defined in this structure. This member can be one of the values.
///
///
///
/// Value
/// Meaning
///
/// -
/// szOID_AUTHORITY_REVOCATION_LIST
/// Security attribute.
///
/// -
/// szOID_BUSINESS_CATEGORY
/// Case-insensitive string. Explanatory attribute.
///
/// -
/// szOID_CA_CERTIFICATE
/// Security attribute.
///
/// -
/// szOID_CERTIFICATE_REVOCATION_LIST
/// Security attribute.
///
/// -
/// szOID_COMMON_NAME
/// Case-insensitive string. Labeling attribute.
///
/// -
/// szOID_COUNTRY_NAME
/// Two-character printable string. Geographic attribute.
///
/// -
/// szOID_CROSS_CERTIFICATE_PAIR
/// Security attribute.
///
/// -
/// szOID_DESCRIPTION
/// Case-insensitive string. Explanatory attribute.
///
/// -
/// szOID_DESTINATION_INDICATOR
/// Printable string. Telecommunications addressing attribute.
///
/// -
/// szOID_DEVICE_SERIAL_NUMBER
/// Printable string. Labeling attribute.
///
/// -
/// szOID_DOMAIN_COMPONENT
/// IA5 string. DNS name component such as "com."
///
/// -
/// szOID_FACSIMILE_TELEPHONE_NUMBER
/// Telecommunications addressing attribute.
///
/// -
/// szOID_GIVEN_NAME
/// Case-insensitive string. Name attribute.
///
/// -
/// szOID_INITIALS
/// Case-insensitive string. Name attribute.
///
/// -
/// szOID_INTERNATIONAL_ISDN_NUMBER
/// Numeric string. Telecommunications addressing attribute.
///
/// -
/// szOID_LOCALITY_NAME
/// Case-insensitive string. Geographic attribute.
///
/// -
/// szOID_MEMBER
/// Relational application attribute.
///
/// -
/// szOID_ORGANIZATION_NAME
/// Case-insensitive string. Organizational attribute.
///
/// -
/// szOID_ORGANIZATIONAL_UNIT_NAME
/// Case-insensitive string. Organizational attribute.
///
/// -
/// szOID_OWNER
/// Relational application attribute.
///
/// -
/// szOID_PHYSICAL_DELIVERY_OFFICE_NAME
/// Case-insensitive string. Postal addressing attribute.
///
/// -
/// szOID_PKCS_12_FRIENDLY_NAME_ATTR
/// PKCS #12 attribute.
///
/// -
/// szOID_PKCS_12_LOCAL_KEY_ID
/// PKCS #12 attribute.
///
/// -
/// szOID_POST_OFFICE_BOX
/// Case-insensitive string. Postal addressing attribute.
///
/// -
/// szOID_POSTAL_ADDRESS
/// Printable string. Postal addressing attribute.
///
/// -
/// szOID_POSTAL_CODE
/// Case-insensitive string. Postal addressing attribute.
///
/// -
/// szOID_PREFERRED_DELIVERY_METHOD
/// Preference attribute.
///
/// -
/// szOID_PRESENTATION_ADDRESS
/// OSI application attribute.
///
/// -
/// szOID_REGISTERED_ADDRESS
/// Telecommunications addressing attribute.
///
/// -
/// szOID_ROLE_OCCUPANT
/// Relational application attribute.
///
/// -
/// szOID_RSA_emailAddr
/// IA5 string. Email attribute.
///
/// -
/// szOID_SEARCH_GUIDE
/// Explanatory attribute.
///
/// -
/// szOID_SEE_ALSO
/// Relational application attribute.
///
/// -
/// szOID_STATE_OR_PROVINCE_NAME
/// Case-insensitive string. Geographic attribute.
///
/// -
/// szOID_STREET_ADDRESS
/// Case-insensitive string. Geographic attribute.
///
/// -
/// szOID_SUPPORTED_APPLICATION_CONTEXT
/// OSI application attribute.
///
/// -
/// szOID_SUR_NAME
/// Case-insensitive string. Labeling attribute.
///
/// -
/// szOID_TELEPHONE_NUMBER
/// Telecommunications addressing attribute.
///
/// -
/// szOID_TELETEXT_TERMINAL_IDENTIFIER
/// Telecommunications addressing attribute.
///
/// -
/// szOID_TELEX_NUMBER
/// Telecommunications addressing attribute.
///
/// -
/// szOID_TITLE
/// Case-insensitive string. Organizational attribute.
///
/// -
/// szOID_USER_CERTIFICATE
/// Security attribute.
///
/// -
/// szOID_USER_PASSWORD
/// Security attribute.
///
/// -
/// szOID_X21_ADDRESS
/// Numeric string. Telecommunications addressing attribute.
///
///
///
[MarshalAs(UnmanagedType.LPStr)]
public string pszObjId;
///
/// Indicates the interpretation of the Value member.
/// This member can be one of the following values.
///
///
/// Value
/// Meaning
///
/// -
/// CERT_RDN_ANY_TYPE
/// The pszObjId member determines the assumed type and length.
///
/// -
/// CERT_RDN_BMP_STRING
/// An array of Unicode characters (16-bit).
///
/// -
/// CERT_RDN_ENCODED_BLOB
/// An encoded data BLOB.
///
/// -
/// CERT_RDN_GENERAL_STRING
/// Currently not used.
///
/// -
/// CERT_RDN_GRAPHIC_STRING
/// Currently not used.
///
/// -
/// CERT_RDN_IA5_STRING
/// An arbitrary string of IA5 (ASCII) characters.
///
/// -
/// CERT_RDN_INT4_STRING
/// An array of INT4 elements (32-bit).
///
/// -
/// CERT_RDN_ISO646_STRING
/// A 128-character set (8-bit).
///
/// -
/// CERT_RDN_NUMERIC_STRING
/// Only the characters 0 through 9 and the space character (8-bit).
///
/// -
/// CERT_RDN_OCTET_STRING
/// An arbitrary string of octets (8-bit).
///
/// -
/// CERT_RDN_PRINTABLE_STRING
/// An arbitrary string of printable characters (8-bit).
///
/// -
/// CERT_RDN_T61_STRING
/// An arbitrary string of T.61 characters (8-bit).
///
/// -
/// CERT_RDN_TELETEX_STRING
/// An arbitrary string of T.61 characters (8-bit)
///
/// -
/// CERT_RDN_UNICODE_STRING
/// An array of Unicode characters (16-bit).
///
/// -
/// CERT_RDN_UNIVERSAL_STRING
/// An array of INT4 elements (32-bit).
///
/// -
/// CERT_RDN_UTF8_STRING
/// An array of 16 bit Unicode characters UTF8 encoded on the wire as a sequence of one, two, or three, eight-bit characters.
///
/// -
/// CERT_RDN_VIDEOTEX_STRING
/// An arbitrary string of videotext characters.
///
/// -
/// CERT_RDN_VISIBLE_STRING
/// A 95-character set (8-bit).
///
///
/// The following flags can be combined by using a bitwise- OR operation into the dwValueType member.
///
///
/// Value
/// Meaning
///
/// -
/// CERT_RDN_DISABLE_CHECK_TYPE_FLAG
/// For encoding. When set, the characters are not checked to determine whether they are valid for the value type.
///
/// -
/// CERT_RDN_DISABLE_IE4_UTF8_FLAG
///
/// For decoding. By default, CERT_RDN_T61_STRING encoded values are initially decoded as UTF8. If the UTF8 decoding fails, the
/// value is decoded as 8-bit characters. If this flag is set, it skips the initial attempt to decode as UTF8 and decodes the
/// value as 8-bit characters.
///
///
/// -
/// CERT_RDN_ENABLE_T61_UNICODE_FLAG
///
/// For encoding. When set, if all the Unicode characters are <= 0xFF, the CERT_RDN_T61_STRING value is selected instead of
/// the CERT_RDN_UNICODE_STRING value.
///
///
/// -
/// CERT_RDN_ENABLE_UTF8_UNICODE_FLAG
///
/// For encoding. When set, strings are encoded with the CERT_RDN_UTF8_STRING value instead of the CERT_RDN_UNICODE_STRING value.
///
///
/// -
/// CERT_RDN_FORCE_UTF8_UNICODE_FLAG
///
/// For encoding. When set, strings are encoded with the CERT_RDN_UTF8_STRING value instead of CERT_RDN_PRINTABLE_STRING value
/// for DirectoryString types. In addition, CERT_RDN_ENABLE_UTF8_UNICODE_FLAG is enabled. Windows Vista, Windows Server 2003 and
/// Windows XP: This flag is not supported.
///
///
/// -
/// CERT_RDN_ENABLE_PUNYCODE_FLAG
///
/// For encoding. If the string contains an email RDN, and the email address is Punycode encoded, then the resultant email
/// address is encoded as an IA5String. The Punycode encoding of the host name is performed on a label-by-label basis. For
/// decoding. If the name contains an email RDN, and the local part or host name portion of the email address contains a
/// Punycode encoded IA5String, the RDN string value is converted to its Unicode equivalent. Windows Server 2008, Windows Vista,
/// Windows Server 2003 and Windows XP: This flag is not supported.
///
///
///
///
public CertRDNType dwValueType;
///
///
/// A CERT_RDN_VALUE_BLOB that contains the attribute value. The cbData member of Value is the length, in bytes,
/// of the pbData member. It is not the number of elements in the pbData string.
///
///
/// For example, a DWORD is 32 bits or 4 bytes long. If pbData is a DWORD array, cbData would be
/// four times the number of DWORD elements in the array. A SHORT is 16 bits or 2 bytes long. If pbData is
/// an array of SHORT elements, cbData must be two times the length of the array.
///
///
/// The pbData member of Value can be a null-terminated array of 8-bit or 16-bit characters or a fixed-length
/// array of elements. If dwValueType is set to CERT_RDN_ENCODED_BLOB, pbData is encoded.
///
///
public CRYPTOAPI_BLOB Value;
}
///
/// Contains parameters used to check for strong signatures on certificates, certificate revocation lists (CRLs), online certificate
/// status protocol (OCSP) responses, and PKCS #7 messages.
///
///
/// The parameters needed to check for a strong signature include the following:
///
/// -
/// Name of the public (asymmetric) algorithm
///
/// -
/// Size, in bits, of the public key
///
/// -
/// Name of the signature algorithm
///
/// -
/// Name of the hashing algorithm
///
///
///
/// The value you specify for the dwInfoChoice member of this structure chooses whether the parameters are transmitted as
/// serialized strings or are predefined by using an object identifier.
///
/// The CERT_STRONG_SIGN_PARA structure is directly referenced by the following functions:
///
/// -
/// CertIsStrongHashToSign
///
/// -
/// CryptMsgControl
///
/// -
/// CryptMsgVerifyCountersignatureEncodedEx
///
///
///
/// The CERT_STRONG_SIGN_PARA structure is also directly referenced by the CRYPT_VERIFY_MESSAGE_PARA structure and is
/// therefore available for use by the following functions:
///
///
/// -
/// CryptDecodeMessage
///
/// -
/// CryptDecryptAndVerifyMessageSignature
///
/// -
/// CryptVerifyDetachedMessageSignature
///
/// -
/// CryptVerifyMessageSignature
///
///
///
/// Finally, the CERT_STRONG_SIGN_PARA structure is directly referenced by the CERT_CHAIN_PARA structure and is therefore
/// available for use by the following functions:
///
///
/// -
/// CertGetCertificateChain
///
/// -
/// CertSelectCertificateChains
///
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_strong_sign_para typedef struct
// _CERT_STRONG_SIGN_PARA { DWORD cbSize; DWORD dwInfoChoice; union { void *pvInfo; PCERT_STRONG_SIGN_SERIALIZED_INFO
// pSerializedInfo; LPSTR pszOID; } DUMMYUNIONNAME; } CERT_STRONG_SIGN_PARA, *PCERT_STRONG_SIGN_PARA;
[PInvokeData("wincrypt.h", MSDNShortId = "12D9F82C-F484-43B0-BD55-F07321058671")]
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public struct CERT_STRONG_SIGN_PARA
{
/// Size, in bytes, of this structure.
[FieldOffset(0)]
public uint cbSize;
///
/// Indicates which nested union member points to the strong signature information. This can be one of the following values:
///
///
/// Value
/// Description
///
/// -
/// CERT_STRONG_SIGN_SERIALIZED_INFO_CHOICE
/// Specifies the pSerializedInfo member.
///
/// -
/// CERT_STRONG_SIGN_OID_INFO_CHOICE
/// Specifies the pszOID member.
///
///
///
[FieldOffset(4)]
public CERT_INFO_CHOICE dwInfoChoice;
/// Reserved.
[FieldOffset(8)]
public IntPtr pvInfo;
/// Pointer to a CERT_STRONG_SIGN_SERIALIZED_INFO structure that specifies the parameters.
[FieldOffset(8)]
public IntPtr pSerializedInfo;
///
///
/// Pointer to a string that contains an object identifier (OID) that represents predefined parameters that can be used for
/// strong signature checking. This can be one of the following values:
///
///
///
/// Value
/// Meaning
///
/// -
/// szOID_CERT_STRONG_SIGN_OS_1 "1.3.6.1.4.1.311.72.1.1"
///
/// The SHA2 hash algorithm is supported. MD2, MD4, MD5, and SSHA1 are not supported. The signing and public key algorithms can
/// be RSA or ECDSA. The DSA algorithm is not supported. The key size for the RSA algorithm must equal or be greater than 2047
/// bits. The key size for the ECDSA algorithm must equal or be greater than 256 bits. Strong signing of CRLs and OCSP responses
/// are enabled.
///
///
/// -
/// szOID_CERT_STRONG_KEY_OS_1 "1.3.6.1.4.1.311.72.2.1"
///
/// SHA1 and SHA2 hashes are supported. MD2, MD4, and MD5 are not. The signing and public key algorithms can be RSA or ECDSA.
/// The DSA algorithm is not supported. The key size for the RSA algorithm must equal or be greater than 2047 bits. The key size
/// for the ECDSA algorithm must equal or be greater than 256 bits. Strong signing of CRLs and OCSP responses are enabled.
///
///
///
///
[FieldOffset(8)]
public StrPtrAnsi pszOID;
}
///
/// The CERT_TRUST_STATUS structure contains trust information about a certificate in a certificate chain, summary trust
/// information about a simple chain of certificates, or summary information about an array of simple chains.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/wincrypt/ns-wincrypt-_cert_trust_status typedef struct _CERT_TRUST_STATUS {
// DWORD dwErrorStatus; DWORD dwInfoStatus; } CERT_TRUST_STATUS, *PCERT_TRUST_STATUS;
[PInvokeData("wincrypt.h", MSDNShortId = "af1e1db2-7b53-4491-8317-4abf3568fb03")]
[StructLayout(LayoutKind.Sequential)]
public struct CERT_TRUST_STATUS
{
///
/// The following error status codes are defined for certificates and chains.
///
///
/// Value
/// Meaning
///
/// -
/// CERT_TRUST_NO_ERROR 0x00000000
/// No error found for this certificate or chain.
///
/// -
/// CERT_TRUST_IS_NOT_TIME_VALID 0x00000001
/// This certificate or one of the certificates in the certificate chain is not time valid.
///
/// -
/// CERT_TRUST_IS_REVOKED 0x00000004
/// Trust for this certificate or one of the certificates in the certificate chain has been revoked.
///
/// -
/// CERT_TRUST_IS_NOT_SIGNATURE_VALID 0x00000008
/// The certificate or one of the certificates in the certificate chain does not have a valid signature.
///
/// -
/// CERT_TRUST_IS_NOT_VALID_FOR_USAGE 0x00000010
/// The certificate or certificate chain is not valid for its proposed usage.
///
/// -
/// CERT_TRUST_IS_UNTRUSTED_ROOT 0x00000020
/// The certificate or certificate chain is based on an untrusted root.
///
/// -
/// CERT_TRUST_REVOCATION_STATUS_UNKNOWN 0x00000040
/// The revocation status of the certificate or one of the certificates in the certificate chain is unknown.
///
/// -
/// CERT_TRUST_IS_CYCLIC 0x00000080
/// One of the certificates in the chain was issued by a certification authority that the original certificate had certified.
///
/// -
/// CERT_TRUST_INVALID_EXTENSION 0x00000100
/// One of the certificates has an extension that is not valid.
///
/// -
/// CERT_TRUST_INVALID_POLICY_CONSTRAINTS 0x00000200
///
/// The certificate or one of the certificates in the certificate chain has a policy constraints extension, and one of the
/// issued certificates has a disallowed policy mapping extension or does not have a required issuance policies extension.
///
///
/// -
/// CERT_TRUST_INVALID_BASIC_CONSTRAINTS 0x00000400
///
/// The certificate or one of the certificates in the certificate chain has a basic constraints extension, and either the
/// certificate cannot be used to issue other certificates, or the chain path length has been exceeded.
///
///
/// -
/// CERT_TRUST_INVALID_NAME_CONSTRAINTS 0x00000800
/// The certificate or one of the certificates in the certificate chain has a name constraints extension that is not valid.
///
/// -
/// CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT 0x00001000
///
/// The certificate or one of the certificates in the certificate chain has a name constraints extension that contains
/// unsupported fields. The minimum and maximum fields are not supported. Thus minimum must always be zero and maximum must
/// always be absent. Only UPN is supported for an Other Name. The following alternative name choices are not supported:
///
///
/// -
/// CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT 0x00002000
///
/// The certificate or one of the certificates in the certificate chain has a name constraints extension and a name constraint
/// is missing for one of the name choices in the end certificate.
///
///
/// -
/// CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT 0x00004000
///
/// The certificate or one of the certificates in the certificate chain has a name constraints extension, and there is not a
/// permitted name constraint for one of the name choices in the end certificate.
///
///
/// -
/// CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT 0x00008000
///
/// The certificate or one of the certificates in the certificate chain has a name constraints extension, and one of the name
/// choices in the end certificate is explicitly excluded.
///
///
/// -
/// CERT_TRUST_IS_OFFLINE_REVOCATION 0x01000000
///
/// The revocation status of the certificate or one of the certificates in the certificate chain is either offline or stale.
///
///
/// -
/// CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY 0x02000000
///
/// The end certificate does not have any resultant issuance policies, and one of the issuing certification authority
/// certificates has a policy constraints extension requiring it.
///
///
/// -
/// CERT_TRUST_IS_EXPLICIT_DISTRUST 0x04000000
/// The certificate is explicitly distrusted. Windows Vista and Windows Server 2008: Support for this flag begins.
///
/// -
/// CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT 0x08000000
///
/// The certificate does not support a critical extension. Windows Vista and Windows Server 2008: Support for this flag begins.
///
///
/// -
/// CERT_TRUST_HAS_WEAK_SIGNATURE 0x00100000
///
/// The certificate has not been strong signed. Typically this indicates that the MD2 or MD5 hashing algorithms were used to
/// create a hash of the certificate. Windows 8 and Windows Server 2012: Support for this flag begins.
///
///
///
/// The following codes are defined for chains only.
///
///
/// Value
/// Meaning
///
/// -
/// CERT_TRUST_IS_PARTIAL_CHAIN 0x00010000
/// The certificate chain is not complete.
///
/// -
/// CERT_TRUST_CTL_IS_NOT_TIME_VALID 0x00020000
/// A certificate trust list (CTL) used to create this chain was not time valid.
///
/// -
/// CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID 0x00040000
/// A CTL used to create this chain did not have a valid signature.
///
/// -
/// CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE 0x00080000
/// A CTL used to create this chain is not valid for this usage.
///
///
///
public uint dwErrorStatus;
///
/// The following information status codes are defined.
///
///
/// Value
/// Meaning
///
/// -
/// CERT_TRUST_HAS_EXACT_MATCH_ISSUER 0x00000001
/// An exact match issuer certificate has been found for this certificate. This status code applies to certificates only.
///
/// -
/// CERT_TRUST_HAS_KEY_MATCH_ISSUER 0x00000002
/// A key match issuer certificate has been found for this certificate. This status code applies to certificates only.
///
/// -
/// CERT_TRUST_HAS_NAME_MATCH_ISSUER 0x00000004
/// A name match issuer certificate has been found for this certificate. This status code applies to certificates only.
///
/// -
/// CERT_TRUST_IS_SELF_SIGNED 0x00000008
/// This certificate is self-signed. This status code applies to certificates only.
///
/// -
/// CERT_TRUST_HAS_PREFERRED_ISSUER 0x00000100
/// The certificate or chain has a preferred issuer. This status code applies to certificates and chains.
///
/// -
/// CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY 0x00000400
/// An issuance chain policy exists. This status code applies to certificates and chains.
///
/// -
/// CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS 0x00000400
/// A valid name constraints for all namespaces, including UPN. This status code applies to certificates and chains.
///
/// -
/// CERT_TRUST_IS_PEER_TRUSTED 0x00000800
///
/// This certificate is peer trusted. This status code applies to certificates only. Windows Vista and Windows Server 2008:
/// Support for this flag begins.
///
///
/// -
/// CERT_TRUST_HAS_CRL_VALIDITY_EXTENDED 0x00001000
///
/// This certificate's certificate revocation list (CRL) validity has been extended. This status code applies to certificates
/// only. Windows Vista and Windows Server 2008: Support for this flag begins.
///
///
/// -
/// CERT_TRUST_IS_FROM_EXCLUSIVE_TRUST_STORE 0x00002000
///
/// The certificate was found in either a store pointed to by the hExclusiveRoot or hExclusiveTrustedPeople member of the
/// CERT_CHAIN_ENGINE_CONFIG structure. Windows 7 and Windows Server 2008 R2: Support for this flag begins.
///
///
/// -
/// CERT_TRUST_IS_COMPLEX_CHAIN 0x00010000
/// The certificate chain created is a complex chain. This status code applies to chains only.
///
/// -
/// CERT_TRUST_IS_CA_TRUSTED 0x00004000
///
/// A non-self-signed intermediate CA certificate was found in the store pointed to by the hExclusiveRoot member of the
/// CERT_CHAIN_ENGINE_CONFIG structure. The CA certificate is treated as a trust anchor for the certificate chain. This flag
/// will only be set if the CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG value is set in the dwExclusiveFlags member of the
/// CERT_CHAIN_ENGINE_CONFIG structure. If this flag is set, the CERT_TRUST_IS_SELF_SIGNED and the
/// CERT_TRUST_IS_PARTIAL_CHAINdwErrorStatus flags will not be set. Windows 8 and Windows Server 2012: Support for this flag begins.
///
///
///
///
public uint dwInfoStatus;
}
///
/// The CRL_CONTEXT structure contains both the encoded and decoded representations of a certificate revocation list (CRL).
/// CRL contexts returned by any CryptoAPI function must be freed by calling the CertFreeCRLContext function.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crl_context typedef struct _CRL_CONTEXT { DWORD
// dwCertEncodingType; BYTE *pbCrlEncoded; DWORD cbCrlEncoded; PCRL_INFO pCrlInfo; HCERTSTORE hCertStore; } CRL_CONTEXT, *PCRL_CONTEXT;
[PInvokeData("wincrypt.h", MSDNShortId = "cf7cabcd-b469-492a-b855-8870465ea1cc")]
[StructLayout(LayoutKind.Sequential)]
public struct CRL_CONTEXT
{
///
///
/// Type of encoding used. It is always acceptable to specify both the certificate and message encoding types by combining them
/// with a bitwise- OR operation as shown in the following example:
///
/// X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
/// Currently defined encoding types are:
///
/// -
/// X509_ASN_ENCODING
///
/// -
/// PKCS_7_ASN_ENCODING
///
///
///
public CertEncodingType dwCertEncodingType;
/// A pointer to the encoded CRL information.
public IntPtr pbCrlEncoded;
/// The size, in bytes, of the encoded CRL information.
public uint cbCrlEncoded;
/// A pointer to CRL_INFO structure containing the CRL information.
public IntPtr pCrlInfo;
/// A handle to the certificate store.
public HCERTSTORE hCertStore;
/// A pointer to CRL_INFO structure containing the CRL information.
public unsafe CRL_INFO* pUnsafeCrlInfo => (CRL_INFO*)(void*)pCrlInfo;
}
///
/// The CRL_ENTRY structure contains information about a single revoked certificate. It is a member of a CRL_INFO structure.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crl_entry typedef struct _CRL_ENTRY { CRYPT_INTEGER_BLOB
// SerialNumber; FILETIME RevocationDate; DWORD cExtension; PCERT_EXTENSION rgExtension; } CRL_ENTRY, *PCRL_ENTRY;
[PInvokeData("wincrypt.h", MSDNShortId = "30e7952a-a408-404f-9058-8197539387f6")]
[StructLayout(LayoutKind.Sequential)]
public struct CRL_ENTRY
{
///
/// A BLOB that contains the serial number of a revoked certificate.
/// Leading 0x00 or 0xFF bytes are removed. For more information, see CertCompareIntegerBlob.
///
public CRYPTOAPI_BLOB SerialNumber;
///
/// Date that the certificate was revoked. Time is UTC-time encoded as an eight-byte date/time precise to seconds with a two
/// digit year (that is, YYMMDDHHMMSS plus 2 bytes). The date is interpreted as a date between the years 1968 and 2067.
///
public FILETIME RevocationDate;
/// Number of elements in the rgExtension member array of extensions.
public uint cExtension;
/// Array of pointers to CERT_EXTENSION structures, each providing information about the revoked certificate.
public IntPtr rgExtension;
}
/// The CRL_INFO structure contains the information of a certificate revocation list (CRL).
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crl_info typedef struct _CRL_INFO { DWORD dwVersion;
// CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; CERT_NAME_BLOB Issuer; FILETIME ThisUpdate; FILETIME NextUpdate; DWORD cCRLEntry;
// PCRL_ENTRY rgCRLEntry; DWORD cExtension; PCERT_EXTENSION rgExtension; } CRL_INFO, *PCRL_INFO;
[PInvokeData("wincrypt.h", MSDNShortId = "06a28de3-dd7c-4efe-9baa-20aac69d63f3")]
[StructLayout(LayoutKind.Sequential)]
public struct CRL_INFO
{
///
/// Version number of the CRL. Currently defined version numbers are shown in the following table.
///
///
/// Value
/// Meaning
///
/// -
/// CRL_V1
/// version 1
///
/// -
/// CRL_V2
/// version 2
///
///
///
public uint dwVersion;
///
/// CRYPT_ALGORITHM_IDENTIFIER structure that contains the object identifier (OID) of a signature algorithm and any associated
/// additional parameters.
///
public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;
/// A BLOB structure that contains an encoded certificate issuer's name.
public CRYPTOAPI_BLOB Issuer;
///
/// Indication of the date and time of the CRL's published. If the time is after 1950 and before 2050, it is UTC-time encoded as
/// an 8-byte date/time precise to seconds with a 2-digit year (that is, YYMMDDHHMMSS plus 2 bytes). Otherwise, it is
/// generalized-time encoded as an 8-byte year precise to milliseconds with a 4-byte year.
///
public FILETIME ThisUpdate;
///
/// Indication of the date and time for the CRL's next available scheduled update. If the time is after 1950 and before 2050, it
/// is UTC-time encoded as an 8-byte date/time precise to seconds with a 2-digit year (that is, YYMMDDHHMMSS plus 2 bytes).
/// Otherwise, it is generalized-time encoded as an 8-byte date time precise to milliseconds with a 4-byte year.
///
public FILETIME NextUpdate;
/// Number of elements in the rgCRLEntry array.
public uint cCRLEntry;
/// Array of pointers to CRL_ENTRY structures. Each of these structures represents a revoked certificate.
public IntPtr rgCRLEntry;
/// Number of elements in the rgExtension array.
public uint cExtension;
/// Array of pointers to CERT_EXTENSION structures, each holding information about the CRL.
public IntPtr rgExtension;
}
///
/// The CRYPT_ALGORITHM_IDENTIFIER structure specifies an algorithm used to encrypt a private key. The structure includes the object
/// identifier (OID) of the algorithm and any needed parameters for that algorithm. The parameters contained in its CRYPT_OBJID_BLOB
/// are encoded.
///
[PInvokeData("wincrypt.h")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CRYPT_ALGORITHM_IDENTIFIER
{
/// An OID of an algorithm.
public StrPtrAnsi pszObjId;
///
/// A BLOB that provides encoded algorithm-specific parameters. In many cases, there are no parameters. This is indicated by
/// setting the cbData member of the Parameters BLOB to zero.
///
public CRYPTOAPI_BLOB Parameters;
}
/// The CRYPT_ATTRIBUTE structure specifies an attribute that has one or more values.
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crypt_attribute typedef struct _CRYPT_ATTRIBUTE { LPSTR
// pszObjId; DWORD cValue; PCRYPT_ATTR_BLOB rgValue; } CRYPT_ATTRIBUTE, *PCRYPT_ATTRIBUTE;
[PInvokeData("wincrypt.h", MSDNShortId = "cdbaf38d-ddbe-4be0-afbc-f8bd76ef4847")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_ATTRIBUTE
{
/// An object identifier (OID) that specifies the type of data contained in the rgValue array.
public StrPtrAnsi pszObjId;
/// A DWORD value that indicates the number of elements in the rgValue array.
public uint cValue;
///
/// Pointer to an array of CRYPT_INTEGER_BLOB structures. The cbData member of the CRYPT_INTEGER_BLOB structure
/// indicates the length of the pbData member. The pbData member contains the attribute information.
///
public IntPtr rgValue;
}
///
/// The CRYPT_ATTRIBUTE_TYPE_VALUE structure contains a single attribute value. The Value member's CRYPT_OBJID_BLOB is encoded.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/wincrypt/ns-wincrypt-_crypt_attribute_type_value typedef struct
// _CRYPT_ATTRIBUTE_TYPE_VALUE { LPSTR pszObjId; CRYPT_OBJID_BLOB Value; } CRYPT_ATTRIBUTE_TYPE_VALUE, *PCRYPT_ATTRIBUTE_TYPE_VALUE;
[PInvokeData("wincrypt.h", MSDNShortId = "84057581-d0a9-464a-9399-ba806e37516f")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_ATTRIBUTE_TYPE_VALUE
{
/// Object identifier (OID) that specifies the attribute type data contained in the Value BLOB.
public StrPtrAuto pszObjId;
///
/// A CRYPT_OBJID_BLOB that contains the encoded attribute. The cbData member of the CRYPT_OBJID_BLOB structure
/// indicates the length of the pbData member. The pbData member contains the attribute information.
///
public CRYPTOAPI_BLOB Value;
}
/// The CRYPT_BIT_BLOB structure contains a set of bits represented by an array of bytes.
///
/// Because the smallest chunk of memory that can normally be allocated is a byte, the CRYPT_BIT_BLOB structure allows the
/// last byte in the array to contain zero to seven unused bits. The number of unused bits in the array is contained in the
/// cUnusedBits member of this structure. The number of meaningful bits in the pbData member is calculated with the
/// formula (( cbData × 8) – cUnusedBits). For example, if you need to represent 10 bits, you would allocate an array
/// of 2 bytes and set cUnusedBits to 6. If you view the array as contiguous bits from left to right, the left 10 bits would
/// be meaningful, and the right 6 bits would be unused.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crypt_bit_blob typedef struct _CRYPT_BIT_BLOB { DWORD
// cbData; BYTE *pbData; DWORD cUnusedBits; } CRYPT_BIT_BLOB, *PCRYPT_BIT_BLOB;
[PInvokeData("wincrypt.h", MSDNShortId = "NS:wincrypt._CRYPT_BIT_BLOB")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_BIT_BLOB
{
/// The number of bytes in the pbData array.
public uint cbData;
/// A pointer to an array of bytes that represents the bits.
public IntPtr pbData;
///
/// The number of unused bits in the last byte of the array. The unused bits are always the least significant bits in the last
/// byte of the array.
///
public uint cUnusedBits;
}
///
/// The CRYPT_KEY_PROV_INFO structure contains information about a key container within a cryptographic service provider (CSP).
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crypt_key_prov_info typedef struct _CRYPT_KEY_PROV_INFO {
// LPWSTR pwszContainerName; LPWSTR pwszProvName; DWORD dwProvType; DWORD dwFlags; DWORD cProvParam; PCRYPT_KEY_PROV_PARAM
// rgProvParam; DWORD dwKeySpec; } CRYPT_KEY_PROV_INFO, *PCRYPT_KEY_PROV_INFO;
[PInvokeData("wincrypt.h", MSDNShortId = "6aea2f47-9d4a-4069-ac6d-f28907df00be")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_KEY_PROV_INFO
{
///
/// A pointer to a null-terminated Unicode string that contains the name of the key container.
///
/// When the dwProvType member is zero, this string contains the name of a key within a CNG key storage provider. This
/// string is passed as the pwszKeyName parameter to the NCryptOpenKey function.
///
///
[MarshalAs(UnmanagedType.LPWStr)] public string pwszContainerName;
///
/// A pointer to a null-terminated Unicode string that contains the name of the CSP.
///
/// When the dwProvType member is zero, this string contains the name of a CNG key storage provider. This string is
/// passed as the pwszProviderName parameter to the NCryptOpenStorageProvider function.
///
///
[MarshalAs(UnmanagedType.LPWStr)] public string pwszProvName;
///
/// Specifies the CSP type. This can be zero or one of the Cryptographic Provider Types.
/// If this member is zero, the key container is one of the CNG key storage providers.
///
public uint dwProvType;
///
/// A set of flags that indicate additional information about the provider. This can be zero or one of the following values.
///
///
/// Value
/// Meaning
///
/// -
/// CERT_SET_KEY_PROV_HANDLE_PROP_ID / CERT_SET_KEY_CONTEXT_PROP_ID
/// Enables the handle to the key provider to be kept open for subsequent calls to the cryptographic functions.
///
/// -
/// CRYPT_MACHINE_KEYSET / NCRYPT_MACHINE_KEY_FLAG
/// The key container contains machine keys. If this flag is not present, the key container contains user keys.
///
/// -
/// CRYPT_SILENT / NCRYPT_SILENT_FLAG
/// The key container will attempt to open any keys silently without any user interface prompts.
///
///
///
/// The cryptographic functions CryptDecryptMessage, CryptSignMessage, CryptDecryptAndVerifyMessageSignature, and
/// CryptSignAndEncryptMessage internally perform CryptAcquireContext operations using the CRYPT_KEY_PROV_INFO from a
/// certificate. When the CERT_SET_KEY_CONTEXT_PROP_ID or CERT_SET_KEY_PROV_HANDLE_PROP_ID flag is set, these
/// cryptographic functions then can call CertSetCertificateContextProperty with CERT_KEY_CONTEXT_PROP_ID. This call
/// enables the handle to the key provider to be kept open for subsequent calls to the cryptographic functions mentioned that
/// use that same certificate, which eliminates the need to perform additional calls to CryptAcquireContext, improving
/// efficiency. Also, because some providers can require that a password be entered for calls to CryptAcquireContext, it
/// is desirable for applications to minimize the number of CryptAcquireContext calls made. Handles to key providers that
/// were kept open are automatically released when the store is closed.
///
///
/// For example, consider an email application where five encrypted messages have been received, all encrypted with the public
/// key from the same certificate. If the handle to the key provider is kept open after the first message is processed, calls to
/// CryptAcquireContext are not required for the four remaining messages.
///
///
public uint dwFlags;
///
/// The number of elements in the rgProvParam array.
/// When the dwProvType member is zero, this member is not used and must be zero.
///
public uint cProvParam;
///
///
/// An array of CRYPT_KEY_PROV_PARAM structures that contain the parameters for the key container. The cProvParam member
/// contains the number of elements in this array.
///
/// When the dwProvType member is zero, this member is not used and must be NULL.
///
public IntPtr rgProvParam;
///
/// The specification of the private key to retrieve.
/// The following values are defined for the default provider.
///
/// When the dwProvType member is zero, this value is passed as the dwLegacyKeySpec parameter to the NCryptOpenKey function.
///
///
///
/// Value
/// Meaning
///
/// -
/// AT_KEYEXCHANGE
/// Keys used to encrypt/decrypt session keys.
///
/// -
/// AT_SIGNATURE
/// Keys used to create and verify digital signatures.
///
///
///
public CertKeySpec dwKeySpec;
}
///
/// The CRYPT_TIMESTAMP_ACCURACY structure is used by the CRYPT_TIMESTAMP_INFO structure to represent the accuracy of the
/// time deviation around the UTC time at which the time stamp token was created by the Time Stamp Authority (TSA).
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crypt_timestamp_accuracy typedef struct
// _CRYPT_TIMESTAMP_ACCURACY { DWORD dwSeconds; DWORD dwMillis; DWORD dwMicros; } CRYPT_TIMESTAMP_ACCURACY, *PCRYPT_TIMESTAMP_ACCURACY;
[PInvokeData("wincrypt.h", MSDNShortId = "9115db8a-7cc1-4360-b89b-6c33ddb67fe9")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_TIMESTAMP_ACCURACY
{
///
/// Optional. Specifies, in seconds, the accuracy of the upper limit of the time at which the time stamp token was created by
/// the TSA.
///
public uint dwSeconds;
///
/// Optional. Specifies, in milliseconds, the accuracy of the upper limit of the time at which the time stamp token was created
/// by the TSA.
///
public uint dwMillis;
///
/// Optional. Specifies, in microseconds, the accuracy of the upper limit of the time at which the time-stamp token was created
/// by the TSA.
///
public uint dwMicros;
}
///
/// The CRYPT_TIMESTAMP_CONTEXT structure contains both the encoded and decoded representations of a time stamp token.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crypt_timestamp_context typedef struct
// _CRYPT_TIMESTAMP_CONTEXT { DWORD cbEncoded; BYTE *pbEncoded; PCRYPT_TIMESTAMP_INFO pTimeStamp; } CRYPT_TIMESTAMP_CONTEXT, *PCRYPT_TIMESTAMP_CONTEXT;
[PInvokeData("wincrypt.h", MSDNShortId = "2831b2a9-0f84-4e41-a666-5903fc882965")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_TIMESTAMP_CONTEXT
{
/// The size, in bytes, of the buffer pointed to by the pbEncoded member.
public uint cbEncoded;
///
/// A pointer to a buffer that contains an Abstract Syntax Notation One (ASN.1) encoded content information sequence. This value
/// should be stored for future time stamp validations on the signature. Applications can use the CertOpenStore function with
/// the CERT_STORE_PROV_PKCS7 flag to find additional certificates or certificate revocation lists (CRLs) related to the
/// TSA time stamp signature.
///
public IntPtr pbEncoded;
///
/// A pointer to a CRYPT_TIMESTAMP_INFO structure that contains a signed data content type in Cryptographic Message Syntax (CMS) format.
///
public IntPtr pTimeStamp;
}
///
/// The CRYPT_TIMESTAMP_INFO structure contains a signed data content type in Cryptographic Message Syntax (CMS) format.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crypt_timestamp_info typedef struct _CRYPT_TIMESTAMP_INFO
// { DWORD dwVersion; LPSTR pszTSAPolicyId; CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm; CRYPT_DER_BLOB HashedMessage;
// CRYPT_INTEGER_BLOB SerialNumber; FILETIME ftTime; PCRYPT_TIMESTAMP_ACCURACY pvAccuracy; BOOL fOrdering; CRYPT_DER_BLOB Nonce;
// CRYPT_DER_BLOB Tsa; DWORD cExtension; PCERT_EXTENSION rgExtension; } CRYPT_TIMESTAMP_INFO, *PCRYPT_TIMESTAMP_INFO;
[PInvokeData("wincrypt.h", MSDNShortId = "05ca0877-5e9d-4b21-9fca-a1eef2cb4626")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_TIMESTAMP_INFO
{
///
/// A DWORD value that specifies the version of the time stamp request.
///
///
/// Value
/// Meaning
///
/// -
/// TIMESTAMP_VERSION 1
/// Specifies that this is a version 1 time stamp request.
///
///
///
public uint dwVersion;
///
/// Optional. A pointer to a null-terminated string that specifies the Time Stamping Authority (TSA) policy under which the time
/// stamp token was provided. This value must correspond with the value passed in the CRYPT_TIMESTAMP_REQUEST structure.
///
public StrPtrAnsi pszTSAPolicyId;
///
/// A CRYPT_ALGORITHM_IDENTIFIER structure that contains information about the algorithm used to calculate the hash. This value
/// must correspond with the value passed in the CRYPT_TIMESTAMP_REQUEST structure.
///
public CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
/// A CRYPT_DER_BLOB structure that specifies the hash values to be time stamped.
public CRYPTOAPI_BLOB HashedMessage;
/// A CRYPT_INTEGER_BLOB structure that contains the serial number assigned by the TSA to each time stamp token.
public CRYPTOAPI_BLOB SerialNumber;
/// A FILETIME value that specifies the time at which the time stamp token was produced by the TSA.
public FILETIME ftTime;
///
/// Optional. A pointer to a CRYPT_TIMESTAMP_ACCURACY structure that contains the time deviation around the UTC time at which
/// the time stamp token was created by the TSA.
///
public IntPtr pvAccuracy;
/// This member is reserved.
[MarshalAs(UnmanagedType.Bool)] public bool fOrdering;
///
/// Optional. A CRYPT_DER_BLOB structure that contains the nonce value used by the client to verify the timeliness of the
/// response when no local clock is available. This value must correspond with the value passed in the CRYPT_TIMESTAMP_REQUEST structure.
///
public CRYPTOAPI_BLOB Nonce;
/// Optional. A CRYPT_DER_BLOB structure that contains the subject name of the TSA certificate.
public CRYPTOAPI_BLOB Tsa;
/// The number of elements in the array pointed to by the rgExtension member.
public uint cExtension;
/// A pointer to an array of CERT_EXTENSION structures that contain extension information returned from the request.
public IntPtr rgExtension;
}
/// The CRYPT_TIMESTAMP_PARA structure defines additional parameters for the time stamp request.
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-crypt_timestamp_para typedef struct _CRYPT_TIMESTAMP_PARA
// { LPCSTR pszTSAPolicyId; BOOL fRequestCerts; CRYPT_INTEGER_BLOB Nonce; DWORD cExtension; PCERT_EXTENSION rgExtension; }
// CRYPT_TIMESTAMP_PARA, *PCRYPT_TIMESTAMP_PARA;
[PInvokeData("wincrypt.h", MSDNShortId = "26a6e9d3-b35e-47ae-9cea-a37ca6297c28")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_TIMESTAMP_PARA
{
///
/// Optional. A pointer to a null-terminated character string that contains the Time Stamping Authority (TSA) policy under which
/// the time stamp token should be provided.
///
public StrPtrAnsi pszTSAPolicyId;
///
/// A Boolean value that specifies whether the TSA must include the certificates used to sign the time stamp token in the
/// response .
///
[MarshalAs(UnmanagedType.Bool)] public bool fRequestCerts;
///
/// Optional. A CRYPT_INTEGER_BLOB structure that contains the nonce value used by the client to verify the timeliness of the
/// response when no local clock is available.
///
public CRYPTOAPI_BLOB Nonce;
/// The number of elements in the array pointed to by the rgExtension member.
public uint cExtension;
///
/// A pointer to an array of CERT_EXTENSION structures that contain extension information that is passed in the request.
///
public IntPtr rgExtension;
}
///
/// The BLOB structure contains an arbitrary array of bytes. The structure definition includes aliases appropriate to the various
/// functions that use it.
///
[PInvokeData("wincrypt.h")]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPTOAPI_BLOB
{
/// Initializes a new instance of the struct with default values.
/// A pointer to the data buffer.
/// The count, in bytes, of .
public CRYPTOAPI_BLOB(IntPtr data, SizeT size) { pbData = data; cbData = size; }
///
/// Initializes a new instance of the struct from a instance.
///
/// The allocated memory instance.
public CRYPTOAPI_BLOB(SafeAllocatedMemoryHandle mem) { pbData = mem?.DangerousGetHandle() ?? default; cbData = mem?.Size ?? 0; }
/// A DWORD variable that contains the count, in bytes, of data.
public uint cbData;
/// A pointer to the data buffer.
public IntPtr pbData;
/// Gets the bytes associated with this blob.
public byte[] GetBytes() => pbData.ToArray((int)cbData);
}
///
///
/// The CTL_CONTEXT structure contains both the encoded and decoded representations of a CTL. It also contains an opened
/// HCRYPTMSG handle to the decoded, cryptographically signed message containing the CTL_INFO as its inner content.
///
/// CryptoAPI low-level message functions can be used to extract additional signer information.
/// A CTL_CONTEXT returned by any CryptoAPI function must be freed by calling the CertFreeCTLContext function.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-ctl_context typedef struct _CTL_CONTEXT { DWORD
// dwMsgAndCertEncodingType; BYTE *pbCtlEncoded; DWORD cbCtlEncoded; PCTL_INFO pCtlInfo; HCERTSTORE hCertStore; HCRYPTMSG hCryptMsg;
// BYTE *pbCtlContent; DWORD cbCtlContent; } CTL_CONTEXT, *PCTL_CONTEXT;
[PInvokeData("wincrypt.h", MSDNShortId = "780edddf-1b44-4292-9156-4dfd5100adb8")]
[StructLayout(LayoutKind.Sequential)]
public struct CTL_CONTEXT
{
///
///
/// Type of encoding used. It is always acceptable to specify both the certificate and message encoding types by combining them
/// with a bitwise- OR operation as shown in the following example:
///
/// X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
/// Currently defined encoding types are:
///
/// -
/// X509_ASN_ENCODING
///
/// -
/// PKCS_7_ASN_ENCODING
///
///
///
public CertEncodingType dwMsgAndCertEncodingType;
/// A pointer to the encoded CTL.
public IntPtr pbCtlEncoded;
/// The size, in bytes, of the encoded CTL.
public uint cbCtlEncoded;
/// A pointer to CTL_INFO structure contain the CTL information.
public IntPtr pCtlInfo;
/// A handle to the certificate store.
public HCERTSTORE hCertStore;
///
/// Open HCRYPTMSG handle to a decoded, cryptographic-signed message containing the CTL_INFO as its inner content.
///
public HCRYPTMSG hCryptMsg;
/// The encoded inner content of the signed message.
public IntPtr pbCtlContent;
/// Count, in bytes, of pbCtlContent.
public uint cbCtlContent;
/// A pointer to CTL_INFO structure contain the CTL information.
public unsafe CTL_INFO* pUnsafeCtlInfo => (CTL_INFO*)(void*)pCtlInfo;
}
/// The CTL_ENTRY structure is an element of a certificate trust list (CTL).
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-ctl_entry typedef struct _CTL_ENTRY { CRYPT_DATA_BLOB
// SubjectIdentifier; DWORD cAttribute; PCRYPT_ATTRIBUTE rgAttribute; } CTL_ENTRY, *PCTL_ENTRY;
[PInvokeData("wincrypt.h", MSDNShortId = "ebc63847-b641-4205-b15c-7b32c1426c21")]
[StructLayout(LayoutKind.Sequential)]
public struct CTL_ENTRY
{
/// BLOB containing a unique identifier of a subject. It can be a hash or any unique byte sequence.
public CRYPTOAPI_BLOB SubjectIdentifier;
/// Count of elements in the rgAttribute member array.
public uint cAttribute;
/// Array of CRYPT_ATTRIBUTE structures, each holding information about the subject.
public IntPtr rgAttribute;
}
/// The CTL_INFO structure contains the information stored in a Certificate Trust List (CTL).
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-ctl_info typedef struct _CTL_INFO { DWORD dwVersion;
// CTL_USAGE SubjectUsage; CRYPT_DATA_BLOB ListIdentifier; CRYPT_INTEGER_BLOB SequenceNumber; FILETIME ThisUpdate; FILETIME
// NextUpdate; CRYPT_ALGORITHM_IDENTIFIER SubjectAlgorithm; DWORD cCTLEntry; PCTL_ENTRY rgCTLEntry; DWORD cExtension;
// PCERT_EXTENSION rgExtension; } CTL_INFO, *PCTL_INFO;
[PInvokeData("wincrypt.h", MSDNShortId = "83b015b5-a650-4a81-a9f0-c3e8a9805c81")]
[StructLayout(LayoutKind.Sequential)]
public struct CTL_INFO
{
///
/// The CTL's version number. Currently defined version numbers are shown in the following table.
///
///
/// Value
/// Meaning
///
/// -
/// CTL_V1
/// Version 1
///
///
///
public uint dwVersion;
///
/// CTL_USAGE structure identifying the intended usage of the list as a sequence of object identifiers. This is the same as in
/// the Enhanced Key Usage extension.
///
public CTL_USAGE SubjectUsage;
///
/// A CRYPT_DATA_BLOB structure that includes a byte string that uniquely identifies the list. This member is used to augment
/// the SubjectUsage and further specifies the list when desired.
///
public CRYPTOAPI_BLOB ListIdentifier;
/// A BLOB that contains a monotonically increasing number for each update of the CTL.
public CRYPTOAPI_BLOB SequenceNumber;
///
/// Indication of the date and time of the certificate revocation lists (CRLs) published. If the time is after 1950 and before
/// 2050, it is UTC-time encoded as an 8-byte date/time precise to seconds with a 2-digit year (that is, YYMMDDHHMMSS plus 2
/// bytes). Otherwise, it is generalized-time encoded as an 8-byte year precise to milliseconds with a 4-byte year.
///
public FILETIME ThisUpdate;
///
/// Indication of the date and time for the CRL's next available scheduled update. If the time is after 1950 and before 2050, it
/// is UTC-time encoded as an 8-byte date/time precise to seconds with a 2-digit year (that is, YYMMDDHHMMSS plus 2 bytes).
/// Otherwise, it is generalized-time encoded as an 8-byte date time precise to milliseconds with a 4-byte year.
///
public FILETIME NextUpdate;
///
/// CRYPT_ALGORITHM_IDENTIFIER structure that contains the algorithm type of the SubjectIdentifier in CTL_ENTRY members
/// of the rgCTLEntry member array. The structure also includes additional parameters used by the algorithm.
///
public CRYPT_ALGORITHM_IDENTIFIER SubjectAlgorithm;
/// Number of elements in the rgCTLEntry member array.
public uint cCTLEntry;
/// Array of CTL_ENTRY structures.
public IntPtr rgCTLEntry;
/// Number of elements in the rgExtension array.
public uint cExtension;
/// Array of CERT_EXTENSION structures.
public IntPtr rgExtension;
}
///
/// The CTL_USAGE structure contains an array of object identifiers (OIDs) for Certificate Trust List (CTL) extensions.
/// CTL_USAGE structures are used in functions that search for CTLs for specific uses.
///
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-ctl_usage typedef struct _CTL_USAGE { DWORD
// cUsageIdentifier; LPSTR *rgpszUsageIdentifier; } CTL_USAGE, *PCTL_USAGE, CERT_ENHKEY_USAGE, *PCERT_ENHKEY_USAGE;
[PInvokeData("wincrypt.h", MSDNShortId = "70ee138a-df94-4fc4-9de5-0d8b7704b890")]
[StructLayout(LayoutKind.Sequential)]
public struct CTL_USAGE
{
/// Number of elements in the rgpszUsageIdentifier member array.
public uint cUsageIdentifier;
/// Array of object identifiers (OIDs) of CTL extensions.
public IntPtr rgpszUsageIdentifier;
}
/// Provides a handle to a cryptographic default context.
[StructLayout(LayoutKind.Sequential)]
public struct HCRYPTDEFAULTCONTEXT : IHandle
{
private IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public HCRYPTDEFAULTCONTEXT(IntPtr preexistingHandle) => handle = preexistingHandle;
/// Returns an invalid handle by instantiating a object with .
public static HCRYPTDEFAULTCONTEXT NULL => new HCRYPTDEFAULTCONTEXT(IntPtr.Zero);
/// Gets a value indicating whether this instance is a null handle.
public bool IsNull => handle == IntPtr.Zero;
/// Performs an explicit conversion from to .
/// The handle.
/// The result of the conversion.
public static explicit operator IntPtr(HCRYPTDEFAULTCONTEXT h) => h.handle;
/// Performs an implicit conversion from to .
/// The pointer to a handle.
/// The result of the conversion.
public static implicit operator HCRYPTDEFAULTCONTEXT(IntPtr h) => new HCRYPTDEFAULTCONTEXT(h);
/// Implements the operator !=.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator !=(HCRYPTDEFAULTCONTEXT h1, HCRYPTDEFAULTCONTEXT h2) => !(h1 == h2);
/// Implements the operator ==.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator ==(HCRYPTDEFAULTCONTEXT h1, HCRYPTDEFAULTCONTEXT h2) => h1.Equals(h2);
///
public override bool Equals(object obj) => obj is HCRYPTDEFAULTCONTEXT h ? handle == h.handle : false;
///
public override int GetHashCode() => handle.GetHashCode();
///
public IntPtr DangerousGetHandle() => handle;
}
/// Provides a handle to a CryptoApi hash.
[StructLayout(LayoutKind.Sequential)]
public struct HCRYPTHASH : IHandle
{
private readonly IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public HCRYPTHASH(IntPtr preexistingHandle) => handle = preexistingHandle;
/// Returns an invalid handle by instantiating a object with .
public static HCRYPTHASH NULL => new HCRYPTHASH(IntPtr.Zero);
/// Gets a value indicating whether this instance is a null handle.
public bool IsNull => handle == IntPtr.Zero;
/// Performs an explicit conversion from to .
/// The handle.
/// The result of the conversion.
public static explicit operator IntPtr(HCRYPTHASH h) => h.handle;
/// Performs an implicit conversion from to .
/// The pointer to a handle.
/// The result of the conversion.
public static implicit operator HCRYPTHASH(IntPtr h) => new HCRYPTHASH(h);
/// Implements the operator !=.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator !=(HCRYPTHASH h1, HCRYPTHASH h2) => !(h1 == h2);
/// Implements the operator ==.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator ==(HCRYPTHASH h1, HCRYPTHASH h2) => h1.Equals(h2);
///
public override bool Equals(object obj) => obj is HCRYPTHASH h ? handle == h.handle : false;
///
public override int GetHashCode() => handle.GetHashCode();
///
public IntPtr DangerousGetHandle() => handle;
}
/// Provides a handle to a CryptoApi key.
[StructLayout(LayoutKind.Sequential)]
public struct HCRYPTKEY : IHandle
{
private readonly IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public HCRYPTKEY(IntPtr preexistingHandle) => handle = preexistingHandle;
/// Returns an invalid handle by instantiating a object with .
public static HCRYPTKEY NULL => new HCRYPTKEY(IntPtr.Zero);
/// Gets a value indicating whether this instance is a null handle.
public bool IsNull => handle == IntPtr.Zero;
/// Performs an explicit conversion from to .
/// The handle.
/// The result of the conversion.
public static explicit operator IntPtr(HCRYPTKEY h) => h.handle;
/// Performs an implicit conversion from to .
/// The pointer to a handle.
/// The result of the conversion.
public static implicit operator HCRYPTKEY(IntPtr h) => new HCRYPTKEY(h);
/// Implements the operator !=.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator !=(HCRYPTKEY h1, HCRYPTKEY h2) => !(h1 == h2);
/// Implements the operator ==.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator ==(HCRYPTKEY h1, HCRYPTKEY h2) => h1.Equals(h2);
///
public override bool Equals(object obj) => obj is HCRYPTKEY h ? handle == h.handle : false;
///
public override int GetHashCode() => handle.GetHashCode();
///
public IntPtr DangerousGetHandle() => handle;
}
/// Provides a handle to a CryptoAPI provider.
[StructLayout(LayoutKind.Sequential)]
public struct HCRYPTPROV : IHandle
{
private readonly IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public HCRYPTPROV(IntPtr preexistingHandle) => handle = preexistingHandle;
/// Returns an invalid handle by instantiating a object with .
public static HCRYPTPROV NULL => new HCRYPTPROV(IntPtr.Zero);
/// Gets a value indicating whether this instance is a null handle.
public bool IsNull => handle == IntPtr.Zero;
/// Performs an explicit conversion from to .
/// The handle.
/// The result of the conversion.
public static explicit operator IntPtr(HCRYPTPROV h) => h.handle;
/// Performs an implicit conversion from to .
/// The pointer to a handle.
/// The result of the conversion.
public static implicit operator HCRYPTPROV(IntPtr h) => new HCRYPTPROV(h);
/// Implements the operator !=.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator !=(HCRYPTPROV h1, HCRYPTPROV h2) => !(h1 == h2);
/// Implements the operator ==.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator ==(HCRYPTPROV h1, HCRYPTPROV h2) => h1.Equals(h2);
///
public override bool Equals(object obj) => obj is HCRYPTPROV h ? handle == h.handle : false;
///
public override int GetHashCode() => handle.GetHashCode();
///
public IntPtr DangerousGetHandle() => handle;
}
/// Provides a handle to a CERT_CONTEXT.
[StructLayout(LayoutKind.Sequential)]
public struct PCCERT_CONTEXT : IHandle
{
private IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public PCCERT_CONTEXT(IntPtr preexistingHandle) => handle = preexistingHandle;
/// Returns an invalid handle by instantiating a object with .
public static PCCERT_CONTEXT NULL => new PCCERT_CONTEXT(IntPtr.Zero);
/// Gets a value indicating whether this instance is a null handle.
public bool IsNull => handle == IntPtr.Zero;
/// Performs an explicit conversion from to .
/// The handle.
/// The result of the conversion.
public static explicit operator IntPtr(PCCERT_CONTEXT h) => h.handle;
/// Performs an implicit conversion from to .
/// The pointer to a handle.
/// The result of the conversion.
public static implicit operator PCCERT_CONTEXT(IntPtr h) => new PCCERT_CONTEXT(h);
/// Performs an explicit conversion from to .
/// The instance.
/// The resulting instance from the conversion.
public static unsafe explicit operator CERT_CONTEXT*(PCCERT_CONTEXT h) => (CERT_CONTEXT*)(void*)h.handle;
/// Implements the operator !=.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator !=(PCCERT_CONTEXT h1, PCCERT_CONTEXT h2) => !(h1 == h2);
/// Implements the operator ==.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator ==(PCCERT_CONTEXT h1, PCCERT_CONTEXT h2) => h1.Equals(h2);
///
public override bool Equals(object obj) => obj is PCCERT_CONTEXT h ? handle == h.handle : false;
///
public override int GetHashCode() => handle.GetHashCode();
///
public IntPtr DangerousGetHandle() => handle;
}
/// Provides a handle to a CLR_CONTEXT.
[StructLayout(LayoutKind.Sequential)]
public struct PCCRL_CONTEXT : IHandle
{
private IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public PCCRL_CONTEXT(IntPtr preexistingHandle) => handle = preexistingHandle;
/// Returns an invalid handle by instantiating a object with .
public static PCCRL_CONTEXT NULL => new PCCRL_CONTEXT(IntPtr.Zero);
/// Gets a value indicating whether this instance is a null handle.
public bool IsNull => handle == IntPtr.Zero;
/// Performs an explicit conversion from to .
/// The handle.
/// The result of the conversion.
public static explicit operator IntPtr(PCCRL_CONTEXT h) => h.handle;
/// Performs an implicit conversion from to .
/// The pointer to a handle.
/// The result of the conversion.
public static implicit operator PCCRL_CONTEXT(IntPtr h) => new PCCRL_CONTEXT(h);
/// Performs an implicit conversion from to .
/// The instance.
/// The resulting instance from the conversion.
public static unsafe explicit operator CRL_CONTEXT*(PCCRL_CONTEXT h) => (CRL_CONTEXT*)(void*)h.handle;
/// Implements the operator !=.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator !=(PCCRL_CONTEXT h1, PCCRL_CONTEXT h2) => !(h1 == h2);
/// Implements the operator ==.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator ==(PCCRL_CONTEXT h1, PCCRL_CONTEXT h2) => h1.Equals(h2);
///
public override bool Equals(object obj) => obj is PCCRL_CONTEXT h ? handle == h.handle : false;
///
public override int GetHashCode() => handle.GetHashCode();
///
public IntPtr DangerousGetHandle() => handle;
}
/// Provides a handle to a CTL_CONTEXT.
[StructLayout(LayoutKind.Sequential)]
public struct PCCTL_CONTEXT : IHandle
{
private IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public PCCTL_CONTEXT(IntPtr preexistingHandle) => handle = preexistingHandle;
/// Returns an invalid handle by instantiating a object with .
public static PCCTL_CONTEXT NULL => new PCCTL_CONTEXT(IntPtr.Zero);
/// Gets a value indicating whether this instance is a null handle.
public bool IsNull => handle == IntPtr.Zero;
/// Performs an explicit conversion from to .
/// The handle.
/// The result of the conversion.
public static explicit operator IntPtr(PCCTL_CONTEXT h) => h.handle;
/// Performs an implicit conversion from to .
/// The pointer to a handle.
/// The result of the conversion.
public static implicit operator PCCTL_CONTEXT(IntPtr h) => new PCCTL_CONTEXT(h);
/// Performs an explicit conversion from to .
/// The handle.
/// The resulting instance from the conversion.
public static unsafe explicit operator CTL_CONTEXT*(PCCTL_CONTEXT h) => (CTL_CONTEXT*)(void*)h.handle;
/// Implements the operator !=.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator !=(PCCTL_CONTEXT h1, PCCTL_CONTEXT h2) => !(h1 == h2);
/// Implements the operator ==.
/// The first handle.
/// The second handle.
/// The result of the operator.
public static bool operator ==(PCCTL_CONTEXT h1, PCCTL_CONTEXT h2) => h1.Equals(h2);
///
public override bool Equals(object obj) => obj is PCCTL_CONTEXT h ? handle == h.handle : false;
///
public override int GetHashCode() => handle.GetHashCode();
///
public IntPtr DangerousGetHandle() => handle;
}
///
/// The BLOB structure contains an arbitrary array of bytes. The structure definition includes aliases appropriate to the various
/// functions that use it.
///
[PInvokeData("wincrypt.h")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class SafeCRYPTOAPI_BLOB : IDisposable
{
/// A DWORD variable that contains the count, in bytes, of data.
private uint cbData;
/// A pointer to the data buffer.
private IntPtr pbData;
/// Initializes a new instance of the class.
/// The size, in bytes, to allocate.
public SafeCRYPTOAPI_BLOB(int size)
{
cbData = (uint)size;
if (size > 0)
pbData = MemMethods.AllocMem(size);
}
/// Initializes a new instance of the class.
/// The bytes to copy into the blob.
public SafeCRYPTOAPI_BLOB(byte[] bytes) : this(bytes?.Length ?? 0)
{
Marshal.Copy(bytes, 0, pbData, bytes.Length);
}
/// Initializes a new instance of the class with a string.
/// The string value.
/// The character set to use.
public SafeCRYPTOAPI_BLOB(string value, CharSet charSet = CharSet.Unicode) : this(StringHelper.GetBytes(value, true, charSet))
{
}
private SafeCRYPTOAPI_BLOB(IntPtr handle, int size)
{
pbData = handle;
cbData = (uint)size;
}
/// Represents an empty instance of a blob.
public static readonly SafeCRYPTOAPI_BLOB Empty = new SafeCRYPTOAPI_BLOB(IntPtr.Zero, 0);
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public void Dispose()
{
MemMethods.FreeMem(pbData);
pbData = IntPtr.Zero;
cbData = 0;
}
/// Allocates from unmanaged memory sufficient memory to hold an object of type T.
/// Native type
/// The value.
/// object to an native (unmanaged) memory block the size of T.
public static SafeCRYPTOAPI_BLOB CreateFromStructure(in T value = default) => new SafeCRYPTOAPI_BLOB(InteropExtensions.MarshalToPtr(value, MemMethods.AllocMem, out int s), s);
///
/// Allocates from unmanaged memory to represent a structure with a variable length array at the end and marshal these structure
/// elements. It is the callers responsibility to marshal what precedes the trailing array into the unmanaged memory. ONLY
/// structures with attribute StructLayout of LayoutKind.Sequential are supported.
///
/// Type of the trailing array of structures
/// Collection of structure objects
///
/// Number of items in . Setting this value to -1 will cause the method to get the count by iterating
/// through .
///
/// Number of bytes preceding the trailing array of structures
/// object to an native (unmanaged) structure with a trail array of structures
public static SafeCRYPTOAPI_BLOB CreateFromList(IEnumerable values, int count = -1, int prefixBytes = 0) =>
new SafeCRYPTOAPI_BLOB(InteropExtensions.MarshalToPtr(values, MemMethods.AllocMem, out int s, prefixBytes), s);
/// Allocates from unmanaged memory sufficient memory to hold an array of strings.
/// The list of strings.
/// The packing type for the strings.
/// The character set to use for the strings.
/// Number of bytes preceding the trailing strings.
///
/// object to an native (unmanaged) array of strings stored using the model and the character set defined by .
///
public static SafeCRYPTOAPI_BLOB CreateFromStringList(IEnumerable values, StringListPackMethod packing = StringListPackMethod.Concatenated, CharSet charSet = CharSet.Auto, int prefixBytes = 0) =>
new SafeCRYPTOAPI_BLOB(InteropExtensions.MarshalToPtr(values, packing, MemMethods.AllocMem, out int s, charSet, prefixBytes), s);
private static IMemoryMethods MemMethods => HGlobalMemoryMethods.Instance;
}
/// Provides a for an object identifier that can be either a string or an integer.
public class SafeOID : SafeHANDLE
{
/// Initializes a new instance of the class and assigns an existing handle.
/// An object that represents the pre-existing handle to use.
///
/// to reliably release the handle during the finalization phase; otherwise, (not recommended).
///
public SafeOID(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { }
/// Initializes a new instance of the class.
/// The value.
public SafeOID(int value) { SetHandle((IntPtr)unchecked((ushort)value)); }
/// Initializes a new instance of the class.
/// The value.
public SafeOID(uint value) { SetHandle((IntPtr)unchecked((ushort)value)); }
/// Initializes a new instance of the class.
/// The value.
public SafeOID(string value) : base(Marshal.StringToCoTaskMemAnsi(value)) { }
/// Initializes a new instance of the class.
private SafeOID() : base() { }
/// Gets a value indicating whether this instance is string.
/// if this instance is string; otherwise, .
private bool IsString => !Macros.IS_INTRESOURCE(handle);
/// Performs an implicit conversion from to .
/// The value.
/// The resulting instance from the conversion.
public static implicit operator IntPtr(SafeOID value) => value.handle;
/// Performs an implicit conversion from to .
/// The value.
/// The resulting instance from the conversion.
public static implicit operator SafeOID(string value) => new SafeOID(value);
/// Performs an implicit conversion from to .
/// The value.
/// The resulting instance from the conversion.
public static implicit operator SafeOID(int value) => new SafeOID(value);
/// Performs an implicit conversion from to .
/// The value.
/// The resulting instance from the conversion.
public static implicit operator SafeOID(uint value) => new SafeOID(value);
/// Performs an implicit conversion from to .
/// The value.
/// The resulting instance from the conversion.
public static implicit operator StrPtrAnsi(SafeOID value) => value.handle;
/// Gets the integer value, if possible.
/// The integer value, if set; otherwise .
public int? GetInt32Value() => IsString ? null : (int?)handle.ToInt32();
/// Gets the string value, if possible.
/// The string value, if set; otherwise .
public string GetStringValue() => IsString ? Marshal.PtrToStringAnsi(handle) : null;
///
/// Internal method that actually releases the handle. This is called by
/// for valid handles and afterwards zeros the handle.
///
/// true to indicate successful release of the handle; false otherwise.
protected override bool InternalReleaseHandle()
{
if (IsString)
Marshal.FreeCoTaskMem(handle);
handle = IntPtr.Zero;
return true;
}
///
public static readonly SafeOID CRYPT_ENCODE_DECODE_NONE = new SafeOID(0);
//+-------------------------------------------------------------------------
// Predefined X509 certificate data structures that can be encoded / decoded.
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_CERT = new SafeOID(1);
///
public static readonly SafeOID X509_CERT_TO_BE_SIGNED = new SafeOID(2);
///
public static readonly SafeOID X509_CERT_CRL_TO_BE_SIGNED = new SafeOID(3);
///
public static readonly SafeOID X509_CERT_REQUEST_TO_BE_SIGNED = new SafeOID(4);
///
public static readonly SafeOID X509_EXTENSIONS = new SafeOID(5);
///
public static readonly SafeOID X509_NAME_VALUE = new SafeOID(6);
///
public static readonly SafeOID X509_NAME = new SafeOID(7);
///
public static readonly SafeOID X509_PUBLIC_KEY_INFO = new SafeOID(8);
//+-------------------------------------------------------------------------
// Predefined X509 certificate extension data structures that can be
// encoded / decoded.
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_AUTHORITY_KEY_ID = new SafeOID(9);
///
public static readonly SafeOID X509_KEY_ATTRIBUTES = new SafeOID(10);
///
public static readonly SafeOID X509_KEY_USAGE_RESTRICTION = new SafeOID(11);
///
public static readonly SafeOID X509_ALTERNATE_NAME = new SafeOID(12);
///
public static readonly SafeOID X509_BASIC_CONSTRAINTS = new SafeOID(13);
///
public static readonly SafeOID X509_KEY_USAGE = new SafeOID(14);
///
public static readonly SafeOID X509_BASIC_CONSTRAINTS2 = new SafeOID(15);
///
public static readonly SafeOID X509_CERT_POLICIES = new SafeOID(16);
//+-------------------------------------------------------------------------
// Additional predefined data structures that can be encoded / decoded.
//--------------------------------------------------------------------------
///
public static readonly SafeOID PKCS_UTC_TIME = new SafeOID(17);
///
public static readonly SafeOID PKCS_TIME_REQUEST = new SafeOID(18);
///
public static readonly SafeOID RSA_CSP_PUBLICKEYBLOB = new SafeOID(19);
///
public static readonly SafeOID X509_UNICODE_NAME = new SafeOID(20);
///
public static readonly SafeOID X509_KEYGEN_REQUEST_TO_BE_SIGNED = new SafeOID(21);
///
public static readonly SafeOID PKCS_ATTRIBUTE = new SafeOID(22);
///
public static readonly SafeOID PKCS_CONTENT_INFO_SEQUENCE_OF_ANY = new SafeOID(23);
//+-------------------------------------------------------------------------
// Predefined primitive data structures that can be encoded / decoded.
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_UNICODE_NAME_VALUE = new SafeOID(24);
///
public static readonly SafeOID X509_ANY_STRING = X509_NAME_VALUE;
///
public static readonly SafeOID X509_UNICODE_ANY_STRING = X509_UNICODE_NAME_VALUE;
///
public static readonly SafeOID X509_OCTET_STRING = new SafeOID(25);
///
public static readonly SafeOID X509_BITS = new SafeOID(26);
///
public static readonly SafeOID X509_INTEGER = new SafeOID(27);
///
public static readonly SafeOID X509_MULTI_BYTE_INTEGER = new SafeOID(28);
///
public static readonly SafeOID X509_ENUMERATED = new SafeOID(29);
///
public static readonly SafeOID X509_CHOICE_OF_TIME = new SafeOID(30);
//+-------------------------------------------------------------------------
// More predefined X509 certificate extension data structures that can be
// encoded / decoded.
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_AUTHORITY_KEY_ID2 = new SafeOID(31);
///
public static readonly SafeOID X509_AUTHORITY_INFO_ACCESS = new SafeOID(32);
///
public static readonly SafeOID PKCS_CONTENT_INFO = new SafeOID(33);
///
public static readonly SafeOID X509_SEQUENCE_OF_ANY = new SafeOID(34);
///
public static readonly SafeOID X509_CRL_DIST_POINTS = new SafeOID(35);
///
public static readonly SafeOID X509_ENHANCED_KEY_USAGE = new SafeOID(36);
///
public static readonly SafeOID PKCS_CTL = new SafeOID(37);
///
public static readonly SafeOID X509_MULTI_BYTE_UINT = new SafeOID(38);
///
public static readonly SafeOID X509_DSS_PARAMETERS = new SafeOID(39);
///
public static readonly SafeOID X509_DSS_SIGNATURE = new SafeOID(40);
///
public static readonly SafeOID PKCS_RC2_CBC_PARAMETERS = new SafeOID(41);
///
public static readonly SafeOID PKCS_SMIME_CAPABILITIES = new SafeOID(42);
///
public static readonly SafeOID X509_SUBJECT_INFO_ACCESS = X509_AUTHORITY_INFO_ACCESS;
///
public static readonly SafeOID X509_CRL_REASON_CODE = X509_ENUMERATED;
///
public static readonly SafeOID X509_DSS_PUBLICKEY = X509_MULTI_BYTE_UINT;
// Qualified Certificate Statements Extension uses the same encode/decode
// function as PKCS_SMIME_CAPABILITIES. Its data structures are identical
// except for the names of the fields.
///
public static readonly SafeOID X509_QC_STATEMENTS_EXT = new SafeOID(42);
//+-------------------------------------------------------------------------
// data structures for private keys
//--------------------------------------------------------------------------
///
public static readonly SafeOID PKCS_RSA_PRIVATE_KEY = new SafeOID(43);
///
public static readonly SafeOID PKCS_PRIVATE_KEY_INFO = new SafeOID(44);
///
public static readonly SafeOID PKCS_ENCRYPTED_PRIVATE_KEY_INFO = new SafeOID(45);
//+-------------------------------------------------------------------------
// certificate policy qualifier
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_PKIX_POLICY_QUALIFIER_USERNOTICE = new SafeOID(46);
//+-------------------------------------------------------------------------
// Diffie-Hellman Key Exchange
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_DH_PUBLICKEY = X509_MULTI_BYTE_UINT;
///
public static readonly SafeOID X509_DH_PARAMETERS = new SafeOID(47);
///
public static readonly SafeOID PKCS_ATTRIBUTES = new SafeOID(48);
///
public static readonly SafeOID PKCS_SORTED_CTL = new SafeOID(49);
//+-------------------------------------------------------------------------
// ECC Signature
//--------------------------------------------------------------------------
// Uses the same encode/decode function as X509_DH_PARAMETERS. Its data
// structure is identical except for the names of the fields.
///
public static readonly SafeOID X509_ECC_SIGNATURE = new SafeOID(47);
//+-------------------------------------------------------------------------
// X942 Diffie-Hellman
//--------------------------------------------------------------------------
///
public static readonly SafeOID X942_DH_PARAMETERS = new SafeOID(50);
//+-------------------------------------------------------------------------
// The following is the same as X509_BITS, except before encoding,
// the bit length is decremented to exclude trailing zero bits.
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_BITS_WITHOUT_TRAILING_ZEROES = new SafeOID(51);
//+-------------------------------------------------------------------------
// X942 Diffie-Hellman Other Info
//--------------------------------------------------------------------------
///
public static readonly SafeOID X942_OTHER_INFO = new SafeOID(52);
///
public static readonly SafeOID X509_CERT_PAIR = new SafeOID(53);
///
public static readonly SafeOID X509_ISSUING_DIST_POINT = new SafeOID(54);
///
public static readonly SafeOID X509_NAME_CONSTRAINTS = new SafeOID(55);
///
public static readonly SafeOID X509_POLICY_MAPPINGS = new SafeOID(56);
///
public static readonly SafeOID X509_POLICY_CONSTRAINTS = new SafeOID(57);
///
public static readonly SafeOID X509_CROSS_CERT_DIST_POINTS = new SafeOID(58);
//+-------------------------------------------------------------------------
// Certificate Management Messages over CMS (CMC) Data Structures
//--------------------------------------------------------------------------
///
public static readonly SafeOID CMC_DATA = new SafeOID(59);
///
public static readonly SafeOID CMC_RESPONSE = new SafeOID(60);
///
public static readonly SafeOID CMC_STATUS = new SafeOID(61);
///
public static readonly SafeOID CMC_ADD_EXTENSIONS = new SafeOID(62);
///
public static readonly SafeOID CMC_ADD_ATTRIBUTES = new SafeOID(63);
//+-------------------------------------------------------------------------
// Certificate Template
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_CERTIFICATE_TEMPLATE = new SafeOID(64);
//+-------------------------------------------------------------------------
// Online Certificate Status Protocol (OCSP) Data Structures
//--------------------------------------------------------------------------
///
public static readonly SafeOID OCSP_SIGNED_REQUEST = new SafeOID(65);
///
public static readonly SafeOID OCSP_REQUEST = new SafeOID(66);
///
public static readonly SafeOID OCSP_RESPONSE = new SafeOID(67);
///
public static readonly SafeOID OCSP_BASIC_SIGNED_RESPONSE = new SafeOID(68);
///
public static readonly SafeOID OCSP_BASIC_RESPONSE = new SafeOID(69);
//+-------------------------------------------------------------------------
// Logotype and Biometric Extensions
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_LOGOTYPE_EXT = new SafeOID(70);
///
public static readonly SafeOID X509_BIOMETRIC_EXT = new SafeOID(71);
///
public static readonly SafeOID CNG_RSA_PUBLIC_KEY_BLOB = new SafeOID(72);
///
public static readonly SafeOID X509_OBJECT_IDENTIFIER = new SafeOID(73);
///
public static readonly SafeOID X509_ALGORITHM_IDENTIFIER = new SafeOID(74);
///
public static readonly SafeOID PKCS_RSA_SSA_PSS_PARAMETERS = new SafeOID(75);
///
public static readonly SafeOID PKCS_RSAES_OAEP_PARAMETERS = new SafeOID(76);
///
public static readonly SafeOID ECC_CMS_SHARED_INFO = new SafeOID(77);
//+-------------------------------------------------------------------------
// TIMESTAMP
//--------------------------------------------------------------------------
///
public static readonly SafeOID TIMESTAMP_REQUEST = new SafeOID(78);
///
public static readonly SafeOID TIMESTAMP_RESPONSE = new SafeOID(79);
///
public static readonly SafeOID TIMESTAMP_INFO = new SafeOID(80);
//+-------------------------------------------------------------------------
// CertificateBundle
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_CERT_BUNDLE = new SafeOID(81);
//+-------------------------------------------------------------------------
// ECC Keys
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_ECC_PRIVATE_KEY = new SafeOID(82); // CRYPT_ECC_PRIVATE_KEY_INFO
///
public static readonly SafeOID CNG_RSA_PRIVATE_KEY_BLOB = new SafeOID(83); // BCRYPT_RSAKEY_BLOB
//+-------------------------------------------------------------------------
// Subject Directory Attributes extension
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_SUBJECT_DIR_ATTRS = new SafeOID(84);
//+-------------------------------------------------------------------------
// Generic ECC Parameters
//--------------------------------------------------------------------------
///
public static readonly SafeOID X509_ECC_PARAMETERS = new SafeOID(85);
//+-------------------------------------------------------------------------
// Predefined PKCS #7 data structures that can be encoded / decoded.
//--------------------------------------------------------------------------
///
public static readonly SafeOID PKCS7_SIGNER_INFO = new SafeOID(500);
//+-------------------------------------------------------------------------
// Predefined PKCS #7 data structures that can be encoded / decoded.
//--------------------------------------------------------------------------
///
public static readonly SafeOID CMS_SIGNER_INFO = new SafeOID(501);
}
}
}