简体   繁体   中英

C++ adding certificate to Trust Root storage in Windows

I have a task to add certificate (private key and certificate file) generated by openssl library to Trust Root Storage in Windows from my C++ program. Could you, please, show some code examples? I suppose that I should use Win Api, but I haven't found examples yet. Maybe someone had the same task or could recommend relevant resources. I still have found only C++ access trusted root certificates but that is inverse issue. Instead of that I need to add certificate in the storage.

I don't know if this is the best way to do it, but at least it works for me (I assume that you want to import into the current user's store and not the machine certificate store).

First you have to load the PFX file into a CRYPT_DATA_BLOB (it's a struct that contains a pointer to a buffer and associated length). Basically you read the PFX into the buffer and set the length accordingly. You can then import that CRYPT_DATA_BLOB into a cert store by using PFXImportCertStore. This cert store is a temporary one, so it's not yet into the cert store you want. You then have to open the cert store you want to really import the certificate into (by using CertOpenSystemStore), extract the certificate object from the temporary cert store with CertEnumCertificatesInStore and insert it into the final cert store with CertAddCertificateContextToStore.

This code shows all of the above more or less:

#include <Windows.h>
#include <wincrypt.h>

int main(int argc, char** argv) {
    UNREFERENCED_PARAMETER(argc);
    UNREFERENCED_PARAMETER(argv);

    unsigned char buffer[8192];
    CRYPT_DATA_BLOB key;
    key.cbData = 0;
    key.pbData = buffer;

    HANDLE h = CreateFile(L"c:\\temp\\server.pfx", FILE_GENERIC_READ, 0, NULL,  OPEN_EXISTING, 0, NULL);
    ReadFile(h, buffer, 8192, &key.cbData, NULL);
    CloseHandle(h);

    HCERTSTORE store = PFXImportCertStore(&key, L"mypassword", 0);
    PCCERT_CONTEXT ctx = CertEnumCertificatesInStore(store, NULL);
    HCERTSTORE rootStore = CertOpenSystemStore(NULL, L"ROOT");
    CertAddCertificateContextToStore(rootStore, ctx, CERT_STORE_ADD_REPLACE_EXISTING, NULL);
    CertCloseStore(store, 0);
    CertCloseStore(rootStore, 0);
    return 0;
}

For the sake of brevity, the code does not include any error checks. It also assumes that there is only one certificate in the temporary store (otherwise you should put CertEnumCertificatesInStore in a loop). Anyway, I think that you can build from here (you should check the options available for many of the methods).

Remember to add crypt32.lib to the project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM