Problem
Creating X509Certificate2 causes program stopped. No exception captured.

Cause
For some reason the constructor is trying to get access to the private key store although the private key is in stored in the file being opened. By default the user key store is used but ASP.NET (and probably non-interactive Windows services in general) are not allowed to open it. Chances are the user key store for the selected account doesn’t even exist.

Solution
Another solution is to pass an additional parameter to the constructor – a flag indicating the private keys are (supposed to be) stored in the local computer – X509KeyStorageFlags.MachineKeySet, like this:

var certificate = new X509Certificate2(fileName, password, X509KeyStorageFlags.MachineKeySet);

Reference: http://vdachev.net/2012/03/07/c-sharp-error-creating-x509certificate2-from-a-pfx-or-p12-file-in-production/

Advertisements