Search code examples
winapicryptoapi

CryptExportKey: how to export private key from PKCS#12 store?


I need to export public and private RSA key from certificate, stored in PKCS#12 format, on Windows.

I can open certificate store with CertOpenStore(), then find certificate with CertFindCertificateInStore() and acquire private key with CryptAcquireCertificatePrivateKey().

It works Ok. Then I extract user key with CryptGetUserKey() It works too.

But CryptExportKey() with blob type PRIVATEKEYBLOB fails. CryptSetKeyParam() with KP_PERMISSIONS and set permission CRYPT_EXPORT also fails.

How could I get all RSA key pair parameters in such case?

All examples use CryptGenKey() to create and THEN export key, but I need to export existing key pair to simple binary form.


Solution

  • Found solution: if use more specific PFXImportCertStore() to open PKCS#12 file instead of generic CertOpenStore() with CERT_STORE_PROV_PKCS12 store provider, it accepts flag CRYPT_EXPORTABLE and key could be exported with CryptExportKey().