【问题标题】:Error during create X509Certificate2 object on IIS server在 IIS 服务器上创建 X509Certificate2 对象时出错
【发布时间】:2021-12-07 05:13:40
【问题描述】:

我在创建 X509Certificate2 对象时遇到问题。

private void OpenKey()
{
    if (!File.Exists(KeyFile))
    {
        return;
    }

    cert = new X509Certificate2(File.ReadAllBytes(KeyFile), KeyPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
    securityKey = new X509SecurityKey(cert);
}

在本地主机上这工作正常,在开发服务器上也是如此,但在生产服务器上我有错误:

Exception: System.Security.Cryptography.CryptographicException: An internal error occurred. at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) at System.Security.Cryptography.X509Certificates.X509Utils.LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle pCertCtx) at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags) 

我在 .NET Framework 4.5.2 上工作。

我能做些什么来解决这个问题?

【问题讨论】:

  • 用户可能没有足够的权限将私钥保存在机器存储中。

标签: c# asp.net .net iis x509certificate2


【解决方案1】:

@Hazrelle 在 cmets 中是正确的,应用程序池无权将私钥保存在本地机器存储中(需要管理员/系统权限)。

而且,实际上,您不应持久保存您动态加载的证书及其密钥,并且不打算持久保存它们。我有博客文章更详细地解释了这一点:https://www.pkisolutions.com/handling-x509keystorageflags-in-applications/

要解决您的问题,您应该跳过构造函数中的所有存储标志,即:

cert = new X509Certificate2(File.ReadAllBytes(KeyFile), KeyPassword);

并将证书参考保存在课堂上的某处,以便您可以调用

cert.Dispose();

在完成使用证书后(在签署 JWT 之后)从文件系统中删除私钥材料。

【讨论】:

  • 我尝试了你的建议,但它仍然不起作用。尝试将“加载用户配置文件”设置为 False 和 True,结果相同。
猜你喜欢
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2016-11-18
相关资源
最近更新 更多