我正在尝试使用自签名证书 (c#):
X509Certificate2 cert = new X509Certificate2(
Server.MapPath("~/App_Data/myhost.pfx"), "pass");
在共享网络托管服务器上,我收到错误:
System.Security.Cryptography.CryptographicException: An internal error occurred.
堆栈跟踪结束于
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
在我的开发机器上加载正常。 我加载 *.pfx 而不是 *.cer 文件的原因是因为我需要私钥访问(cer 文件加载正常)。 我在我的开发机上制作了 pfx:
makecert -r -n "CN=myhost.com, E=admin@myhost.com" -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>
我使用的是 makecert v5.131.3790.0 版本
最佳答案
使用本地计算机商店获取私钥:
X509Certificate2 cert = new X509Certificate2("myhost.pfx", "pass",
X509KeyStorageFlags.MachineKeySet);
MachineKeySet
被描述为“私钥存储在本地计算机存储而不是当前用户存储”。没有标志的默认值是放置在用户存储中。
即使您从磁盘读取证书并将其存储在对象中,私钥仍存储在 Microsoft Cryptographic API 加密服务提供商 key 数据库中。在托管服务器上,ASP.NET 进程没有访问用户存储的权限。
另一种方法(根据下面的一些评论)是修改 IIS 配置或应用程序池标识——这确实有效。但是,这假设可以访问这些配置项,而实际情况可能并非如此(例如,在共享主机环境中)。
关于c# - 使用 X509Certificate2 加载 pfx 文件时为 "An internal error occurred.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1345262/