RSAParameters转换为pfx格式(X509Certificate2)

3
我希望能够从由RSACryptoServiceProvider创建的密钥中创建一个pfx文件。 我尝试了以下方法:
certificate.PrivateKey =  rsa as AsymmetricAlgorithm;

这是与之相反的操作:

rsa = (RSACryptoServiceProvider)certificate.PrivateKey;

似乎可以工作(第二个)。但是出现了以下错误:

m_safeCertContext是无效的句柄。

我尝试使用RSAParameters做一些事情,但都没有成功。

1个回答

0

您可以使用Bouncy Castle来实现:

private static byte[] MergePFXFromPrivateAndCertificate(RSAParameters privateKey, X509Certificate2 certificate, string pfxPassPhrase)
{
    RsaPrivateCrtKeyParameters rsaParam = new RsaPrivateCrtKeyParameters(
        ParseAsUnsignedBigInteger(privateKey.Modulus),
        ParseAsUnsignedBigInteger(privateKey.Exponent),
        ParseAsUnsignedBigInteger(privateKey.D),
        ParseAsUnsignedBigInteger(privateKey.P),
        ParseAsUnsignedBigInteger(privateKey.Q),
        ParseAsUnsignedBigInteger(privateKey.DP),
        ParseAsUnsignedBigInteger(privateKey.DQ),
        ParseAsUnsignedBigInteger(privateKey.InverseQ)
    );

    Org.BouncyCastle.X509.X509Certificate bcCert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(certificate.RawData);

    MemoryStream p12Stream = new MemoryStream();
    Pkcs12Store p12 = new Pkcs12Store();
    p12.SetKeyEntry("key", new AsymmetricKeyEntry(rsaParam), new X509CertificateEntry[] { new X509CertificateEntry(bcCert) });
    p12.Save(p12Stream, pfxPassPhrase.ToCharArray(), new SecureRandom());

    return p12Stream.ToArray();
}

private static BigInteger ParseAsUnsignedBigInteger(byte[] rawUnsignedNumber)
{
    return new BigInteger(1, rawUnsignedNumber, 0, rawUnsignedNumber.Length);
}

你需要以下名称空间:

using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接