Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 269
Mohammed Noureldin Avatar asked Jan 03 '18 12:01

Mohammed Noureldin


People also ask

How do I open a PEM certificate?

Navigate to Advanced > Certificates > Manage Certificates > Your Certificates > Import. From the "File name:" section of the Import window, choose Certificate Files from the drop-down, and then find and open the PEM file.

How does PEM certificate work?

Privacy Enhanced Mail (PEM) files are concatenated certificate containers frequently used in certificate installations when multiple certificates that form a complete chain are being imported as a single file. They are a defined standard in RFCs 1421 through 1424.


1 Answers

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:

  • How to parse(Convert to RSAParameters) X.509 private key in C#?
  • Create RSACryptoServiceProvider object using RSA private key file in C#
  • How is a private key encrypted in a pem certificate?
  • Export private/public keys from X509 certificate to PEM

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.

like image 108
bartonjs Avatar answered Sep 30 '22 05:09

bartonjs