I used Below program to retrieve the private key of "1-ksp-digitalid-MSKSP 27th June" certificate stored under LOCAL_MACHINE. It gives me error 0x80090016 i.e. Keyset does not exist error. On Properties you can see dialog saying that "you have private key corresponding to this certificate"
.
Please help in resolution of this issue
//Open Local Machine store
NCRYPT_KEY_HANDLE hKey = 0;
PCCERT_CONTEXT pCertContext = NULL;
HCERTSTORE hCertStore = NULL;
DWORD dwKeySpec;
BOOL bCallerFreeProv;
hCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"My");
// Enumerate all certificates.
while (pCertContext = CertFindCertificateInStore(hCertStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, pCertContext))
{
std::cout << "\n=====================================================================================================\n";
// Print the certificate's subject name.
wchar_t szName[256];
if (CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, szName, 256))
{
}
if (lstrcmpiW(szName, L"1-ksp-digitalid-MSKSP 27th June") != 0)
continue;
std::wcout << "Certificate Subject Name: " << szName << std::endl;
// Get the private key
if (!CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG, NULL, &hKey, &dwKeySpec, &bCallerFreeProv))
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&lpMsgBuf,
0, NULL);
wprintf(L"Error acquiring private key for %s. Error: %lu %s\n", szName, dw, lpMsgBuf);
//goto Cleanup;
}
}