Функция CertGetSubjectCertificateFromStore (wincrypt.h)

Функция CertGetSubjectCertificateFromStore возвращает из хранилища сертификатов контекст сертификата субъекта, уникально определяемый его издателем и серийным номером.

Синтаксис

PCCERT_CONTEXT CertGetSubjectCertificateFromStore(
  [in] HCERTSTORE hCertStore,
  [in] DWORD      dwCertEncodingType,
  [in] PCERT_INFO pCertId
);

Параметры

[in] hCertStore

Дескриптор хранилища сертификатов.

[in] dwCertEncodingType

Используемый тип кодирования. Всегда допустимо указывать типы кодирования сертификатов и сообщений, объединяя их с побитовой операцией ИЛИ , как показано в следующем примере:

X509_ASN_ENCODING | PKCS_7_ASN_ENCODING в настоящее время определены следующие типы кодирования:

  • X509_ASN_ENCODING
  • PKCS_7_ASN_ENCODING

[in] pCertId

Указатель на структуру CERT_INFO . Используются только члены Issuer и SerialNumber .

Возвращаемое значение

Если функция выполняется успешно, функция возвращает указатель на CERT_CONTEXT только для чтения. CERT_CONTEXT необходимо освободить, вызвав CertFreeCertificateContext.

Возможно, возвращенный сертификат недействителен. Обычно он проверяется при получении сертификата издателя (CertGetIssuerCertificateFromStore).

Чтобы получить дополнительные сведения об ошибке, вызовите Метод GetLastError. Ниже приведен один из возможных кодов ошибки.

Код возврата Описание
CRYPT_E_NOT_FOUND
Сертификат субъекта не найден в хранилище.

Комментарии

Для создания дубликата сертификата можно вызвать CertDuplicateCertificateContext.

Примеры

В следующем примере показано получение контекста сертификата субъекта, уникально определяемого его издателем и серийным номером, из хранилища сертификатов. Пример, включающий полный контекст для этого примера, см. в разделе Пример программы C: подписывание, кодирование, декодирование и проверка сообщения.


#include <windows.h>
#include <stdio.h>
#include <Wincrypt.h>

#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

void main()
{
//-------------------------------------------------------------------
// Declare and initialize variables.

HCERTSTORE hStoreHandle;           // certificate store handle
HCRYPTMSG hMsg;
PCCERT_CONTEXT pSignerCertContext;
DWORD          cbSignerCertInfo;
PCERT_INFO     pSignerCertInfo;
//-------------------------------------------------------------------
//  This code is based on hMsg being a signed, encoded message
//  read from a file or otherwise acquired. For detailed code, see 
//  "Example C Program: Signing, Encoding, Decoding, and Verifying a 
//  Message."

//-------------------------------------------------------------------
// Retrieve the signer CERT_INFO from the message by first getting
// the size of the memory required for the certificate.

if(CryptMsgGetParam(
   hMsg,                         // handle to the message
   CMSG_SIGNER_CERT_INFO_PARAM,  // parameter type
   0,                            // index
   NULL,   
   &cbSignerCertInfo))           // size of the returned information

{
   printf("%d bytes needed for the buffer.\n", cbSignerCertInfo);
}
else
{
   printf("Verify SIGNER_CERT_INFO #1 failed\n");
   exit(1);
}

//-------------------------------------------------------------------
// Allocate memory.

pSignerCertInfo = (PCERT_INFO) malloc(cbSignerCertInfo);
if (!pSignerCertInfo)
{
    printf("Verify memory allocation failed.\n");
    exit(1);
}

//-------------------------------------------------------------------
// Get the message certificate information (CERT_INFO
// structure).

if(!(CryptMsgGetParam(
     hMsg,                         // handle to the message
     CMSG_SIGNER_CERT_INFO_PARAM,  // parameter type
     0,                            // index
     pSignerCertInfo,              // address for returned information
     &cbSignerCertInfo)))          // size of the returned information

{
    printf("Verify SIGNER_CERT_INFO #2 failed.\n");
    exit(1);
}

//-------------------------------------------------------------------
// Open a certificate store in memory using CERT_STORE_PROV_MSG,
// which initializes it with the certificates from the message.

hStoreHandle = CertOpenStore(
   CERT_STORE_PROV_MSG,         // store provider type 
   MY_ENCODING_TYPE,            // encoding type
   NULL,                        // cryptographic provider
                                // use NULL for the default
   0,                           // flags
   hMsg));                      // handle to the message
   
if (hStoreHandle)
{
    printf("The certificate store to be used for message\n ");
    printf("    verification has been opened. \n");
}
else  
{
    printf("Verify open store failed.\n");
    exit(1);
}

//-------------------------------------------------------------------
// Find the signer's certificate in the store.

pSignerCertContext = CertGetSubjectCertificateFromStore(
    hStoreHandle,       // handle to store
    MY_ENCODING_TYPE,   // encoding type
    pSignerCertInfo));  // pointer to retrieved CERT_CONTEXT
    
if(pSignerCertContext)
{

//-------------------------------------------------------------------
// Use the certificate retrieved from the message. For some 
// processing that can be done with the certificate, see the full
// program.

}
//-------------------------------------------------------------------
// Clean up.

if(pSignerCertInfo)
   free(pSignerCertInfo);
if(pSignerCertContext)
   CertFreeCertificateContext(pSignerCertContext); 
if(hStoreHandle)
   CertCloseStore(hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG);
if(hMsg)
   CryptMsgClose(hMsg);

}

Требования

Требование Значение
Минимальная версия клиента Windows XP [классические приложения | Приложения UWP]
Минимальная версия сервера Windows Server 2003 [классические приложения | Приложения UWP]
Целевая платформа Windows
Header wincrypt.h
Библиотека Crypt32.lib
DLL Crypt32.dll

См. также раздел

CertDuplicateCertificateContext

CertFreeCertificateContext

CertGetIssuerCertificateFromStore

Функции сертификата