c# - RSAParameters 到 pfx (X509Certificate2) 的转换

标签 c# .net security pfx rsacryptoserviceprovider

我想根据 RSACryptoServiceProvider 创建的 key 创建一个 pfx 文件。 我试过:

certificate.PrivateKey =  rsa as AsymmetricAlgorithm;

这是相反的:

rsa = (RSACryptoServiceProvider)certificate.PrivateKey;

这似乎有效(即第二个)。但是出现以下错误:

m_safeCertContext is an invalid handle.

我尝试了一些使用 RSAParameters 的方法 - 但无济于事。

最佳答案

您可以使用 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;

关于c# - RSAParameters 到 pfx (X509Certificate2) 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17488757/

相关文章:

asp.net - 将 packageReference 和 packages.config 混合在一个解决方案中?

javascript - 前端游戏如何安全提交高分防止post劫持

java.security.AccessControlException : access denied ("java.util.PropertyPermission" "jna.boot.library.path" "read")

c# - ActionResult 的不同结果

c# - EF 4.3 关系不正确

c# - 如何在wpf中的tabitem上制作标签拉伸(stretch)

asp.net - 在 SQL SERVER 2005 上启用 CLR 是否存在任何安全问题?

c# - 如何在异常中显示对象列表?

.net - 控制台应用程序相对于 Windows 服务的好处

c# - 每个程序集一个命名空间?