Generating self-signed certificate without external libraries Generating self-signed certificate without external libraries powershell powershell

Generating self-signed certificate without external libraries


There's nothing to create certificates in any released version of .NET.

.NET Core 2.0 (which hasn't released yet, but should soon) has and .NET Framework 4.7.2 have added this functionality via CertificateRequest (an API which can do self-signed certs, chain-signed certs, or PKCS#10 certificate/certification signing requests).

The PowerShell command is combining three things:

  • Key Storage Parameters (the CSP)
  • Certificate Creation
  • Certificate Storage (the store to add the cert to)

To create a "few-frills" self-signed certificate good for TLS server authentication on localhost:

X509Certificate2 certificate = null;var sanBuilder = new SubjectAlternativeNameBuilder();sanBuilder.AddDnsName("localhost");// New .NET Core Create(int) method.  Or use// rsa = RSA.Create(), rsa.KeySize = newRsaKeySize,// or (on .NET Framework) new RSACng(newRsaKeySize)using (RSA rsa = RSA.Create(newRsaKeySize)){    var certRequest = new CertificateRequest(        $"CN=localhost",        rsa,        HashAlgorithmName.SHA256,        RSASignaturePadding.Pkcs1);    // Explicitly not a CA.    certRequest.CertificateExtensions.Add(        new X509BasicConstraintsExtension(false, false, 0, false));    certRequest.CertificateExtensions.Add(        new X509KeyUsageExtension(            X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment,            true));    // TLS Server EKU    certRequest.CertificateExtensions.Add(        new X509EnhancedKeyUsageExtension(            new OidCollection            {                new Oid("1.3.6.1.5.5.7.3.1"),            },            false));    // Add the SubjectAlternativeName extension    certRequest.CertificateExtensions.Add(sanBuilder.Build());    DateTimeOffset now = DateTimeOffset.UtcNow;    certificate = certRequest.CreateSelfSigned(now, now.AddDays(365.25));}

The certificate this created has an ephemeral private key -- it's not currently written to disk. If you don't care what key storage provider it uses then at this point your best bet would be to export the certificate (and private key) as a PFX/PKCS#12, then re-import it with PersistKeySet (and Exportable, since you want that), and add the imported copy to the X509Store of your choosing.

If you care about the key storage provider (in your case, a CAPI CSP), or you want to avoid export/import, you can create it using a pre-persisted key. So you'd replace RSA.Create(newRsaKeySize) with

CAPI:

var cspParameters = new CspParameters(    /* PROV_RSA_AES */ 24,    "Microsoft Enhanced RSA and AES Cryptographic Provider",    Guid.NewGuid().ToString());using (RSA rsa = new RSACryptoServiceProvider(newRsaKeySize, cspParameters))

CNG:

var keyParams = new CngKeyCreationParameters();keyParams.Parameters.Add(    new CngProperty(        "Length",        BitConverter.GetBytes(newRsaKeySize),        CngPropertyOptions.Persist));using (CngKey rsaKey = CngKey.Create(CngAlgorithm.RSA, Guid.NewGuid().ToString(), keyParams)using (RSA rsa = new RSACng(rsaKey))

And then add it to an open X509Store instance in the usual way.

it feels like that if I knew enough how to construct certificates, it'd be possible to create a byte array template or such and use that in the X509Certificate2 constructor.

True. But it is a tad bit tricky. You'd need to learn ASN.1 (ITU-T X.680), DER (ITU-T X.690) and X.509 (either RFC 5280 or ITU-T X.509). If you wanted to create the certificate mated with the private key you'd then need to learn PFX/PKCS#12 (RFC 7292, though limited to some of the older options unless you're Win10-only) and that has a bunch of prerequisite knowledge, too.

I think these are all fun things to learn about, and good things to know... but my colleagues give me strange looks when I start doodling DER on a whiteboard, so I probably don't represent the average developer opinion of "fun".