Create a Self-Signed Digital Certificate in C#

void CreateDigitalCertificate()
{
    X509CertificateGenerator certGenerator = new X509CertificateGenerator("");

    //set the validity of the certificate
    certGenerator.ValidFrom = DateTime.Now;
    //set the certificate expiration date
    certGenerator.ValidTo = DateTime.Now.AddYears(2);

    //set the signing algorithm and the key size
    certGenerator.KeySize = KeySize.KeySize2048Bit;
    certGenerator.SignatureAlgorithm = SignatureAlgorithm.SHA256WithRSA;

    //set the certificate sobject
    certGenerator.Subject = "CN=Digital Signature Certificate, OU=Organization Unit, E=user@email.com";

    //add some simple extensions to the client certificate
    certGenerator.Extensions.AddKeyUsage(CertificateKeyUsage.DigitalSignature);
    certGenerator.Extensions.AddKeyUsage(CertificateKeyUsage.DataEncipherment);

    //add some enhanced extensions to the client certificate marked as critical
    certGenerator.Extensions.AddEnhancedKeyUsage(CertificateEnhancedKeyUsage.SecureEmail);

    byte[] userCert = certGenerator.GenerateCertificate("PfxCertificatePassword");

    //verify certificate
    var verifyCert = new X509Certificate2(userCert, "PfxCertificatePassword");

    //save the certificate
    File.WriteAllBytes("userCertificate.pfx", userCert);
}

See also: