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

前端 未结 2 1257
梦如初夏
梦如初夏 2020-11-28 23:01

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

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


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 23:21

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

提交回复
热议问题