c++windowscertificate-storewincryptp7b

How to point to/access a cert file `CertCreateCertificateContext` function? (wincrypt api)


A little new to windows programming/C++. I'm trying to install a .p7b root certificate file to the Trusted Root Certificate Store. I want to use the Windows Wincrypt library. Specifically, these are the suggested steps that I got from an old forum:

  1. Call CertCreateCertificateContext using your certificate content bytes in order to obtain a PCCERT_CONTEXT
  2. Call CertOpenSystemStore with szSubsystemProtocol set to "ROOT" in order to obtain a HCERTSTORE
  3. Call CertAddCertificateContextToStore using the above HCERTSTORE and PCCERT_CONTEXT.

[Here's] the api documentation for CertCreateCertificateContext. Not sure how to just point pbCertEncoded to my actual cert file. Should I just point it to the path? Do I have to load the cert in? What should the type be?


Solution

  • From Simon Rozman's answer in this post: We have to use CertOpenStore() instead of CertCreateCertificateContext(), which supports one certificate only, whereas PKCS #7 file can contain many.

    After the certificate store is open, you can use CertEnumCertificatesInStore() to retrieve certificate context of individual certificates from store.

    So from my original steps to successfully install a p7b into the root store:

    1. Call CertOpenStore() for the root store and for the actual certificate itself. This will give you two HCERTSTORE handles.

    2. Have a while loop that will add the certificate contexts to the opened root store (using CertAddCertificateContextToStore()) as long as the certificate context exists (check using CertEnumCertificatesInStore() on the opened certificate store).