Función CertGetSubjectCertificateFromStore (wincrypt.h)

La función CertGetSubjectCertificateFromStore devuelve desde un almacén de certificados un contexto de certificado del firmante identificado de forma única por su emisor y número de serie.

Sintaxis

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

Parámetros

[in] hCertStore

Identificador de un almacén de certificados.

[in] dwCertEncodingType

Tipo de codificación usada. Siempre es aceptable especificar los tipos de codificación de certificados y mensajes mediante su combinación con una operación OR bit a bit, como se muestra en el ejemplo siguiente:

X509_ASN_ENCODING | PKCS_7_ASN_ENCODING tipos de codificación definidos actualmente son:

  • X509_ASN_ENCODING
  • PKCS_7_ASN_ENCODING

[in] pCertId

Puntero a una estructura CERT_INFO . Solo se usan los miembros Issuer y SerialNumber .

Valor devuelto

Si la función se ejecuta correctamente, la función devuelve un puntero a un CERT_CONTEXT de solo lectura. El CERT_CONTEXT debe liberarse llamando a CertFreeCertificateContext.

Es posible que el certificado devuelto no sea válido. Normalmente, se comprueba al obtener su certificado de emisor (CertGetIssuerCertificateFromStore).

Para obtener información de error extendida, llame a GetLastError. Un posible código de error es el siguiente.

Código devuelto Descripción
CRYPT_E_NOT_FOUND
No se encontró el certificado del firmante en el almacén.

Comentarios

Se puede llamar a CertDuplicateCertificateContext para crear un certificado duplicado.

Ejemplos

En el ejemplo siguiente se muestra cómo recuperar el contexto de certificado de un firmante, identificado de forma única por su emisor y número de serie, desde el almacén de certificados. Para obtener un ejemplo que incluya el contexto completo de este ejemplo, vea Ejemplo de programa C: firma, codificación, descodificación y comprobación de un mensaje.


#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);

}

Requisitos

Requisito Value
Cliente mínimo compatible Windows XP [aplicaciones de escritorio | aplicaciones para UWP]
Servidor mínimo compatible Windows Server 2003 [aplicaciones de escritorio | aplicaciones para UWP]
Plataforma de destino Windows
Encabezado wincrypt.h
Library Crypt32.lib
Archivo DLL Crypt32.dll

Consulte también

CertDuplicateCertificateContext

CertFreeCertificateContext

CertGetIssuerCertificateFromStore

Funciones de certificado