chacham15
chacham15

Reputation: 14251

How do I add a Client Certificate and Private Key to the Users Store in Windows with C++?

Basically, the title: How do I add a Client Certificate and Private Key to the Users Store in Windows with C++?

I've found the function PFXImportCertStore which will let me load the cert and private key from a PKCS12 into a temporary cert store but I dont know how to save this store to the users store. The goal is to add a private key which other applications can access (for example, Outlook).

Upvotes: 1

Views: 633

Answers (2)

Gabriel Schwarz
Gabriel Schwarz

Reputation: 21

PFXImportCertStore(...) is returning a store. That store can be added to a store in Windows like this:

auto store = PFXImportCertStore(&pfxBLOB, pw, CRYPT_USER_KEYSET); 

if (store == nullptr)
{
    auto errorCode = GetLastError();
    // error case
}

// Oppening "MY"-Store, to add here my certificate
HCERTSTORE myStore = CertOpenSystemStore(NULL, "MY");

if (myStore == nullptr)
{
    // error case
}

// Enumerate certificates in the temporary store, if it contains multiple certificats
PCCERT_CONTEXT certContext = nullptr;
while ((certContext = CertEnumCertificatesInStore(store, certContext)) != nullptr)
{
    // Add each certificate to the MY store
    if (!CertAddCertificateContextToStore(myStore, certContext, CERT_STORE_ADD_REPLACE_EXISTING, nullptr))
    {
        // error case
    }
    else
    {
        // success
    }
}
CertCloseStore(myStore, 0);
CertCloseStore(store, 0);

Upvotes: 2

chacham15
chacham15

Reputation: 14251

I needed to call CertAddCertificateContextToStore to put it in the store that I wanted.

Upvotes: 0

Related Questions