I am installing a pfx file using the code below (password and certPath are passed into method):
X509Certificate2 cert = password != string.Empty ? new X509Certificate2(certPath, password) : new X509Certificate2(certPath);
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();
On some machines this works, but on other environments it fails every time. No exception is thrown, but when I load up mmc.exe and add the certificates snap-in the certificate doesn't seem to have installed correctly. It shows up under the correct store, but when I right click the certificate and go under 'All Tasks' > 'Manage Private Keys', it loads a dialogue box saying 'Object was not found'. There is nothing logged in the event viewer and stepping through the code it appears to have execute correctly.
FindPrivateKey.exe also fails to find the key.
What could be causing this certificate to not run on some machines which appear to be identical to the environments where it does work?
Removing the key from within the certificate snap-in and re-importing it works, but I need this to work reliably from the C# code.
Edit - I should add that the certificate which is failing has a password which means the first line of code is effectively:
X509Certificate2 cert = new X509Certificate2(certPath, password);
Have you tried adding X509KeyStorageFlags?
new X509Certificate2(certPath, password, X509KeyStorageFlags.PersistKeySet);
EDIT: The actual answer for the question can be found in this KB article: http://support.microsoft.com/kb/950090
When the certificate is installed using the X509Certificate or X509Certificate2 class, X509Certificate/X509Certificate2 by default creates a temporary container to import the private key. The private key is deleted when there is no longer a reference to the private key.