C# – How to create a self-signed certificate using C#

ccertificatenetself-signed

I need to create a self-signed certificate (for local encryption – it's not used to secure communications), using C#.

I've seen some implementations that use P/Invoke with Crypt32.dll, but they are complicated and it's hard to update the parameters – and I would also like to avoid P/Invoke if at all possible.

I don't need something that is cross platform – running only on Windows is good enough for me.

Ideally, the result would be an X509Certificate2 object that I can use to insert into the Windows certificate store or export to a PFX file.

Best Answer

Since .NET 4.7.2 you can create self-signed certs using System.Security.Cryptography.X509Certificates.CertificateRequest.

For example:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public class CertificateUtil
{
    static void MakeCert()
    {
        var ecdsa = ECDsa.Create(); // generate asymmetric key pair
        var req = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256);
        var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));

        // Create PFX (PKCS #12) with private key
        File.WriteAllBytes("c:\\temp\\mycert.pfx", cert.Export(X509ContentType.Pfx, "P@55w0rd"));

        // Create Base 64 encoded CER (public key only)
        File.WriteAllText("c:\\temp\\mycert.cer",
            "-----BEGIN CERTIFICATE-----\r\n"
            + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
            + "\r\n-----END CERTIFICATE-----");
    }
}