我正在将 .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."
关于c# - 设置 X509Certificate2 PrivateKey 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54752834/