CryptAcquireCertificatePrivateKey gets a handle to something that knows both the private and the public keys

mterrisse 96 Reputation points
2023-02-15T14:30:10.05+00:00

Hello,

CryptAcquireCertificatePrivateKey with the flag CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG gets a handle (NCRYPT_KEY_HANDLE) to a certificate's private key.

In the documentation https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecertificateprivatekey you can read: "The CryptAcquireCertificatePrivateKey function obtains the private key for a certificate".

But I found out that we get a handle to something that knows both the private key and the public key, and if I encrypt something with this handle (NCryptEncrypt), it encrypts with the public key and not the private key as expected. The result can indeed be decrypted (NCryptDecrypt) using the same handle (strange for an asymmetric algorithm), but not with a handle to the public key (public key obtained with CryptImportPublicKeyInfoEx2), NCryptDecrypt returns 0xc000000d = STATUS_INVALID_PARAMETER that just means "Can't decrypt".

Of course, we're supposed to encrypt with a public key and decrypt with a private key, the opposite looks more like a signature than encryption, but I needed to do it in a special case. It seems I can't.

Can you confirm this analysis? It took me a long time to understand this.

Regards,

Michel Terrisse

Windows development | Windows API - Win32
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jeanine Zhang-MSFT 11,356 Reputation points Microsoft External Staff
    2023-02-16T02:13:51.25+00:00

    Hello,

    Welcome to Microsoft Q&A!

    If you want to confirm that whether could you use the certificate's private key for encryption/decryption? If so, the analysis is right. You could use the CryptAcquireCertificatePrivateKey function get the private key for a certificate. And then use the certificate's private key to encryption/decryption.

    You could refer to the thread: https://stackoverflow.com/questions/48830779/how-can-i-get-a-ncrypt-key-handle-for-the-private-key-of-a-pccert-context

    Thank you.

    Jeanine


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    [2]:


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.