views:

1539

answers:

5

I'm trying use self-signed certificate (c#):

X509Certificate2 cert = new X509Certificate2(
    Server.MapPath("~/App_Data/myhost.pfx"), "pass");

on a shared web hosting server and I got an error:

System.Security.Cryptography.CryptographicException: An internal error occurred.

stack trace ends with

System.Security.Cryptography.CryptographicException.
    ThrowCryptogaphicException(Int32 hr) +33
System.Security.Cryptography.X509Certificates.X509Utils.
    _LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, 
        Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
System.Security.Cryptography.X509Certificates.X509Certificate.
    LoadCertificateFromFile(String fileName, Object password, 
        X509KeyStorageFlags keyStorageFlags) +237
System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(
    String fileName, String password) +131

On my dev machine it loads ok. The reason I load *.pfx not a *.cer file because I need a private key access (cer file loads Ok). I made pfx on my dev mochine like that:

makecert -r -n "CN=myhost.com, [email protected]" -sky exchange -b 01/01/2009
    -pe -sv myhost.pvk myhost.cer
<b>pvk2pfx</b> -pvk myhost.pvk -spc myhost.cer -pfx myhost.pfx -po pass</code>

I am using version v5.131.3790.0 of makecert

+11  A: 

Use the local computer store for the private key:

X509Certificate2 cert = new X509Certificate2("myhost.pfx", "pass",
    X509KeyStorageFlags.MachineKeySet);

UPDATE:

MachineKeySet is described as "Private keys are stored in the local computer store rather than the current user store". The default with no flags is to place in the user store. So, I'm guessing that even though you are reading the cert from disk and storing it in an object that the _LoadCertFromFile method is still accessing a certificate store. And on the hosting server the ASP.NET process does not have permission to access the user store (or a user store does not even exist).

Tuzo
yes it helps, thanks. could you explain why? docs says nothing helpful.
Fredrik Johansson
A: 

WOW! That really solved my issue as well. I was loading the cert from as an embedded resource into a byte[] and it worked on the dev machine without any problems but once deployed on the server I got that strange "internal error occured". With the MachineKeySet attribute attached everything works like a charm! Thanks a lot!

TillmanZ
A: 

You saved my life Tuzo !!!!!!! CHEERS....

Alich
A: 

Thank you Tuzo. You solved my problem.

Gustavo
A: 

Thanks, saved me so much hassle. love stackoverflow community.

minalg