Access X509 Certificate store with unmanaged C++

只谈情不闲聊 提交于 2019-12-02 04:28:38

问题


Does anyone know how I would do the equivalent of the below C# code using unmanaged C++ i.e. query a certificate from the X509 certificate store by thumbprint?

        var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

        store.Open(OpenFlags.ReadOnly);

        var allCerts = store.Certificates;

        foreach (var certificate in from X509Certificate2 certificate in allCerts
                                    where certificate.Thumbprint != null
                                       && certificate.Thumbprint.Equals(thumbprint, StringComparison.OrdinalIgnoreCase)
                                    select certificate)
        {
            return certificate;
        }

Thanks in advance

Dave


回答1:


In order to accomplish what you want, you'll have to look into the Win32 CryptAPI library. It won't be as easy as .NET. Look into CertOpenStore and CertFindCertificateInStore.

You'll need to open a certificate store and pass it into CertFindCertificateStore, creating a structure to hold whatever criteria you want to use to find your certificate. You can use a serial number, signature, etc.

    HCERTSTORE hSysStore = NULL;
    PCCERT_CONTEXT  pDesiredCert = NULL;
if(hSysStore = CertOpenStore(
   CERT_STORE_PROV_SYSTEM,          // The store provider type
   0,                               // The encoding type is
                                    // not needed
   NULL,                            // Use the default HCRYPTPROV
   CERT_SYSTEM_STORE_CURRENT_USER,  // Set the store location in a
                                    // registry location
   L"MY"                            // The store name as a Unicode 
                                    // string
   ))
{
    //We have our store, let's do stuff with it
    if (pDesiredCert = CertFindCertificateInStore(.....) {  ..... }
}
else
{
    //Error stuff
}

You will need to #include <Wincrypt.h> and #include <windows.h>




回答2:


The code from CertFindCertificateInStore. will not work on newer systems. On newer versions of Windows the certificate's name or subject are in Unicode format which uses 2 bytes for each character. The folowing line:

LPCSTR lpszCertSubject = (LPCSTR) "Cert_subject_1";

has to be change into:

LPCWSTR lpszCertSubject = (LPCWSTR ) L"Cert_subject_1";

or

LPCTSTR lpszCertSubject = (LPCTSTR ) _T"Cert_subject_1"; // add #include <tchar.h> 

depending on what you need.



来源:https://stackoverflow.com/questions/8058510/access-x509-certificate-store-with-unmanaged-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!