PCCERT_CONTEXT的私钥如何得到NCRYPT_KEY_HANDLE?

How can I get a NCRYPT_KEY_HANDLE for the private key of a PCCERT_CONTEXT?

如何从 windows 证书存储中的 PCCERT_CONTEXT 的私钥中使用 CNG 为 encryption/decryption 获取 NCRYPT_KEY_HANDLE

CryptEncrypt 函数已被 NCryptEncryptBCryptEncrypt 函数取代,但是没有立即明显的方法从 PCCERT_CONTEXT 来自 Windows 证书存储。

是否甚至可以使用 CNG 函数 encryption/decryption 使用证书(的私钥)而不用像导出证书这样的暴力破解方法?

我正在自己回答这个问题,因为我在别处找不到答案:

以下代码将为您提供所需的信息:

const HCERTSTORE store(CertOpenStore(CERT_STORE_PROV_SYSTEM_W, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_READONLY_FLAG, (const void*)L"MY"));
const PCCERT_CONTEXT certContext(CertFindCertificateInStore(store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR_W, subjectName, nullptr));
if (certContext)
{
  HCRYPTPROV_OR_NCRYPT_KEY_HANDLE keyHandle;
  DWORD keySpec;
  BOOL callerFreesKeyHandle;

  // Get NCrypt key handle from certificate.
  // Might fail for instance if certificate private key is not accessible to current user.
  if (CryptAcquireCertificatePrivateKey(certContext, CRYPT_ACQUIRE_SILENT_FLAG | CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG, nullptr, &keyHandle, &keySpec, &callerFreesKeyHandle))
  {
    check(keySpec == CERT_NCRYPT_KEY_SPEC); //< Should always have this value when giving CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG.
    UNIQUE_NCRYPT_KEY_HANDLE keyHandleKeeper;
    if (callerFreesKeyHandle)
    {
      keyHandleKeeper.reset(keyHandle);
    }
    ...