how to create a completely new x509Certificate2 in .net?

travellover picture travellover · Feb 23, 2010 · Viewed 24.7k times · Source

I google it from web, find many samples to generate a new x509Certificate2 from a file in .net, but there is no one sample to show how to generate a completely new x509Certificate2 from the beginning in .net.

Is there any one that can tell me how to do it in .net?

Thank you very much.

Answer

Arsen Zahray picture Arsen Zahray · Feb 12, 2012

Here's a code you can use:

    static X509Certificate2 GenerateCertificate(string certName)
    {
        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.MaxValue);
        gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
        gen.SetSignatureAlgorithm("MD5WithRSA");
        gen.SetPublicKey(keypair.Public);           

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

        return new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));
    }

for this to work, don't forget to add reference to BouncyCastle library