“An internal error occurred.” when loading pfx file with X509Certificate2

断了今生、忘了曾经 提交于 2019-11-27 03:02:28

Use the local computer store for the private key:

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

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.

Even though you are reading the certificate from disk and storing it in an object the private keys are still stored in the Microsoft Cryptographic API Cryptographic Service Provider key database. On the hosting server the ASP.NET process does not have permission to access the user store.

Another approach (as per some comments below) is to modify the IIS Configuration or App Pool identity -- which do work. However, this assumes that there is access to these configuration items which may not be the case (e.g. in a shared hosting environment).

I tried Randy's solution of changing it to MachineKeySet, but then got the error message:

"key not valid for use in specified state"

So after a little googling around I found a post that suggested changing it to:

var certificate = new X509Certificate2(certKeyFilePath, passCode, 
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet |       
X509KeyStorageFlags.PersistKeySet );

and this sorted out my issues.

I haven't yet tried the suggestion to change the setting app pool setting in the IIS configuration. To do this go to the Advanced Settings for your site's app pool then set "load user profile" to true. When this setting is false, the key containers aren't accessible apparently.

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