我们正在尝试使用C#和BouncyCastle库以编程方式生成X509证书(包括私钥).我们尝试使用Felix Kollmann的这个示例中的一些代码,但证书的私钥部分返回null.代码和单元测试如下:
using System;
using System.Collections;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
namespace MyApp
{
public class CertificateGenerator
{
/// <summary>
///
/// </summary>
/// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
/// <param name="subjectName"></param>
/// <returns></returns>
public static byte[] GenerateCertificate(string subjectName)
{
var kpgen = new RsaKeyPairGenerator();
kpgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
var kp = kpgen.GenerateKeyPair();
var gen = new X509V3CertificateGenerator();
var certName = new X509Name("CN=" + subjectName); …Run Code Online (Sandbox Code Playgroud) 我正在将.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);
Run Code Online (Sandbox Code Playgroud)
在.NetCore库中,将x509certificate.PrivateKey与DotNetUtilities.ToRSA(rsaParams)中的RSA一起设置,将引发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)
Run Code Online (Sandbox Code Playgroud)