private static X509Certificate2 CreateCertificate(string subject, DateTimeOffset notBefore, DataTimeOffset notAfter, string issuer, AsymmetricKeyParamter issuerPrivateKey)
{
// Setup
X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
SecureRandom random = new SecureRandom(new CryptoApiRandomGenerator());
RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(new KeyGenerationParameters(random, KeyStrength));
// Randomly generate a serial number
BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
certGenerator.SetSerialNumber(serialNumber);
// Set the issuer and subject names
X509Name issuerName = new X509Name(issuer);
X509Name subjectName = new X509Name(subject);
certGenerator.SetIssuerDN(issuerName);
certGenerator.SetSubjectDN(subjectName);
// Set the validity period
certGenerator.SetNotBefore(notBefore.UtcDateTime);
certGenerator.SetNotAfter(notAfter.UtcDateTime);
// Randomly generate the public key
AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certGenerator.SetPublicKey(subjectKeyPair.Public);
// Generate the signed certificate
ISignatureFactory signatureFactory = new Asn1SignatureFactory(SHA256RSASignatureAlgorithm, issuerPrivateKey ?? subjectKeyPair.Private, random);
X509Certificate2 certificate = new X509Certificate2(certGenerator.Generate(signatureFactory).GetEncoded());
// Include the private key with the response
// ERROR HERE!
certificate.PrivateKey = DotNetUtilities.ToRSA(subjectKeyPair.Private as RsaPrivateCrtKeyParameters);
return certificate;
}
这段代码位于一个针对.NET Standard 2.0的库中,该库是两个不同应用程序的依赖项:一个针对.NET Core 2.1,另一个针对.NET Framework 4.7.2。我相信在.NET Framework应用程序中这可以正常工作,但在.NET Core应用程序中,我在上面指示的行收到了一个异常,其消息为:“此平台不支持该操作。”
显然,这是.NET Core的预期行为。我知道CopyWithPrivateKey
方法,如this question中所述,理论上我应该使用它。然而,此方法不受.NET Standard 2.0支持(请注意页面顶部的错误指示重定向)。此外,由于其他一些依赖关系是.NET Framework,因此目前无法将.NET Framework应用程序转换为.NET Core。根据this matrix,.NET Standard 2.1根本不受.NET Framework支持,这意味着我不能升级到.NET Standard 2.1并使用CopyWithPrivateKey
!
我如何在.NET Standard 2.0中创建一个带有私钥的X509Certificate2
,以一种与.NET Core兼容的方式?