【问题标题】:RSAParameters to pfx (X509Certificate2) conversionRSAParameters 到 pfx (X509Certificate2) 的转换
【发布时间】:2013-07-03 13:11:09
【问题描述】:

我想用 RSACryptoServiceProvider 创建的密钥创建一个 pfx 文件。 我试过了:

certificate.PrivateKey =  rsa as AsymmetricAlgorithm;

与以下相反:

rsa = (RSACryptoServiceProvider)certificate.PrivateKey;

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

m_safeCertContext 是无效句柄。

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

【问题讨论】:

    标签: c# .net security pfx rsacryptoserviceprovider


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 2012-03-04
      • 2010-09-29
      • 2018-10-06
      • 1970-01-01
      • 2011-10-06
      • 2021-09-16
      • 1970-01-01
      • 2011-10-12
      相关资源
      最近更新 更多