我想在我的ASP.Net Core 2.0(配备Kestrel web服务器)应用程序中使用HTTPS。
官方文档使用pfx格式,但我想直接使用PEM格式(从Let's encrypt生成),而不需要进行任何转换(至少不在我的C#代码之外)。这是否可行?
我想在我的ASP.Net Core 2.0(配备Kestrel web服务器)应用程序中使用HTTPS。
官方文档使用pfx格式,但我想直接使用PEM格式(从Let's encrypt生成),而不需要进行任何转换(至少不在我的C#代码之外)。这是否可行?
var pem = File.ReadAllText("path/to/my.pem");
var key = X509Certificate2.CreateFromPem(pem);
如果您需要私钥和公钥,
var certPem = File.ReadAllText("path/to/fullchain.pem");
var keyPem = File.ReadAllText("path/to/privkey.pem");
var x509 = X509Certificate2.CreateFromPem(certPem, keyPem);
然后可以像这样将其挂钩到Kestrel中:
webApplicationBuilder.WebHost.ConfigureKestrel(s => {
s.ListenAnyIP(443, options => {
options.UseHttps(x509);
}
也许还可以看一下https://www.scottbrady91.com/c-sharp/pem-loading-in-dotnet-core-and-dotnet。
好消息是,.NET计划在未来支持加载密钥(https://github.com/dotnet/corefx/issues/20414),但由于目前还没有完成(更不用说发布了),这并不能帮助您。
{
"Kestrel": {
"Certificates": {
"Default": {
"Path": "<path to .pem/.crt file>",
"KeyPath": "<path to .key file>",
"Password": "$CREDENTIAL_PLACEHOLDER$"
}
}
}
}
openssl pkcs12 -inkey privkey.pem -in cert.pem -export -out cert_pfx.pfx
然后会提示您输入密码。将 cert_pfx.pfx 复制到 dotnet 发布文件夹中,最后在 Program.cs 中更改:.UseKestrel(options => { options.Listen(IPAddress.Any, 3000, listenOptions => { listenOptions.UseHttps("cert_pfx.pfx", "选择的密码"); }); //https } )
- David Soler