简体   繁体   English

RSAParameters到pfx(X509Certificate2)转换

[英]RSAParameters to pfx (X509Certificate2) conversion

I want to create a pfx file from keys created by RSACryptoServiceProvider . 我想从RSACryptoServiceProvider创建的密钥创建一个pfx文件。 I tried: 我试过了:

certificate.PrivateKey =  rsa as AsymmetricAlgorithm;

which is the reverse of: 这是相反的:

rsa = (RSACryptoServiceProvider)certificate.PrivateKey;

which seems to work (the second, that is). 这似乎工作(第二,也就是说)。 But got the following error: 但得到以下错误:

m_safeCertContext is an invalid handle. m_safeCertContext是一个无效的句柄。

I tried some things using RSAParameters - but to no avail. 我尝试了一些使用RSAParameters的东西 - 但无济于事。

You can use Bouncy Castle to do it: 你可以使用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);
}

You will need the following namespaces: 您将需要以下命名空间:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM