Home » Windows » Need help to find certificate by Subject name (X500 format, CERT_X500_NAME_STR) using CertFindCertificateInStore()?

Need help to find certificate by Subject name (X500 format, CERT_X500_NAME_STR) using CertFindCertificateInStore()?

Posted by: admin February 27, 2018 Leave a comment

Questions:

A client application has to access certificate from Windows certificate store. The search
input is the subject name in X500 string format as below.

"C=CH, S=Aargau, L=Baden, O=Test, OU=FF, CN= Test Root"

An exact match is required (not substring match using CERT_FIND_SUBJECT_STR).
For this i do the following

CERT_NAME_BLOB subjectname = {0};

/*convert the input X500 string to encoded subject name*/
bRet = CertStrToNameA(X509_ASN_ENCODING, "C=CH, S=Aargau, L=Baden, O=Test, OU=S1, CN= Test Root", CERT_X500_NAME_STR, NULL, NULL, &size, NULL);
  if(TRUE == bRet)
  {
     subjectname.pbData  = (BYTE*)malloc(size);
     subjectname.cbData = size;

     bRet = CertStrToNameA(X509_ASN_ENCODING , "C=CH, S=Aargau, L=Baden, O=Test, OU=S1, CN=Test Root", CERT_X500_NAME_STR, NULL, subjectname.pbData, &subjectname.cbData, NULL);
     if(TRUE == bRet)
     {
          capiCertificate = CertFindCertificateInStore(hStore, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_NAME, &subjectname, NULL);
         if (NULL == capiCertificate)
         {
            errorcode = GetLastError();
            ret = CA_CERT_NOT_FOUND;
         }
     }
  }

The problem is that CertFindCertificateInStore always return NULL pointer. I have been debugging, but could not find out what is going wrong here.

Any suggestions will be very helpful.

Answers:

In case anyone is looking for an answer to this question, i am posting how i could do it, incase it is useful

static PCCERT_CONTEXT
FindCertificate(
    const HCERTSTORE hStore,
    const char* CertSearchString)
{
    PCCERT_CONTEXT capiCertificate = NULL;
    DWORD dType = CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG;
    char certname [MAX_SIZE_CERT_NAME] = {0};

    for(;;)
    {
        capiCertificate = CertEnumCertificatesInStore(hStore, capiCertificate);
        if (NULL == capiCertificate)
        {
            break;
        }

        if (FALSE == 
            CertGetNameStringA(capiCertificate, CERT_NAME_RDN_TYPE,
                0, &dType, certname, MAX_SIZE_CERT_NAME))
        {
            CertFreeCertificateContext(capiCertificate);
            capiCertificate = NULL;
            break;
        }

        if ((0 == strncmp(certname, CertSearchString, MAX_SIZE_CERT_NAME)) &&
            (capiCertificate->dwCertEncodingType == X509_ASN_ENCODING))
        {
            break;
        }
    }
    return capiCertificate;
}