Search code examples
c#asp.net-core.net-coressl-certificatekestrel-http-server

How to use PEM certificate in Kestrel directly?


I want to use HTTPS in my ASP.Net Core 2.0 (with Kestrel web server) application.

The official documentation uses pfx format, but I want to use PEM format (generated from Let's encrypt) directly without any conversion (at least nothing outside my C# code). Is is possible?


Solution

  • Update: You can in .NET 5+! It has already been described on this question by Iain: https://stackoverflow.com/a/72816407/6535399, or directly from config as paths, as answered by carlin.scott: https://stackoverflow.com/a/75178736/6535399


    Original Answer:

    The short answer is that you can't. At least, you can't without a whole lot of work or using something like Bouncy Castle.

    When the cert and the key are put together into a PFX the X509Certificate2 object will have cert.HasPrivateKey == true, and is capable of using the private key via the Get[Algorithm]PrivateKey extension method family. When you load a PEM certificate only the public certificate portion is loaded (and if it's a PEM certificate with a PEM key glued onto it? That's still just a PEM certificate).

    The easy way to get a private key associated with a certificate is with the new (in .NET Core 2.0) certWithKey = cert.CopyWithPrivateKey(key) extension method family. So now you "just" need to load the private key. .NET does not currently have the ability to load (or save) ".key" files (no matter what their extension). If you want to take a crack at loading one you might want to check some prior art:

    The good news is that .NET is planning to support loading keys in the future (https://github.com/dotnet/corefx/issues/20414), but since it isn't done yet (much less released) that doesn't help you right now.