【问题标题】:C# X509Certificate2.PrivateKey threw exception "invalid provider type specified."C# X509Certificate2.PrivateKey 抛出异常“指定的提供程序类型无效”。
【发布时间】:2021-06-05 06:12:01
【问题描述】:

我在 Windows Server 2019 上安装了受信任的 CA 颁发的 SSL 证书。当 ASP.NET MVC 控制器中的以下代码运行时,它确实检索到 X509Certificate2,它的 HasProviateKey 属性为 true强>。但是当它的 PrivateKey 属性被访问时,它抛出了 CryptographicException: "invalid provider type specified."

    X509Certificate2 certificate = null;
    X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    userCaStore.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
    X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindByThumbprint, "xyz...", true);

    if (findResult.Count != 1)
        throw new Exception("Certificate not found.");

    certificate = findResult[0];
    userCaStore.Close();

我需要访问私钥的原因是服务器需要接受一些持久的 TCP 套接字连接,并且我计划使用 SSL 证书的公钥/私钥进行典型的握手:客户端生成一个随机 AES 密钥,并使用公钥加密此 AES 密钥并将其发送到服务器。这就是为什么我需要访问服务器端的私钥来解密 AES 密钥。

我该怎么做?

【问题讨论】:

  • 您应该使用cert.GetRSAPrivateKey() 而不是cert.PrivateKey,这应该可以解决您的问题。
  • 谢谢。我试过。 cert.GetRSAPrivateKey() 取回一个 RSACng,但 cert.PublicKey.Key 取回一个 RSACryptoServiceProvider。我尝试使用 RSACryptoServiceProvider 加密并使用 RSACng 解密,但它不起作用。请指教。谢谢。
  • 我试过这段代码,它抛出异常“密钥在指定状态下无效。”:RSACng rsa = (RSACng)certificate.GetRSAPrivateKey(); rsa.Key.SetProperty(new CngProperty("导出策略", itConverter.GetBytes((int)CngExportPolicies.AllowPlaintextExport), ngPropertyOptions.Persist));
  • 如果您只想解密,不知道为什么要搞乱导出策略……只需 GetRSAPrivateKey 并在该实例上调用 Decrypt。
  • 感谢您的回答。如果您提供答案,那么我可以将其标记为解决方案。

标签: ssl-certificate x509certificate2


【解决方案1】:

我部分地想通了。它与 SSL 证书的加密类型有关。我尝试使用相同的代码来检索另一个受信任的 CA 颁发的证书,并且 PrivateKey 属性确实显示为 RsaCryptoServiceProvider。必须做的另一件事是右键单击证书存储 (mmc.exe) 中的证书并选择“所有任务 | 管理私钥”,并确保您的代码使用的身份存在于 ACL 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2018-01-08
    • 2019-02-03
    • 2017-05-19
    • 2012-06-21
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多