【发布时间】: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