1

I want to get a private key from windows store and convert it to PEM in order to use it in OpenSSL. I've been looking for a way to do that for a few hours!

  • I use CertFindCertificateInStore() to get CERT_CONTEXT (which I know it contains the private key using the search parameter).
  • Next, I used CryptAcquireCertificatePrivateKey() to get HCRYPTPROV (just because of the name of the function).
  • Now, I use CryptGetUserKey() to get HCRYPTKEY (just because it sounds right...?!)

But now I'm stuck again.

I think this is security by obscurity done by Microsoft to make sure we will never be able to get private keys.

TCS
  • 5,790
  • 5
  • 54
  • 86

2 Answers2

2

I'm leaving the answer as it is (after all without dbasic I would've been stuck :-)), but I have more to add:

CryptExportPKCS8() end of support ended with XP/2003, so we have to use PFXExportCertStoreEx() , however this function exports the WHOLE store. So, in order to export just one certificate you need to use a memory store.

Check out this example on how to do that: http://msdn.microsoft.com/en-us/library/windows/desktop/aa382037(v=vs.85).aspx

Insert the certificate you want into the memory store, and then use PFXExportCertStoreEx() to export what you need.

TCS
  • 5,790
  • 5
  • 54
  • 86
  • this function exports the certificate within the store as a blob. Is there a way to extract the private key from the blob or from the certificate context? – Rohan Bhosale Apr 06 '21 at 12:31
  • @RohanBhosale Did you get a solution for your question? I am stuck in the same place now – T.s. Arun Feb 07 '23 at 09:37
0

First two are fine. But you need to use CryptExportPKCS8. It will export the private key to a buffer in PKCS #8 DER encoded form. From PKCS #8, you can get it into X509 structure of OpenSSL (by using d2i functions and memory buffer as input in BIO structures).

However, if the private key is marked as non-exportable, this function will fail.

Only use you can do is to sign the data using such private key.

doptimusprime
  • 9,115
  • 6
  • 52
  • 90
  • 1
    Thanks. Notice the function's end of support is XP and server2003. PFXExportCertStoreEx() should be used instead. – TCS May 28 '13 at 08:55
  • @doptimusprime u mentioned "if the private key is marked as non-exportable, this function will fail." that's True. But now is that possible to use private key in openssl even when "it is marked non-exportable", i mean is there way by which we can just pass handle of the key to the openssl api ,it will automatically read the key from windows cert store without actually exporting the key bytes from windows store ? The reason why i am asking for this is because marking a key as exportable allows anyone to export the key bytes from store(Safer Place) to Disk(Unsafe Place). I hope this makes sense – User1234 Dec 31 '15 at 05:47
  • Yes. You can overload RSA_METHOD structure to define signing function and data and can use it in RSA structure. – doptimusprime Dec 31 '15 at 09:37