Create new certificate store in C/C++

1.3k Views Asked by At

I am trying to create a new certificate store in Windows programmatically using C/C++.

I started with this function - CryptAcquireContext, and wrote this piece of code:

#include<windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
    HCRYPTPROV hCryptProvider;
    PCWSTR DefaultContainerName = L"MyStoreName";
    PCWSTR DefaultProviderName = MS_STRONG_PROV;
    DWORD DefaultProviderType = PROV_RSA_FULL;
    DWORD DefaultProviderFlags = CRYPT_MACHINE_KEYSET | CRYPT_SILENT | CRYPT_NEWKEYSET;

    printf("%d\n", CryptAcquireContext(&hCryptProvider, DefaultContainerName, DefaultProviderName, DefaultProviderType, DefaultProviderFlags));

    return 0;
}

The container name and provider name values have been picked up from a design document that I am supposed to follow.

I dont know if this is the correct way to create stores, because after running this and opening the Certificate snap-in of MMC, I do not see the store of the given name. The program prints 1 on being run first time, and 0 from the second time onward.

Is this the correct way ? If yes, why don't I see the store in MMC ? If no, what is the correct way to create new certificate stores using C/C++ ?

Please feel free to point out any mistakes in the code.

2

There are 2 best solutions below

2
On

CryptAcquireContext can create a key container. A key container is not the same thing as a certificate store.

To create a certificate store use CertRegisterPhysicalStore or CertRegisterSystemStore.

0
On

Looking at one function in one of the codebases I was dealing with, I thought it was creating a store. So I wrote a small code snippet with that function, and voila - the store is getting created.

Function : CertOpenStore

Despite its name which signifies an opening of a store, it created the store I specified if it did not exist. Otherwise, it would have opened the existing store. (I do not find any documentation for this).

Here is my code snippet:

#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
using namespace std;

int main()
{
    HCERTSTORE store = NULL;
    LPCSTR StoreProvider = CERT_STORE_PROV_SYSTEM;
    DWORD Flags = CERT_SYSTEM_STORE_LOCAL_MACHINE;
    PCWSTR StoreName = L"MyStore";

    store = CertOpenStore(StoreProvider, 0, NULL, Flags, (void *)StoreName);
    if(store == NULL)
        printf("Could not open store");

    return 0;
}

Checking certificate snap-in of MMC after running this code, I could see the store names 'Mystore' getting listed.

Ben's answer is also correct and I would say is preferable because the function deals specially with registering certificate stores.