BouncyCastle PrivateKey To X509Certificate2 PrivateKey

时间:2011-05-25 17:40:41

标签: c# .net cryptography x509certificate bouncycastle

我使用BouncyCastle

创建证书
        var keypairgen = new RsaKeyPairGenerator();
        keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));

        var keypair = keypairgen.GenerateKeyPair();

        var gen = new X509V3CertificateGenerator();

        var CN = new X509Name("CN=" + certName);
        var SN = BigInteger.ProbablePrime(120, new Random());

        gen.SetSerialNumber(SN);
        gen.SetSubjectDN(CN);
        gen.SetIssuerDN(CN);
        gen.SetNotAfter(DateTime.Now.AddYears(1));
        gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7,0,0,0)));
        gen.SetSignatureAlgorithm("MD5WithRSA");
        gen.SetPublicKey(keypair.Public);

        gen.AddExtension( 
            X509Extensions.AuthorityKeyIdentifier.Id, 
            false, 
            new AuthorityKeyIdentifier( 
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public), 
                new GeneralNames(new GeneralName(CN)), 
                SN 
            )); 

        gen.AddExtension( 
            X509Extensions.ExtendedKeyUsage.Id, 
            false, 
            new ExtendedKeyUsage(new ArrayList() 
            { 
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") 
            }));

        var newCert = gen.Generate(keypair.Private);

这样结束

X509Certificate2 certificate = new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));

现在,因为我的作业告诉我将证书和PrivateKey存储在X509Certificate2对象中,我需要一种方法将keypair.Private转换为X509Certificate2.Private。有什么想法吗?

感谢。

4 个答案:

答案 0 :(得分:6)

请大家详细说明,这是在创建X509Certificate2证书后添加的完整代码:

RSA rsaPriv = DotNetUtilities.ToRSA(keypair.Private as RsaPrivateCrtKeyParameters);
certificate.PrivateKey = rsaPriv;

(当然可以将其优化为一行。)

答案 1 :(得分:5)

对于任何尝试将X509Certificate2导出到PKCS12并保留私钥的人。这就是我必须要做的事情:

        // Convert BouncyCastle X509 Certificate to .NET's X509Certificate
        var cert = DotNetUtilities.ToX509Certificate(certificate);
        var certBytes = cert.Export(X509ContentType.Pkcs12, "password");

        // Convert X509Certificate to X509Certificate2
        var cert2 = new X509Certificate2(certBytes, "password");

        // Convert BouncyCastle Private Key to RSA
        var rsaPriv = DotNetUtilities.ToRSA(issuerKeyPair.Private as RsaPrivateCrtKeyParameters);

        // Setup RSACryptoServiceProvider with "KeyContainerName" set
        var csp = new CspParameters();
        csp.KeyContainerName = "KeyContainer";

        var rsaPrivate = new RSACryptoServiceProvider(csp);

        // Import private key from BouncyCastle's rsa
        rsaPrivate.ImportParameters(rsaPriv.ExportParameters(true));

        // Set private key on our X509Certificate2
        cert2.PrivateKey = rsaPrivate;

        // Export Certificate with private key
        File.WriteAllBytes(@"C:\Temp\cert.pfx", cert2.Export(X509ContentType.Pkcs12, "password"));

答案 2 :(得分:4)

如果您查看this question中的链接,您应该可以使用与DotNetUtilities.ToRSA(...)类似的内容,并将其返回值放入X509Certificate2的{​​{1}}。

答案 3 :(得分:0)

我想分享我的方法:

使用充气城堡的pfx到System.Security.Cryptography.X509Certificates.X509Certificate2。

        public static X509Certificate2 OpenCertificate(string pfxPath, string contrasenia)
    {
        System.Security.Cryptography.X509Certificates.X509Certificate2 x509 = default(System.Security.Cryptography.X509Certificates.X509Certificate2);

        MemoryStream ms = new MemoryStream(File.ReadAllBytes(pfxPath));

        Org.BouncyCastle.Pkcs.Pkcs12Store st = new Org.BouncyCastle.Pkcs.Pkcs12Store(ms, contrasenia.ToCharArray());

        var alias = st.Aliases.Cast<string>().FirstOrDefault(p => st.IsCertificateEntry(p));
        Org.BouncyCastle.Pkcs.X509CertificateEntry keyEntryX = st.GetCertificate(alias);

        x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(DotNetUtilities.ToX509Certificate(keyEntryX.Certificate));

        alias = st.Aliases.Cast<string>().FirstOrDefault(p => st.IsKeyEntry(p));
        Org.BouncyCastle.Pkcs.AsymmetricKeyEntry keyEntry = st.GetKey(alias);
        System.Security.Cryptography.RSACryptoServiceProvider intermediateProvider = (System.Security.Cryptography.RSACryptoServiceProvider)Org.BouncyCastle.Security.DotNetUtilities.ToRSA((Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)keyEntry.Key);

        x509.PrivateKey = intermediateProvider;

        return x509;
    }