Created
December 26, 2020 16:00
-
-
Save yetanotherchris/c4568aeb005e191a741294618f977f30 to your computer and use it in GitHub Desktop.
Loading PEM SSL certificates in Kestrel (Windows work-around)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See https://github.com/dotnet/runtime/issues/23749 | |
public static class CertHelper | |
{ | |
// To generate a self-signed cert: | |
// dotnet dev-certs https -ep $pwd/selfsigned.pem --format Pem -np | |
public static X509Certificate2 GetCertificate() | |
{ | |
X509Certificate2 sslCert = CreateFromPublicPrivateKey("certs/selfsigned.pem", "certs/selfsigned.key"); | |
// work around for Windows (WinApi) problems with PEMS, still in .NET 5 | |
return new X509Certificate2(sslCert.Export(X509ContentType.Pkcs12)); | |
} | |
public static X509Certificate2 CreateFromPublicPrivateKey(string publicCert="certs/public.pem", string privateCert="certs/private.pem") | |
{ | |
byte[] publicPemBytes = File.ReadAllBytes(publicCert); | |
using var publicX509 = new X509Certificate2(publicPemBytes); | |
var privateKeyText = File.ReadAllText(privateCert); | |
var privateKeyBlocks = privateKeyText.Split("-", StringSplitOptions.RemoveEmptyEntries); | |
var privateKeyBytes = Convert.FromBase64String(privateKeyBlocks[1]); | |
using RSA rsa = RSA.Create(); | |
if (privateKeyBlocks[0] == "BEGIN PRIVATE KEY") | |
{ | |
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _); | |
} | |
else if (privateKeyBlocks[0] == "BEGIN RSA PRIVATE KEY") | |
{ | |
rsa.ImportRSAPrivateKey(privateKeyBytes, out _); | |
} | |
X509Certificate2 keyPair = publicX509.CopyWithPrivateKey(rsa); | |
return keyPair; | |
} | |
} | |
// Your program.cs | |
public static IHostBuilder CreateHostBuilder(string[] args) | |
{ | |
return Host.CreateDefaultBuilder(args) | |
.UseSerilog() | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
webBuilder.ConfigureKestrel(options => | |
{ | |
options.ConfigureHttpsDefaults(adapterOptions => | |
{ | |
adapterOptions.ServerCertificate = CertHelper.GetCertificate(); | |
}); | |
}); | |
webBuilder.UseStartup<Startup>(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment