Создайте X509Certificate2 из файлов .crt и .key с помощью встроенного API ASP.NET Core 3.0.C#

Место общения программистов C#
Anonymous
Создайте X509Certificate2 из файлов .crt и .key с помощью встроенного API ASP.NET Core 3.0.

Сообщение Anonymous »

Я разрабатываю веб-приложение с использованием ASP.NET Core 3.0 предварительной версии 8.
Я хочу создать X509Certificate2 непосредственно из файлов .crt и .key (PKCS #11), чтобы использовать его с Kestrel с помощью нового встроенного API .NET Core 3.0, который был представлен на этой странице:
Что новое в .NET Core 3.0 (предварительная версия 8)
В настоящее время я использую эту команду для преобразования сертификата в файл .pfx:
openssl pkcs12 -export -in $CERTIFICATE_FILE -inkey $KEY_FILE -out $OUTPUT_CERTIFICATE_FILE -passout pass:$OUTPUT_CERTIFICATE_PASSWORD

Затем я создаю X509Certificate2 и использую его с Kestrel:
webBuilder.ConfigureKestrel((context, options) =>
{
options.ConfigureHttpsDefaults(httpsOptions =>
{
if (!context.HostingEnvironment.IsProduction())
return;

string outputCertificateFile = context.Configuration["OUTPUT_CERTIFICATE_FILE"];
string outputCertificatePassword = context.Configuration["OUTPUT_CERTIFICATE_PASSWORD"];

var tlsCertificate = new X509Certificate2(outputCertificateFile, outputCertificatePassword);
httpsOptions.ServerCertificate = tlsCertificate;
});
});

Я реализовал новый API на основе примера на странице выше:
using (var privateKey = RSA.Create())
{
byte[] keyBytes = File.ReadAllBytes(context.Configuration["KEY_FILE"]);

privateKey.ImportRSAPrivateKey(keyBytes, out int bytesRead);

X509Certificate2 certificateFile = new X509Certificate2(context.Configuration["CERTIFICATE_FILE"]);

X509Certificate2 tlsCertificate = certificateFile.CopyWithPrivateKey(privateKey);

httpsOptions.ServerCertificate = tlsCertificate;
}

Но новый код выдает это исключение:
Unhandled exception. System.Security.Cryptography.CryptographicException: ASN1 corrupted data.
at System.Security.Cryptography.Asn1.AsnReader.CheckExpectedTag(Asn1Tag tag, Asn1Tag expectedTag, UniversalTagNumber tagNumber)
at System.Security.Cryptography.Asn1.AsnReader.ReadSequence(Asn1Tag expectedTag)
at System.Security.Cryptography.Asn1.RSAPrivateKeyAsn.Decode(AsnReader reader, Asn1Tag expectedTag, RSAPrivateKeyAsn& decoded)
at System.Security.Cryptography.Asn1.RSAPrivateKeyAsn.Decode(Asn1Tag expectedTag, ReadOnlyMemory`1 encoded, AsnEncodingRules ruleSet)
at System.Security.Cryptography.Asn1.RSAPrivateKeyAsn.Decode(ReadOnlyMemory`1 encoded, AsnEncodingRules ruleSet)
at System.Security.Cryptography.RSAKeyFormatHelper.FromPkcs1PrivateKey(ReadOnlyMemory`1 keyData, AlgorithmIdentifierAsn& algId, RSAParameters& ret)
at System.Security.Cryptography.RSA.ImportRSAPrivateKey(ReadOnlySpan`1 source, Int32& bytesRead)
at Example.Program.c__DisplayClass1_0.b__3(HttpsConnectionAdapterOptions httpsOptions) in /src/Example/Program.cs:line 47
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions.ApplyHttpsDefaults(HttpsConnectionAdapterOptions httpsOptions)
at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions, Action`1 configureOptions)
at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func`2 createBinding)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
at Example.Program.Main(String[] args) in /src/Example/Program.cs:line 16

Вернуться в «C#»