Example Code for Certificate Verification Operations

This code demonstrates the following:

#define _WIN32_WINNT 0x0400
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

//********************************************************************
//  This codes demonstrates 
//   Opening and closing a system store
//   Finding a certificate by Subject name
//   Using the CertVerifyTimeValidity function to check the 
//   certificate's validity

void main(void)
{
//********************************************************************
// Declare Variables.
HCERTSTORE      hSystemStoreHandle = NULL;
PCCERT_CONTEXT  pTargetCert=NULL;
char            szSubjectName[] = "Microsoft"; // A string to be found 
                                               // in a certificate 
                                               // subject.
long            nReturn;
PCERT_INFO          pTargetCertInfo; 

//********************************************************************
// Call CertOpenStore to open the ROOT store.
if(hSystemStoreHandle = CertOpenStore(
      CERT_STORE_PROV_SYSTEM,
      0,
      NULL, 
      CERT_SYSTEM_STORE_CURRENT_USER,
      L"ROOT"))
   printf("The Root store is open. \n");
else
{
   printf( "Error opening the Root store.\n");
   goto handle_error;
}
// If successful, hStoreHandle is the open system cert store handle.

//********************************************************************
// Get a particular certificate using CertFindCertificateInStore.
if(pTargetCert = CertFindCertificateInStore(
      hSystemStoreHandle,     // Store handle
      MY_ENCODING_TYPE,       // Encoding type
      0,                      // Not used
      CERT_FIND_SUBJECT_STR_A,// Find type. Find a string in the 
                              // certificate's subject.
      szSubjectName,          // The string to be searched for.
      pTargetCert))           // Previous context
   printf("Found the certificate. \n");
else
{
   printf("Could not find the required certificate");
   goto handle_error;
}
// If successful, pTargetCert is a pointer to the desired
// certificate.

//********************************************************************
// Check the certificate validity.
pTargetCertInfo = pTargetCert->pCertInfo;    
nReturn = CertVerifyTimeValidity(
      NULL,               // Use current time
      pTargetCertInfo);   // Pointer to CERT_INFO
if(nReturn<0)
   printf("Certificate not valid yet. \n");
else
   if(nReturn>0)
      printf("Certificate is expired. \n");
   else
      printf("Certificate is valid. \n");

//********************************************************************
// Clean up memory and quit.
handle_error:
if (pTargetCert)
   CertFreeCertificateContext(pTargetCert);
if(hSystemStoreHandle)
   CertCloseStore(hSystemStoreHandle, 
        CERT_CLOSE_STORE_CHECK_FLAG);
printf("The certificate has been freed and the store closed.\n");
return;
}