需要帮助以使用CertFindCertificateInStore()按主题名称(X500格式,CERT_X500_NAME_STR)查找证书?

时间:2013-03-25 13:39:57

标签: windows certificate cryptoapi

客户端应用程序必须从Windows证书存储区访问证书。搜索 input是X500字符串格式的主题名称,如下所示。

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

需要完全匹配(不使用CERT_FIND_SUBJECT_STR进行子字符串匹配)。 为此我做了以下

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;
         }
     }
  }

问题是CertFindCertificateInStore总是返回NULL指针。我一直在调试,但无法找出这里出了什么问题。

任何建议都会非常有用。

1 个答案:

答案 0 :(得分:7)

如果有人正在寻找这个问题的答案,我会发布如何做到这一点,因为它很有用

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;
}