Entries from June 2008

June 9, 2008

CryptoAPI: How to import a certificate

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 [...]