2

I am attempting to load a certificate with private key from a pfx file and import it to the LocalMachine/My (Personal) certificate store. My code works fine except that when I view the certificate in the store it says

"The associated private key cannot be found"

and further, certutil says

"Cannot find the certificate and private key for decryption"

The strange part is that my code works fine on Windows 7 development box but not on Windows Server 2008 R2 or 2012. Also strange that if I manually import the pfx file using mmc, the private key seems to persist properly.

Here is the code I am using to load the file and import :

// load the certificate from pfx file
X509Certificate2 cert = new X509Certificate2(filePath, pfxPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

// import to the store
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite); //tried MaxAllowed as well
store.Add(caCert);
store.Close();

Any ideas? For background info, I am also generating the certificate in code at an earlier step using BouncyCastle. I ran into some problems persisting the private key during that step but was solved with the answer from this question. Also the code that is attempting the import is running as administrator.

Community
  • 1
  • 1
rusty
  • 499
  • 1
  • 5
  • 19
  • Refer to this answer, http://stackoverflow.com/questions/749654/associate-private-key-to-certificate-for-pfxexportcertstoreex – Raj Sep 07 '15 at 10:26
  • @Raj thanks for the pointer, but I am not explicitly working with CryptoAPI at the moment. I'm wondering if there is a way to do this using the c# System.Security.Cryptography.X509Certificates or related namespaces... – rusty Sep 14 '15 at 16:43

1 Answers1

0

A little time away from this problem helped me refine my investigation. I tracked down the private key file for the imported certificate in

C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
and found that the file had no owner and no permissions set (not even for Administrators or System). Modifying these permissions manually caused the "associated private key" message to go away when viewing the cert in the store.

That led me to modify my code to set permissions on the private key before attempting to import it into the store : https://stackoverflow.com/a/4902009/332610

hooray!

Community
  • 1
  • 1
rusty
  • 499
  • 1
  • 5
  • 19