Valery's Mlog

Mindlog of a Freak
March 7th, 2012 by Valery Dachev

C#: Error Creating X509Certificate2 from a PFX or P12 File in Production


Today I stumbled upon a problem instantiating a X509Certificate2 class from a PKCS#12 container (a .pfx or a .p12 file) in production environment. For some reason I kept getting “The specified network password is not correct.” (for password-less containers) or “An internal error occurred.” (for protected ones).


The cause of the problem doesn’t seem to have much to do with the error messages. 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.


One thing you could try is creating a user key store by logging into the account and importing a certificate in its Personal store (and then remove it again).

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);


9 Responses to “C#: Error Creating X509Certificate2 from a PFX or P12 File in Production”
  1. thanks a lot, it work well now

  2. Thanks, I found this post very useful.

  3. Thanks!! :)

  4. manish sharma says

    thanks it helped :)

  5. kentaro says

    it is very helpful, thanks!

  6. […] Reference:… […]

  7. Thank you so much

  8. Thank you. This article solved my problem.

  9. Navyasree Janjirala says

    Hi, can someone explain me what to do exactly to get this issue resolved. I have a pfx certificate imported in my personal store. I have been trying to solve this since a week and this is my first task at work (apparently which is my first job).
    Appreciate any kind of help.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: