I am trying to add certificate to store, but I am new in it. I've been searching for information about how to install certificate to store without finding certificate context from store (I have no certificate in store). Everything I found I've been used in code below. But it seems like it doesn't work, and I can't find certificate in store even after message that certificate was installed.
static HCRYPTPROV hProv = 0;
static HCRYPTKEY hKey = 0;
static unsigned char *pbKeyBlob = nullptr;
static unsigned int cbKeyBlob;
static unsigned int cbCertBlob;
static unsigned char *pbCertBlob = nullptr;
LPCSTR szCont = "myCont";
if(CryptAcquireContext(&hProv, szCont, nullptr, PROV_GOST_2012_256, 0))
{
qDebug() << "The key container \"%s\" has been acquired.\n" << szCont;
}
else
{
HandleError("Error during CryptAcquireContext.");
}
if(CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hKey))
{
qDebug() << "The public key has been acquired. \n";
}
else
{
HandleError("Error during CryptGetUserKey public key.");
}
if(CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, nullptr, &cbKeyBlob))
{
qDebug() << "Size of the BLOB for the public key determined. \n";
}
else
{
HandleError("Error computing BLOB length.");
}
pbKeyBlob = static_cast<unsigned char*>(malloc(cbKeyBlob));
if(!pbKeyBlob)
{
HandleError("Out of memory. \n");
}
if(CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, pbKeyBlob, &cbKeyBlob))
{
qDebug() << "Contents have been written to the BLOB. \n";
}
else
{
HandleError("Error during CryptExportKey.");
}
if(CryptGetKeyParam(hKey, KP_CERTIFICATE, nullptr, &cbCertBlob, 0))
{
pbCertBlob = static_cast<unsigned char*>(malloc(cbCertBlob));
if(!pbCertBlob)
{
HandleError("Out of memory. \n");
}
szFileName = static_cast<char*>(malloc((strlen(szCont) + 5) * sizeof(char)));
if(!szFileName)
{
HandleError("Out of memory. \n");
}
if(CryptGetKeyParam(hKey, KP_CERTIFICATE, pbCertBlob, &cbCertBlob, 0))
{
qDebug() << "Got certificate from container.\n";
}
else
{
HandleError("Error during CryptGetKeyParam.");
}
strcpy(szFileName, szCont);
strcat(szFileName, ".cer");
WriteBlobToFile(Cert, pbCertBlob, cbCertBlob);
pDesiredCert = CertCreateCertificateContext(MY_ENCODING_TYPE, pbCertBlob, cbCertBlob);
hCertStore = CertOpenSystemStore(0, "mRoot");
Here I didn't get any error and it even seems like it successfully installed, but I found nothing in certificate store.
if (!CertAddEncodedCertificateToStore(hCertStore, MY_ENCODING_TYPE, pDesiredCert->pbCertEncoded, pDesiredCert->cbCertEncoded, CERT_STORE_ADD_NEW, &pDesiredCert))
{
qDebug() << "Cartificate installing failed.";
}
else
{
qDebug() << "Certificate was installed successfully to mRoot store.";
}
It is better to create certificate with dedicated tools such as makecert, openssl, etc. Afterward, According to Serializing Certificates you can add it into a certificate store.
Edit:
Then