How to export HCRYPTKEY or PRIVATEKEYBLOB to a PFX file

I have a previously generated RSA private key that is stored as PRIVATEKEYBLOB . I am trying to move this to a new certificate for better key management. How can I take this blob and turn it into a .pfx certificate?

I have HCRYPTPROV (uses MS_ENHANCED_PROV and PROV_RSA_FULL). I can get HCRYPTKEY from CryptImportKey.

PFXExportCertStoreEx, apparently, is a function of exporting it to PFX-blob (which I assume that I will write to a file), but I do not understand how to get the key from it.

+4
source share
1 answer

If I understand your problem correctly, you have a certificate and the corresponding private key as a drop of data, and both of them separately . If you are working with CryptoAPI, it is important to understand that the API is mainly focused on working with certificates stored in certificate stores and private keys stored in key containers. A function like PFXExportCertStoreEx follows this approach and allows you to export all certificates from one certificate store to a data block, which can simply be saved as a .PFX file.

So what you can do is the following:

  • Create a temporary certificate store using CertOpenStore with the CERT_STORE_PROV_MEMORY parameter.
  • Place in the certificate store in the store using the CertAddEncodedCertificateToStore function .
  • Create a new key container using CryptAcquireContext with the CRYPT_NEWKEYSET option. You must specify some unique name for the container (see the pszContainer Function Parameter).
  • Import the information from PRIVATEKEYBLOB that you currently have into the key container in relation to the CryptImportKey function.
  • Bind a certificate from a certificate store to a key container. To do this, you must use CertSetCertificateContextProperty to set the CERT_KEY_PROV_INFO_PROP_ID , called the so-called extended certificate property. It is important to understand that advanced properties are not part of the X.509 specification. Advanced properties allow you to store additional information related to the certificate in the certificate store (and not in the certificate itself). In the case of CERT_KEY_PROV_INFO_PROP_ID you can store the full information ( CRYPT_KEY_PROV_INFO ) described by the key container.
  • Now you can use PFXExportCertStoreEx to export the temporary certificate store (which contains only one certificate and has a link to the key container) to memory, and then save the memory location in a .PFX file.
  • You must delete the key container created in step 3. To do this, you need to open the key container using the CryptAcquireContext using the CRYPT_DELETEKEYSET option.
+2
source

Source: https://habr.com/ru/post/1432227/


All Articles