June 9, 2008...4:16 pm

CryptoAPI: How to import a certificate

Jump to Comments

Following is the C code to import a certificate into the Windows trusted root certificate store using CryptoAPI:

PCCERT_CONTEXT pCertCtx = NULL;

if (CryptQueryObject (
        CERT_QUERY_OBJECT_FILE,
        L"D:\\selva\\b64.cer",
        CERT_QUERY_CONTENT_FLAG_ALL,
        CERT_QUERY_FORMAT_FLAG_ALL,
        0,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        (const void **)&pCertCtx) != 0)
{
    HCERTSTORE hCertStore = CertOpenStore (
        CERT_STORE_PROV_SYSTEM,
        0,
        0,
        CERT_STORE_OPEN_EXISTING_FLAG |
        CERT_SYSTEM_STORE_LOCAL_MACHINE,
        L"ROOT");
    if (hCertStore != NULL)
    {
        if (CertAddCertificateContextToStore (
            hCertStore,
            pCertCtx,
            CERT_STORE_ADD_ALWAYS,
            NULL))
        {
            cout << "Added certificate to store." << endl;
        }

        if (CertCloseStore (hCertStore, 0))
        {
            cout << "Cert. store handle closed." << endl;
        }
    }

    if (pCertCtx)
    {
        CertFreeCertificateContext (pCertCtx);
    }
}

NOTE: I have tested the above code to import DER encoded and Base-64 encoded certificates.

4 Comments

  • I get many undefine variables when i compile the code. This is just one of then, PCCERT_CONTEXT. How do i resolve it?

  • Thanks! This post was really helpful. I think I finally have the Crypto API wrapped around my little finger.

  • @Ted Shear: You would have to include the appropriate header files – wincrypt.h in this case – for the names to be resolved correctly. Also, make sure that the directory in which the headers reside is in your INCLUDE path. If you want to find out the header required to resolve a CryptoAPI function, you may refer to MSDN.


Leave a Reply