Using X509Certificate2 to get PrivateKey causes CryptographicException “Invalid provider type specified”

谁说我不能喝 提交于 2019-12-10 15:24:00

问题


everyone,

I am developing a web application that uses X509Certificate2 to get a private key from a certification file. Code snippet looks like following:

    public static RSACryptoServiceProvider GetSignProviderFromPfx()
    {
        var strFileName = "c:\cer\mycerfile.pfx";
        var strPassword = "000000";            
        X509Certificate2 pc = new X509Certificate2(strFileName, strPassword, X509KeyStorageFlags.MachineKeySet);
        var ThePivateKey = pc.PrivateKey;

        return (RSACryptoServiceProvider)ThePivateKey;
    }

But the statement pc.Privatekey causes a System.Security.Cryptography.CryptographicException "Invalid provider type specified" . I'm sure the certification file has no problem, it really has a private key. And the property pc.HasPrivateKey is also return true.

The test environment is VS2013, window 7.

I also tried following:

a. I debugged it in VS2013 with iis express, the problem occured.

b. I debugged it in another computer with same enviroment with mine, the problem occured too.

c. I published the application to a server with iis running on Windows Web Server 2008 R2, it worked fine.

d. I published the application to widows azure website, it also worked fine.

Therefore, I guess the code snippet has no problem. The key reason raising the exception is that there may be some problem about running environment. I checked and compared the reading/writing right on the certification file in different environment, all of them are same.

Anybody can help?

Thanks.


回答1:


I have been having the same problem and this is what I did to solve it. Hopefully this will help you too.

We had to set Load User Profile to True in the app pools advanced settings

You can also set it in the web.config I believe.

https://blogs.msdn.microsoft.com/vijaysk/2009/03/08/iis-7-tip-3-you-can-now-load-the-user-profile-of-the-application-pool-identity/




回答2:


may be it useful to you; On local try:

X509Certificate2 pc = new X509Certificate2(strFileName, strPassword);


来源:https://stackoverflow.com/questions/32430835/using-x509certificate2-to-get-privatekey-causes-cryptographicexception-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!