Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BouncyCastle PrivateKey To X509Certificate2 PrivateKey

I create a certificate using 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);

This end with

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

Now, because my assignment tells me to store both the Certificate and the PrivateKey in the X509Certificate2 object I need a way to convert the keypair.Private into a X509Certificate2.Private. Any ideas?

Thanks.

like image 513
barjed Avatar asked May 25 '11 17:05

barjed


2 Answers

Just be be verbose, this is the full code to add after creation of X509Certificate2 certificate:

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

(Which of course can be optimised into one line.)

like image 114
Ben Avatar answered Sep 19 '22 15:09

Ben


If you look at the links from this question, you should be able to use something similar to DotNetUtilities.ToRSA(...) and put its return value into the X509Certificate2's PrivateKey.

like image 44
Bruno Avatar answered Sep 18 '22 15:09

Bruno