c# - 设置 X509Certificate2 PrivateKey 时出错

标签 c# .net-core

我正在将 .NetFramework 4.6.1 库迁移到 .NetCore 2.2。 但我无法设置 x509certificate.PrivateKey,如下所示。

我已读到这可能是由于 RSAServiceProvider 造成的,但我不知道如何设置此属性。甚至实例化:
x509certificate.PrivateKey = new RSACryptoServiceProvider();
抛出 PlatformNotSupportedException。

// selfsign certificate
Org.BouncyCastle.X509.X509Certificate certificate = 
certificateGenerator.Generate(signatureFactory);

// correponding private key
PrivateKeyInfo info = 
PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

// merge into X509Certificate2
var x509certificate = new X509Certificate2(certificate.GetEncoded());

Asn1Sequence seq = (Asn1Sequence)
Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded() 
);

RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq);
RsaPrivateCrtKeyParameters rsaParams = new 
RsaPrivateCrtKeyParameters(
rsa.Modulus,
rsa.PublicExponent,
rsa.PrivateExponent,
rsa.Prime1,
rsa.Prime2,
rsa.Exponent1,
rsa.Exponent2,
rsa.Coefficient);

x509certificate.PrivateKey = DotNetUtilities.ToRSA(rsaParams);

在 .NetCore 库中,使用 DotNetUtilities.ToRSA(rsaParams) 中的 RSA 设置 x509certificate.PrivateKey 会引发 PlatformNotSupportedException。

System.PlatformNotSupportedException
  HResult=0x80131539
  Message=Operation is not supported on this platform.
  Source=System.Security.Cryptography.X509Certificates
  StackTrace:
   at System.Security.Cryptography.X509Certificates.X509Certificate2.set_PrivateKey(AsymmetricAlgorithm value)

最佳答案

正如 LexLi 所说,在 .net core 中设计不可能在现有证书上设置私钥。

按照描述here ,您可以使用 RSACertificateExtensions.CopyWithPrivateKey 方法。

而不是

x509certificate.PrivateKey = DotNetUtilities.ToRSA(rsaParams);

你可以有

var rsa = DotNetUtilities.ToRSA(rsaParams);
var cert = x509certificate.CopyWithPrivateKey(rsa);
return cert;

要访问“CopyWithPrivateKey”扩展方法,请使用以下命令添加:

using System.Security.Cryptography.X509Certificates; /* for getting access to extension methods in RSACertificateExtensions */

"(CopyWithPrivateKey) Combines a private key with the public key of an RSA certificate to generate a new RSA certificate."

https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.rsacertificateextensions.copywithprivatekey?view=netcore-3.0

关于c# - 设置 X509Certificate2 PrivateKey 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54752834/

相关文章:

c# - 如何将 Asp.Net Identity 与 Azure AD 授权相结合

c# - 让 dotnet core 2.0.0 Socket.Listen() 支持 UNIX Domain Socket?

c# - 试图找出模型和 DbContext : 'Employee' 的 EntityFramework 元数据

.net-core - .Net Core 2.1 asp-for 标签不起作用

c# - 使用 LINQ .OrderByDescending 不起作用

c# - 寻找一种 Android 解决方案来阻止单击选项卡更改为新页面

c# - LINQ 中的动态查询

C# 吉他英雄克隆,注意动画时序

asp.net-mvc - 在 MVC 中使用 dotnet core 时如何删除 ErrorViewModel

ASP.NET 5 DNX : How to shutdown application properly?