diff --git a/eng/Workarounds.props b/eng/Workarounds.props index b3ff8f3b82cc..2520bde09bd6 100644 --- a/eng/Workarounds.props +++ b/eng/Workarounds.props @@ -30,10 +30,7 @@ $(NoWarn);NETSDK1138;CS8969 - - - $(NoWarn);SYSLIB0057 - + diff --git a/eng/testing/linker/SupportFiles/Directory.Build.props b/eng/testing/linker/SupportFiles/Directory.Build.props index acff56b5d77e..568f87c9effa 100644 --- a/eng/testing/linker/SupportFiles/Directory.Build.props +++ b/eng/testing/linker/SupportFiles/Directory.Build.props @@ -9,8 +9,7 @@ true true - - $(NoWarn);SYSLIB0057 + win osx diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/XmlEncryption/EncryptedXmlDecryptorTests.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/XmlEncryption/EncryptedXmlDecryptorTests.cs index 3d44df680fe6..f7e1f3ce39ba 100644 --- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/XmlEncryption/EncryptedXmlDecryptorTests.cs +++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/XmlEncryption/EncryptedXmlDecryptorTests.cs @@ -15,7 +15,7 @@ public class EncryptedXmlDecryptorTests [Fact] public void ThrowsIfCannotDecrypt() { - var testCert1 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password"); + var testCert1 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password"); var encryptor = new CertificateXmlEncryptor(testCert1, NullLoggerFactory.Instance); var data = new XElement("SampleData", "Lorem ipsum"); var encryptedXml = encryptor.Encrypt(data); @@ -29,8 +29,8 @@ public void ThrowsIfCannotDecrypt() [Fact] public void ThrowsIfProvidedCertificateDoesNotMatch() { - var testCert1 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password"); - var testCert2 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert2.pfx"), "password"); + var testCert1 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password"); + var testCert2 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert2.pfx"), "password"); var services = new ServiceCollection() .Configure(o => o.AddKeyDecryptionCertificate(testCert2)) .BuildServiceProvider(); @@ -47,8 +47,8 @@ public void ThrowsIfProvidedCertificateDoesNotMatch() [Fact] public void ThrowsIfProvidedCertificateDoesHavePrivateKey() { - var fullCert = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password"); - var publicKeyOnly = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.PublicKeyOnly.cer"), ""); + var fullCert = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password"); + var publicKeyOnly = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.PublicKeyOnly.cer")); var services = new ServiceCollection() .Configure(o => o.AddKeyDecryptionCertificate(publicKeyOnly)) .BuildServiceProvider(); @@ -65,8 +65,8 @@ public void ThrowsIfProvidedCertificateDoesHavePrivateKey() [Fact] public void XmlCanRoundTrip() { - var testCert1 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password"); - var testCert2 = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert2.pfx"), "password"); + var testCert1 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert1.pfx"), "password"); + var testCert2 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(AppContext.BaseDirectory, "TestFiles", "TestCert2.pfx"), "password"); var services = new ServiceCollection() .Configure(o => { diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestCertificateXmlEncryptor.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestCertificateXmlEncryptor.cs index 4aef1f1ca8af..4d46a98e71eb 100644 --- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestCertificateXmlEncryptor.cs +++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestCertificateXmlEncryptor.cs @@ -7,7 +7,7 @@ using System.Security.Cryptography.X509Certificates; using System.Xml.Linq; -var cert = new X509Certificate2(Convert.FromBase64String(Constants.Key), Constants.Password); +var cert = X509CertificateLoader.LoadPkcs12(Convert.FromBase64String(Constants.Key), Constants.Password); var encryptor = new CertificateXmlEncryptor(cert, NullLoggerFactory.Instance); diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestEncryptedXmlDecryptor.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestEncryptedXmlDecryptor.cs index dd01f04b08fe..681bdb839eb5 100644 --- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestEncryptedXmlDecryptor.cs +++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestEncryptedXmlDecryptor.cs @@ -8,7 +8,7 @@ using System.Security.Cryptography.X509Certificates; using System.Xml.Linq; -var cert = new X509Certificate2(Convert.FromBase64String(Constants.Key), Constants.Password); +var cert = X509CertificateLoader.LoadPkcs12(Convert.FromBase64String(Constants.Key), Constants.Password); var encryptedData = XElement.Parse(Constants.KeyRingXmlContents) .Element("descriptor") .Element("descriptor") diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestUnprotectWorksWithX509Certificate.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestUnprotectWorksWithX509Certificate.cs index 317b9f62fc32..fe47c7a13200 100644 --- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestUnprotectWorksWithX509Certificate.cs +++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestUnprotectWorksWithX509Certificate.cs @@ -9,7 +9,7 @@ var keyDirectory = new DirectoryInfo(AppContext.BaseDirectory); File.WriteAllText(Path.Combine(keyDirectory.FullName, Constants.KeyRingXmlFileName), Constants.KeyRingXmlContents); -var cert = new X509Certificate2(Convert.FromBase64String(Constants.Key), Constants.Password); +var cert = X509CertificateLoader.LoadPkcs12(Convert.FromBase64String(Constants.Key), Constants.Password); var dpProvider = DataProtectionProvider.Create(keyDirectory, cert); var protector = dpProvider.CreateProtector(purpose: "Test trimming"); diff --git a/src/DataProtection/Extensions/test/DataProtectionProviderTests.cs b/src/DataProtection/Extensions/test/DataProtectionProviderTests.cs index 610d13c8789b..0cd879530d00 100644 --- a/src/DataProtection/Extensions/test/DataProtectionProviderTests.cs +++ b/src/DataProtection/Extensions/test/DataProtectionProviderTests.cs @@ -119,7 +119,7 @@ public void System_UsesProvidedDirectory_WithConfigurationCallback() public void System_UsesProvidedDirectoryAndCertificate() { var filePath = Path.Combine(GetTestFilesPath(), "TestCert.pfx"); - using (var imported = new X509Certificate2(filePath, "password", X509KeyStorageFlags.Exportable)) + using (var imported = X509CertificateLoader.LoadPkcs12FromFile(filePath, "password", X509KeyStorageFlags.Exportable)) { using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { @@ -145,7 +145,7 @@ public void System_UsesProvidedDirectoryAndCertificate() var data = protector.Protect("payload"); // add a cert without the private key to ensure the decryption will still fallback to the cert store - var certWithoutKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCertWithoutPrivateKey.pfx"), "password"); + var certWithoutKey = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(GetTestFilesPath(), "TestCertWithoutPrivateKey.pfx"), "password"); var unprotector = DataProtectionProvider.Create(directory, o => o.UnprotectKeysWithAnyCertificate(certWithoutKey)).CreateProtector("purpose"); Assert.Equal("payload", unprotector.Unprotect(data)); @@ -173,7 +173,7 @@ public void System_UsesProvidedCertificateNotFromStore() using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadWrite); - var certWithoutKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCert3WithoutPrivateKey.pfx"), "password3", X509KeyStorageFlags.Exportable); + var certWithoutKey = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(GetTestFilesPath(), "TestCert3WithoutPrivateKey.pfx"), "password3", X509KeyStorageFlags.Exportable); Assert.False(certWithoutKey.HasPrivateKey, "Cert should not have private key"); store.Add(certWithoutKey); store.Close(); @@ -190,7 +190,7 @@ public void System_UsesProvidedCertificateNotFromStore() try { - var certWithKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCert3.pfx"), "password3"); + var certWithKey = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(GetTestFilesPath(), "TestCert3.pfx"), "password3"); var protector = DataProtectionProvider.Create(directory, certWithKey).CreateProtector("purpose"); var data = protector.Protect("payload"); @@ -214,7 +214,7 @@ public void System_UsesProvidedCertificateNotFromStore() public void System_UsesInMemoryCertificate() { var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx"); - var certificate = new X509Certificate2(filePath, "password"); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(filePath, "password"); AssetStoreDoesNotContain(certificate); @@ -243,7 +243,7 @@ public void System_UsesInMemoryCertificate() public void System_UsesCertificate() { var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx"); - var certificate = new X509Certificate2(filePath, "password"); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(filePath, "password"); AssetStoreDoesNotContain(certificate); @@ -285,7 +285,7 @@ private static void AssetStoreDoesNotContain(X509Certificate2 certificate) public void System_CanUnprotectWithCert() { var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx"); - var certificate = new X509Certificate2(filePath, "password"); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(filePath, "password"); WithUniqueTempDirectory(directory => { diff --git a/src/Grpc/Interop/test/testassets/InteropClient/InteropClient.cs b/src/Grpc/Interop/test/testassets/InteropClient/InteropClient.cs index 60322f052e99..fafb9cafac62 100644 --- a/src/Grpc/Interop/test/testassets/InteropClient/InteropClient.cs +++ b/src/Grpc/Interop/test/testassets/InteropClient/InteropClient.cs @@ -162,7 +162,7 @@ private async Task HttpClientCreateChannel() { var pem = File.ReadAllText("Certs/ca.pem"); var certData = GetBytesFromPem(pem, "CERTIFICATE"); - var cert = new X509Certificate2(certData!); + var cert = X509CertificateLoader.LoadCertificate(certData!); httpClientHandler.ClientCertificates.Add(cert); } diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.Forms.cs b/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.Forms.cs index bddef0511d52..4e2ef05a8046 100644 --- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.Forms.cs +++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.Forms.cs @@ -494,7 +494,7 @@ public async Task RequestDelegatePopulatesFromIFormFileParameterIfRequestHasClie httpContext.TraceIdentifier = "my-trace-id"; #pragma warning disable SYSLIB0026 // Type or member is obsolete - var clientCertificate = new X509Certificate2(); + var clientCertificate = X509CertificateLoader.LoadCertificate(Array.Empty()); #pragma warning restore SYSLIB0026 // Type or member is obsolete httpContext.Features.Set(new TlsConnectionFeature(clientCertificate)); diff --git a/src/Middleware/HttpOverrides/src/CertificateForwardingOptions.cs b/src/Middleware/HttpOverrides/src/CertificateForwardingOptions.cs index d546c642b611..de25634d7cdf 100644 --- a/src/Middleware/HttpOverrides/src/CertificateForwardingOptions.cs +++ b/src/Middleware/HttpOverrides/src/CertificateForwardingOptions.cs @@ -24,5 +24,5 @@ public class CertificateForwardingOptions /// /// This defaults to a conversion from a base64 encoded string. /// - public Func HeaderConverter = (headerValue) => new X509Certificate2(Convert.FromBase64String(headerValue)); + public Func HeaderConverter = (headerValue) => X509CertificateLoader.LoadCertificate(Convert.FromBase64String(headerValue)); } diff --git a/src/Security/Authentication/WsFederation/samples/WsFedSample/Program.cs b/src/Security/Authentication/WsFederation/samples/WsFedSample/Program.cs index 340236658d81..52b5b913c3fa 100644 --- a/src/Security/Authentication/WsFederation/samples/WsFedSample/Program.cs +++ b/src/Security/Authentication/WsFederation/samples/WsFedSample/Program.cs @@ -54,7 +54,7 @@ private static X509Certificate2 LoadCertificate() certificatePayload = memoryStream.ToArray(); } - return new X509Certificate2(certificatePayload, "testPassword"); + return X509CertificateLoader.LoadPkcs12(certificatePayload, "testPassword"); } } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs b/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs index 56a5ae4f8fe7..ed47c49264d3 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs @@ -277,7 +277,7 @@ private static unsafe void IOCompleted(ClientCertLoader asyncResult, uint errorC { var certEncoded = new byte[pClientCertInfo->CertEncodedSize]; Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length); - asyncResult.Complete((int)pClientCertInfo->CertFlags, new X509Certificate2(certEncoded)); + asyncResult.Complete((int)pClientCertInfo->CertFlags, X509CertificateLoader.LoadCertificate(certEncoded)); } catch (CryptographicException exception) { diff --git a/src/Servers/IIS/IIS/src/Core/IISHttpContext.FeatureCollection.cs b/src/Servers/IIS/IIS/src/Core/IISHttpContext.FeatureCollection.cs index 6e3475a5f1b8..394f73daf2e0 100644 --- a/src/Servers/IIS/IIS/src/Core/IISHttpContext.FeatureCollection.cs +++ b/src/Servers/IIS/IIS/src/Core/IISHttpContext.FeatureCollection.cs @@ -393,7 +393,7 @@ unsafe X509Certificate2? ITlsConnectionFeature.ClientCertificate // Based off of from https://referencesource.microsoft.com/#system/net/System/Net/HttpListenerRequest.cs,1037c8ec82879ba0,references var rawCertificateCopy = new byte[NativeRequest->pSslInfo->pClientCertInfo->CertEncodedSize]; Marshal.Copy((IntPtr)NativeRequest->pSslInfo->pClientCertInfo->pCertEncoded, rawCertificateCopy, 0, rawCertificateCopy.Length); - _certificate = new X509Certificate2(rawCertificateCopy); + _certificate = X509CertificateLoader.LoadCertificate(rawCertificateCopy); } return _certificate; diff --git a/src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/ClientCertificateFixture.cs b/src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/ClientCertificateFixture.cs index f57828a55c19..7600f35ab5a8 100644 --- a/src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/ClientCertificateFixture.cs +++ b/src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/ClientCertificateFixture.cs @@ -53,7 +53,7 @@ public X509Certificate2 GetOrCreateCertificate() var imported = parentCert; var export = parentCert.Export(X509ContentType.Pkcs12, ""); - imported = new X509Certificate2(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); + imported = X509CertificateLoader.LoadPkcs12(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); Array.Clear(export, 0, export.Length); // Add the cert to the cert store diff --git a/src/Servers/IIS/IISIntegration/src/ForwardedTlsConnectionFeature.cs b/src/Servers/IIS/IISIntegration/src/ForwardedTlsConnectionFeature.cs index 356b82ebb3fb..302022dcf2e9 100644 --- a/src/Servers/IIS/IISIntegration/src/ForwardedTlsConnectionFeature.cs +++ b/src/Servers/IIS/IISIntegration/src/ForwardedTlsConnectionFeature.cs @@ -29,7 +29,7 @@ public X509Certificate2? ClientCertificate try { var bytes = Convert.FromBase64String(_header.ToString()); - _certificate = new X509Certificate2(bytes); + _certificate = X509CertificateLoader.LoadCertificate(bytes); } catch (Exception ex) { diff --git a/src/Servers/Kestrel/Core/src/Internal/Certificates/CertificateConfigLoader.cs b/src/Servers/Kestrel/Core/src/Internal/Certificates/CertificateConfigLoader.cs index d0239122fcde..2b16e35ee8ac 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Certificates/CertificateConfigLoader.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Certificates/CertificateConfigLoader.cs @@ -71,7 +71,7 @@ public CertificateConfigLoader(IHostEnvironment hostEnvironment, ILogger null, X509Certificate2 cert2 => cert2, - _ => new X509Certificate2(certificate), + _ => X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()), }; } } diff --git a/src/Servers/Kestrel/Core/src/ListenOptionsHttpsExtensions.cs b/src/Servers/Kestrel/Core/src/ListenOptionsHttpsExtensions.cs index 32bd1dd59889..6955e2f22eae 100644 --- a/src/Servers/Kestrel/Core/src/ListenOptionsHttpsExtensions.cs +++ b/src/Servers/Kestrel/Core/src/ListenOptionsHttpsExtensions.cs @@ -36,7 +36,7 @@ public static class ListenOptionsHttpsExtensions public static ListenOptions UseHttps(this ListenOptions listenOptions, string fileName) { var env = listenOptions.ApplicationServices.GetRequiredService(); - return listenOptions.UseHttps(new X509Certificate2(Path.Combine(env.ContentRootPath, fileName))); + return listenOptions.UseHttps(X509CertificateLoader.LoadCertificateFromFile(Path.Combine(env.ContentRootPath, fileName))); } /// @@ -50,7 +50,7 @@ public static ListenOptions UseHttps(this ListenOptions listenOptions, string fi public static ListenOptions UseHttps(this ListenOptions listenOptions, string fileName, string? password) { var env = listenOptions.ApplicationServices.GetRequiredService(); - return listenOptions.UseHttps(new X509Certificate2(Path.Combine(env.ContentRootPath, fileName), password)); + return listenOptions.UseHttps(X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(env.ContentRootPath, fileName), password)); } /// @@ -65,7 +65,7 @@ public static ListenOptions UseHttps(this ListenOptions listenOptions, string fi Action configureOptions) { var env = listenOptions.ApplicationServices.GetRequiredService(); - return listenOptions.UseHttps(new X509Certificate2(Path.Combine(env.ContentRootPath, fileName), password), configureOptions); + return listenOptions.UseHttps(X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(env.ContentRootPath, fileName), password), configureOptions); } /// diff --git a/src/Servers/Kestrel/Core/src/Middleware/HttpsConnectionMiddleware.cs b/src/Servers/Kestrel/Core/src/Middleware/HttpsConnectionMiddleware.cs index 7f6b3bf1b197..df97a9b29a1f 100644 --- a/src/Servers/Kestrel/Core/src/Middleware/HttpsConnectionMiddleware.cs +++ b/src/Servers/Kestrel/Core/src/Middleware/HttpsConnectionMiddleware.cs @@ -502,7 +502,7 @@ internal static void EnsureCertificateIsAllowedForServerAuth(X509Certificate2 ce return cert2; } - return new X509Certificate2(certificate); + return X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()); } internal static HttpProtocols ValidateAndNormalizeHttpProtocols(HttpProtocols httpProtocols, ILogger logger) diff --git a/src/Servers/Kestrel/Core/src/TlsConfigurationLoader.cs b/src/Servers/Kestrel/Core/src/TlsConfigurationLoader.cs index abeb9df5c392..64bbfd501e6a 100644 --- a/src/Servers/Kestrel/Core/src/TlsConfigurationLoader.cs +++ b/src/Servers/Kestrel/Core/src/TlsConfigurationLoader.cs @@ -158,7 +158,7 @@ public ListenOptions UseHttpsWithSni( { try { - var certificate = new X509Certificate2(certificatePath, certificateConfig.Password); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(certificatePath, certificateConfig.Password); if (IsDevelopmentCertificate(certificate)) { diff --git a/src/Servers/Kestrel/Core/test/SniOptionsSelectorTests.cs b/src/Servers/Kestrel/Core/test/SniOptionsSelectorTests.cs index 4cb691eb7963..2279730b9447 100644 --- a/src/Servers/Kestrel/Core/test/SniOptionsSelectorTests.cs +++ b/src/Servers/Kestrel/Core/test/SniOptionsSelectorTests.cs @@ -471,7 +471,7 @@ public void ClonesSslServerAuthenticationOptionsIfTheFallbackServerCertificateSe var fallbackOptions = new HttpsConnectionAdapterOptions { - ServerCertificate = new X509Certificate2(Array.Empty()), + ServerCertificate = X509CertificateLoader.LoadCertificate(Array.Empty()), ServerCertificateSelector = (context, serverName) => selectorCertificate }; @@ -531,7 +531,7 @@ public void FallsBackToHttpsConnectionAdapterCertificate() }; var fallbackOptions = new HttpsConnectionAdapterOptions { - ServerCertificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword") + ServerCertificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword") }; var sniOptionsSelector = new SniOptionsSelector( @@ -558,7 +558,7 @@ public void FallsBackToHttpsConnectionAdapterServerCertificateSelectorOverServer var fallbackOptions = new HttpsConnectionAdapterOptions { - ServerCertificate = new X509Certificate2(Array.Empty()), + ServerCertificate = X509CertificateLoader.LoadCertificate(Array.Empty()), ServerCertificateSelector = (context, serverName) => selectorCertificate }; @@ -849,7 +849,7 @@ public void CloneSslOptionsClonesAllProperties() // Defaults to null RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true, // Defaults to null - ServerCertificate = new X509Certificate2(Array.Empty()), + ServerCertificate = X509CertificateLoader.LoadCertificate(Array.Empty()), // Defaults to null ServerCertificateContext = SslStreamCertificateContext.Create(_x509Certificate2, additionalCertificates: null, offline: true), // Defaults to null diff --git a/src/Servers/Kestrel/Kestrel/test/HttpsConfigurationTests.cs b/src/Servers/Kestrel/Kestrel/test/HttpsConfigurationTests.cs index cb27ce5bc210..1c580958780d 100644 --- a/src/Servers/Kestrel/Kestrel/test/HttpsConfigurationTests.cs +++ b/src/Servers/Kestrel/Kestrel/test/HttpsConfigurationTests.cs @@ -25,7 +25,7 @@ public async Task BindAddressFromSetting(string address, bool useKestrelHttpsCon .UseKestrelCore() .ConfigureKestrel(serverOptions => { - serverOptions.TestOverrideDefaultCertificate = new X509Certificate2(Path.Combine("shared", "TestCertificates", "aspnetdevcert.pfx"), "testPassword"); + serverOptions.TestOverrideDefaultCertificate = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine("shared", "TestCertificates", "aspnetdevcert.pfx"), "testPassword"); }) .Configure(app => { }); @@ -190,7 +190,7 @@ public async Task UseHttpsJustWorks() .UseKestrelCore() .ConfigureKestrel(serverOptions => { - serverOptions.TestOverrideDefaultCertificate = new X509Certificate2(Path.Combine("shared", "TestCertificates", "aspnetdevcert.pfx"), "testPassword"); + serverOptions.TestOverrideDefaultCertificate = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine("shared", "TestCertificates", "aspnetdevcert.pfx"), "testPassword"); serverOptions.ListenAnyIP(0, listenOptions => { @@ -219,7 +219,7 @@ public async Task UseHttpsMayNotImplyUseKestrelHttpsConfiguration() { listenOptions.UseHttps(new HttpsConnectionAdapterOptions() { - ServerCertificate = new X509Certificate2(Path.Combine("shared", "TestCertificates", "aspnetdevcert.pfx"), "testPassword"), + ServerCertificate = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine("shared", "TestCertificates", "aspnetdevcert.pfx"), "testPassword"), }); }); }) diff --git a/src/Servers/Kestrel/Kestrel/test/KestrelConfigurationLoaderTests.cs b/src/Servers/Kestrel/Kestrel/test/KestrelConfigurationLoaderTests.cs index b4a55423038b..2f39a94cfea4 100644 --- a/src/Servers/Kestrel/Kestrel/test/KestrelConfigurationLoaderTests.cs +++ b/src/Servers/Kestrel/Kestrel/test/KestrelConfigurationLoaderTests.cs @@ -273,7 +273,7 @@ public void ConfigureEndpointDevelopmentCertificateGetsLoadedWhenPresent() try { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var bytes = certificate.Export(X509ContentType.Pkcs12, "1234"); var path = GetCertificatePath(); Directory.CreateDirectory(Path.GetDirectoryName(path)); @@ -314,7 +314,7 @@ public void DevelopmentCertificateCanBeRemoved() { var serverOptions = CreateServerOptions(); - var devCert = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var devCert = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var devCertBytes = devCert.Export(X509ContentType.Pkcs12, "1234"); var devCertPath = GetCertificatePath(); Directory.CreateDirectory(Path.GetDirectoryName(devCertPath)); @@ -405,7 +405,7 @@ public void ConfigureEndpoint_RecoverFromBadPassword() var testCertificate = TestResources.GetTestCertificate(); var otherCertificatePath = TestResources.GetCertPath("aspnetdevcert.pfx"); - var otherCertificate = new X509Certificate2(otherCertificatePath, "testPassword"); + var otherCertificate = X509CertificateLoader.LoadPkcs12FromFile(otherCertificatePath, "testPassword"); serverOptions.Configure(configRoot).Load(); CheckListenOptions(testCertificate); @@ -440,7 +440,7 @@ public void LoadDevelopmentCertificate_LoadBeforeUseHttps() try { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var bytes = certificate.Export(X509ContentType.Pkcs12, "1234"); var path = GetCertificatePath(); Directory.CreateDirectory(Path.GetDirectoryName(path)); @@ -487,7 +487,7 @@ public void LoadDevelopmentCertificate_UseHttpsBeforeLoad() try { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var bytes = certificate.Export(X509ContentType.Pkcs12, "1234"); var path = GetCertificatePath(); Directory.CreateDirectory(Path.GetDirectoryName(path)); @@ -536,7 +536,7 @@ public void LoadDevelopmentCertificate_UseHttpsBeforeConfigure() try { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var bytes = certificate.Export(X509ContentType.Pkcs12, "1234"); var path = GetCertificatePath(); Directory.CreateDirectory(Path.GetDirectoryName(path)); @@ -587,7 +587,7 @@ public void LoadDevelopmentCertificate_UseHttpsBeforeConfigure() public void ConfigureEndpoint_ThrowsWhen_The_PasswordIsMissing() { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("https-aspnet.crt")); + var certificate = X509CertificateLoader.LoadCertificateFromFile(TestResources.GetCertPath("https-aspnet.crt")); var config = new ConfigurationBuilder().AddInMemoryCollection(new[] { @@ -611,7 +611,7 @@ public void ConfigureEndpoint_ThrowsWhen_The_PasswordIsMissing() public void ConfigureEndpoint_ThrowsWhen_TheKeyDoesntMatchTheCertificateKey() { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("https-aspnet.crt")); + var certificate = X509CertificateLoader.LoadCertificateFromFile(TestResources.GetCertPath("https-aspnet.crt")); var config = new ConfigurationBuilder().AddInMemoryCollection(new[] { @@ -636,7 +636,7 @@ public void ConfigureEndpoint_ThrowsWhen_TheKeyDoesntMatchTheCertificateKey() public void ConfigureEndpoint_ThrowsWhen_The_PasswordIsIncorrect() { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("https-aspnet.crt")); + var certificate = X509CertificateLoader.LoadCertificateFromFile(TestResources.GetCertPath("https-aspnet.crt")); var config = new ConfigurationBuilder().AddInMemoryCollection(new[] { @@ -661,7 +661,7 @@ public void ConfigureEndpoint_ThrowsWhen_The_PasswordIsIncorrect() public void ConfigureEndpoint_ThrowsWhen_The_KeyIsPublic() { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("https-aspnet.crt")); + var certificate = X509CertificateLoader.LoadCertificateFromFile(TestResources.GetCertPath("https-aspnet.crt")); var config = new ConfigurationBuilder().AddInMemoryCollection(new[] { @@ -699,7 +699,7 @@ public void ConfigureEndpoint_ThrowsWhen_The_KeyIsPublic() public void ConfigureEndpoint_CanLoadPemCertificates(string certificateFile, string certificateKey, string password) { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath(Path.ChangeExtension(certificateFile, "crt"))); + var certificate = X509CertificateLoader.LoadCertificateFromFile(TestResources.GetCertPath(Path.ChangeExtension(certificateFile, "crt"))); var ran1 = false; var config = new ConfigurationBuilder().AddInMemoryCollection(new[] @@ -730,7 +730,7 @@ public void ConfigureEndpointDevelopmentCertificateGetsIgnoredIfPasswordIsNotCor try { var serverOptions = CreateServerOptions(); - var certificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var certificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var bytes = certificate.Export(X509ContentType.Pkcs12, "1234"); var path = GetCertificatePath(); Directory.CreateDirectory(Path.GetDirectoryName(path)); @@ -883,10 +883,10 @@ public async Task CertificateChangedOnDisk(bool reloadOnChange) var certificatePassword = "1234"; - var oldCertificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var oldCertificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var oldCertificateBytes = oldCertificate.Export(X509ContentType.Pkcs12, certificatePassword); - var newCertificate = new X509Certificate2(TestResources.TestCertificatePath, "testPassword", X509KeyStorageFlags.Exportable); + var newCertificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.TestCertificatePath, "testPassword", X509KeyStorageFlags.Exportable); var newCertificateBytes = newCertificate.Export(X509ContentType.Pkcs12, certificatePassword); Directory.CreateDirectory(Path.GetDirectoryName(certificatePath)); @@ -981,12 +981,12 @@ public async Task CertificateChangedOnDisk_Symlink() var certificatePassword = "1234"; - var oldCertificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var oldCertificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var oldCertificateBytes = oldCertificate.Export(X509ContentType.Pkcs12, certificatePassword); File.WriteAllBytes(oldCertPath, oldCertificateBytes); - var newCertificate = new X509Certificate2(TestResources.TestCertificatePath, "testPassword", X509KeyStorageFlags.Exportable); + var newCertificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.TestCertificatePath, "testPassword", X509KeyStorageFlags.Exportable); var newCertificateBytes = newCertificate.Export(X509ContentType.Pkcs12, certificatePassword); File.WriteAllBytes(newCertPath, newCertificateBytes); diff --git a/src/Servers/Kestrel/Transport.Quic/src/Internal/QuicConnectionContext.FeatureCollection.cs b/src/Servers/Kestrel/Transport.Quic/src/Internal/QuicConnectionContext.FeatureCollection.cs index e2603836421a..92dfa3abfe49 100644 --- a/src/Servers/Kestrel/Transport.Quic/src/Internal/QuicConnectionContext.FeatureCollection.cs +++ b/src/Servers/Kestrel/Transport.Quic/src/Internal/QuicConnectionContext.FeatureCollection.cs @@ -50,7 +50,7 @@ private void InitializeFeatures() { null => null, X509Certificate2 cert2 => cert2, - _ => new X509Certificate2(certificate), + _ => X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()), }; } } diff --git a/src/Servers/Kestrel/samples/WebTransportInteractiveSampleApp/Program.cs b/src/Servers/Kestrel/samples/WebTransportInteractiveSampleApp/Program.cs index 2fa999a73fc8..1be76a25d19d 100644 --- a/src/Servers/Kestrel/samples/WebTransportInteractiveSampleApp/Program.cs +++ b/src/Servers/Kestrel/samples/WebTransportInteractiveSampleApp/Program.cs @@ -192,7 +192,7 @@ static X509Certificate2 GenerateManualCertificate() req.CertificateExtensions.Add(sanBuilder.Build()); // Sign using var crt = req.CreateSelfSigned(now, now.AddDays(14)); // 14 days is the max duration of a certificate for this - cert = new(crt.Export(X509ContentType.Pfx)); + cert = X509CertificateLoader.LoadPkcs12(crt.Export(X509ContentType.Pfx), password: null); // Save store.Add(cert); diff --git a/src/Servers/Kestrel/samples/WebTransportSampleApp/Program.cs b/src/Servers/Kestrel/samples/WebTransportSampleApp/Program.cs index 556fd7972a22..31ea1abbaf81 100644 --- a/src/Servers/Kestrel/samples/WebTransportSampleApp/Program.cs +++ b/src/Servers/Kestrel/samples/WebTransportSampleApp/Program.cs @@ -78,7 +78,7 @@ static X509Certificate2 GenerateManualCertificate() req.CertificateExtensions.Add(sanBuilder.Build()); // Sign using var crt = req.CreateSelfSigned(now, now.AddDays(14)); // 14 days is the max duration of a certificate for this - cert = new(crt.Export(X509ContentType.Pfx)); + cert = X509CertificateLoader.LoadPkcs12(crt.Export(X509ContentType.Pfx), password: null); // Save store.Add(cert); diff --git a/src/Servers/Kestrel/shared/test/CertHelper.cs b/src/Servers/Kestrel/shared/test/CertHelper.cs index a64041950891..b66e7a811d93 100644 --- a/src/Servers/Kestrel/shared/test/CertHelper.cs +++ b/src/Servers/Kestrel/shared/test/CertHelper.cs @@ -162,7 +162,7 @@ internal static (X509Certificate2 certificate, X509Certificate2Collection) Gener if (OperatingSystem.IsWindows()) { X509Certificate2 ephemeral = endEntity; - endEntity = new X509Certificate2(endEntity.Export(X509ContentType.Pfx), (string?)null, X509KeyStorageFlags.Exportable); + endEntity = X509CertificateLoader.LoadPkcs12(endEntity.Export(X509ContentType.Pfx), (string?)null, X509KeyStorageFlags.Exportable); ephemeral.Dispose(); } diff --git a/src/Servers/Kestrel/shared/test/CertificateAuthority.cs b/src/Servers/Kestrel/shared/test/CertificateAuthority.cs index ee1ccafd5328..dd929cfe4123 100644 --- a/src/Servers/Kestrel/shared/test/CertificateAuthority.cs +++ b/src/Servers/Kestrel/shared/test/CertificateAuthority.cs @@ -126,7 +126,7 @@ public void Dispose() internal X509Certificate2 CloneIssuerCert() { - return new X509Certificate2(_cert.RawData); + return X509CertificateLoader.LoadCertificate(_cert.RawData); } internal void Revoke(X509Certificate2 certificate, DateTimeOffset revocationTime) diff --git a/src/Servers/Kestrel/stress/Program.cs b/src/Servers/Kestrel/stress/Program.cs index 20a0b35e0df3..ab52acacae62 100644 --- a/src/Servers/Kestrel/stress/Program.cs +++ b/src/Servers/Kestrel/stress/Program.cs @@ -402,7 +402,7 @@ Func TestAbort(string path) X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1)); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - cert = new X509Certificate2(cert.Export(X509ContentType.Pfx)); + cert = X509CertificateLoader.LoadPkcs12(cert.Export(X509ContentType.Pfx), ""); } listenOptions.UseHttps(cert); } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/CertificateLoaderTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/CertificateLoaderTests.cs index 170db902f235..22e7fd7cc5b6 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/CertificateLoaderTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/CertificateLoaderTests.cs @@ -18,7 +18,7 @@ public void IsCertificateAllowedForServerAuth_AllowWithNoExtensions(string testC { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); - var cert = new X509Certificate2(certPath, "testPassword"); + var cert = X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); Assert.Empty(cert.Extensions.OfType()); Assert.True(CertificateLoader.IsCertificateAllowedForServerAuth(cert)); @@ -31,7 +31,7 @@ public void IsCertificateAllowedForServerAuth_ValidatesEnhancedKeyUsageOnCertifi { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); - var cert = new X509Certificate2(certPath, "testPassword"); + var cert = X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); Assert.NotEmpty(cert.Extensions); var eku = Assert.Single(cert.Extensions.OfType()); Assert.NotEmpty(eku.EnhancedKeyUsages); @@ -46,7 +46,7 @@ public void IsCertificateAllowedForServerAuth_RejectsCertificatesMissingServerEk { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); - var cert = new X509Certificate2(certPath, "testPassword"); + var cert = X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); Assert.NotEmpty(cert.Extensions); var eku = Assert.Single(cert.Extensions.OfType()); Assert.NotEmpty(eku.EnhancedKeyUsages); @@ -61,7 +61,7 @@ public void DoesCertificateHaveASubjectAlternativeName(string testCertName, bool { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); - var cert = new X509Certificate2(certPath, "testPassword"); + var cert = X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); Assert.Equal(hasSan, CertificateLoader.DoesCertificateHaveASubjectAlternativeName(cert)); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsConnectionMiddlewareTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsConnectionMiddlewareTests.cs index 2d4ab6c59018..8d36a8589f7c 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsConnectionMiddlewareTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsConnectionMiddlewareTests.cs @@ -1308,7 +1308,7 @@ public void AcceptsCertificateWithoutExtensions(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); - var cert = new X509Certificate2(certPath, "testPassword"); + var cert = X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); Assert.Empty(cert.Extensions.OfType()); CreateMiddleware(cert); @@ -1321,7 +1321,7 @@ public void ValidatesEnhancedKeyUsageOnCertificate(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); - var cert = new X509Certificate2(certPath, "testPassword"); + var cert = X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); Assert.NotEmpty(cert.Extensions); var eku = Assert.Single(cert.Extensions.OfType()); Assert.NotEmpty(eku.EnhancedKeyUsages); @@ -1340,7 +1340,7 @@ public void ThrowsForCertificatesMissingServerEku(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); - var cert = new X509Certificate2(certPath, "testPassword"); + var cert = X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); Assert.NotEmpty(cert.Extensions); var eku = Assert.Single(cert.Extensions.OfType()); Assert.NotEmpty(eku.EnhancedKeyUsages); @@ -1361,7 +1361,7 @@ public void LogsForCertificateMissingSubjectAlternativeName(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); - var cert = new X509Certificate2(certPath, "testPassword"); + var cert = X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); Assert.False(CertificateLoader.DoesCertificateHaveASubjectAlternativeName(cert)); var testLogger = new TestApplicationErrorLogger(); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsTests.cs index 1f657a849afc..f87ef91c7463 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsTests.cs @@ -373,7 +373,7 @@ public async Task HandshakeTimesOutAndIsLoggedAsDebug() { listenOptions.UseHttps(o => { - o.ServerCertificate = new X509Certificate2(_x509Certificate2); + o.ServerCertificate = _x509Certificate2; o.HandshakeTimeout = TimeSpan.FromMilliseconds(100); }); })) diff --git a/src/Servers/Kestrel/test/Interop.FunctionalTests/Http3/Http3TlsTests.cs b/src/Servers/Kestrel/test/Interop.FunctionalTests/Http3/Http3TlsTests.cs index 78279c042bf7..a22626125cd5 100644 --- a/src/Servers/Kestrel/test/Interop.FunctionalTests/Http3/Http3TlsTests.cs +++ b/src/Servers/Kestrel/test/Interop.FunctionalTests/Http3/Http3TlsTests.cs @@ -430,7 +430,7 @@ public void UseKestrelCore_ConfigurationBased(bool useQuic) [MsQuicSupported] public async Task LoadDevelopmentCertificateViaConfiguration() { - var expectedCertificate = new X509Certificate2(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); + var expectedCertificate = X509CertificateLoader.LoadPkcs12FromFile(TestResources.GetCertPath("aspnetdevcert.pfx"), "testPassword", X509KeyStorageFlags.Exportable); var bytes = expectedCertificate.Export(X509ContentType.Pkcs12, "1234"); var path = GetCertificatePath(); Directory.CreateDirectory(Path.GetDirectoryName(path)); diff --git a/src/Shared/CertificateGeneration/CertificateManager.cs b/src/Shared/CertificateGeneration/CertificateManager.cs index 1d8c713a1e88..0ff3570d4cfa 100644 --- a/src/Shared/CertificateGeneration/CertificateManager.cs +++ b/src/Shared/CertificateGeneration/CertificateManager.cs @@ -454,7 +454,7 @@ internal ImportCertificateResult ImportCertificate(string certificatePath, strin try { Log.LoadCertificateStart(certificatePath); - certificate = new X509Certificate2(certificatePath, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet); + certificate = X509CertificateLoader.LoadPkcs12FromFile(certificatePath, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet); if (Log.IsEnabled()) { Log.LoadCertificateEnd(GetDescription(certificate)); diff --git a/src/Shared/CertificateGeneration/MacOSCertificateManager.cs b/src/Shared/CertificateGeneration/MacOSCertificateManager.cs index 36b0c92d895c..a67bfaf819dc 100644 --- a/src/Shared/CertificateGeneration/MacOSCertificateManager.cs +++ b/src/Shared/CertificateGeneration/MacOSCertificateManager.cs @@ -442,7 +442,7 @@ private static ICollection GetCertsFromDisk() { try { - var certificate = new X509Certificate2(file); + var certificate = X509CertificateLoader.LoadCertificateFromFile(file); certsFromDisk.Add(certificate); } catch (Exception) diff --git a/src/Shared/CertificateGeneration/UnixCertificateManager.cs b/src/Shared/CertificateGeneration/UnixCertificateManager.cs index 149e0fab3ba6..0fa1e1da3656 100644 --- a/src/Shared/CertificateGeneration/UnixCertificateManager.cs +++ b/src/Shared/CertificateGeneration/UnixCertificateManager.cs @@ -153,7 +153,7 @@ protected override X509Certificate2 SaveCertificateCore(X509Certificate2 certifi { var export = certificate.Export(X509ContentType.Pkcs12, ""); certificate.Dispose(); - certificate = new X509Certificate2(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); + certificate = X509CertificateLoader.LoadPkcs12(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); Array.Clear(export, 0, export.Length); using (var store = new X509Store(storeName, storeLocation)) diff --git a/src/Shared/CertificateGeneration/WindowsCertificateManager.cs b/src/Shared/CertificateGeneration/WindowsCertificateManager.cs index 1cf1ebd9480e..61b131b082a7 100644 --- a/src/Shared/CertificateGeneration/WindowsCertificateManager.cs +++ b/src/Shared/CertificateGeneration/WindowsCertificateManager.cs @@ -57,7 +57,7 @@ protected override X509Certificate2 SaveCertificateCore(X509Certificate2 certifi // key that we generated gets persisted. var export = certificate.Export(X509ContentType.Pkcs12, ""); certificate.Dispose(); - certificate = new X509Certificate2(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); + certificate = X509CertificateLoader.LoadPkcs12(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); Array.Clear(export, 0, export.Length); certificate.FriendlyName = AspNetHttpsOidFriendlyName; diff --git a/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs b/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs index a9a25b8f0092..28a6d31ee7bb 100644 --- a/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs +++ b/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs @@ -819,7 +819,7 @@ private IReadOnlyDictionary> GetRequestInfo(IntPtr bas var clientCert = clientCertInfo->pCertEncoded + fixup; var certEncoded = new byte[clientCertInfo->CertEncodedSize]; Marshal.Copy((IntPtr)clientCert, certEncoded, 0, certEncoded.Length); - return new X509Certificate2(certEncoded); + return X509CertificateLoader.LoadCertificate(certEncoded); } // Copied from https://github.com/dotnet/runtime/blob/main/src/libraries/Common/src/System/Memory/PointerMemoryManager.cs diff --git a/src/Shared/TestResources.cs b/src/Shared/TestResources.cs index 9de290ee1327..4d4a396189ab 100644 --- a/src/Shared/TestResources.cs +++ b/src/Shared/TestResources.cs @@ -28,7 +28,7 @@ public static X509Certificate2 GetTestCertificate(string certName = "testCert.pf try { - return new X509Certificate2(GetCertPath(certName), "testPassword"); + return X509CertificateLoader.LoadPkcs12FromFile(GetCertPath(certName), "testPassword"); } finally { @@ -38,7 +38,7 @@ public static X509Certificate2 GetTestCertificate(string certName = "testCert.pf public static X509Certificate2 GetTestCertificate(string certName, string password) { - return new X509Certificate2(GetCertPath(certName), password); + return X509CertificateLoader.LoadPkcs12FromFile(GetCertPath(certName), password); } public static X509Certificate2 GetTestCertificateWithKey(string certName, string keyName) @@ -48,7 +48,7 @@ public static X509Certificate2 GetTestCertificateWithKey(string certName, string { using (cert) { - return new X509Certificate2(cert.Export(X509ContentType.Pkcs12)); + return X509CertificateLoader.LoadPkcs12(cert.Export(X509ContentType.Pkcs12), ""); } } return cert; diff --git a/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.cs b/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.cs index 81c9e807698f..5bd96e6780f5 100644 --- a/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.cs +++ b/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.cs @@ -91,7 +91,7 @@ public async Task HttpOptionsSetOntoHttpClientHandler() return testHttpHandler; }; httpOptions.Cookies.Add(new Cookie("Name", "Value", string.Empty, "fakeuri.org")); - var clientCertificate = new X509Certificate(Array.Empty()); + var clientCertificate = X509CertificateLoader.LoadCertificate(Array.Empty()); httpOptions.ClientCertificates.Add(clientCertificate); httpOptions.UseDefaultCredentials = false; httpOptions.Credentials = Mock.Of(); diff --git a/src/SignalR/common/Shared/TestCertificates.cs b/src/SignalR/common/Shared/TestCertificates.cs index b452291f82ef..7895d37e9325 100644 --- a/src/SignalR/common/Shared/TestCertificates.cs +++ b/src/SignalR/common/Shared/TestCertificates.cs @@ -33,13 +33,13 @@ internal static X509Certificate2 GetTestCert() { // RSA cert, won't work on Windows 8.1 & Windows 2012 R2 using HTTP2, and ECC won't work in some Node environments var certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location), "TestCertificates", "testCert.pfx"); - return new X509Certificate2(certPath, "testPassword"); + return X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); } else { // ECC cert, works on Windows 8.1 & Windows 2012 R2 using HTTP2 var certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location), "TestCertificates", "testCertECC.pfx"); - return new X509Certificate2(certPath, "testPassword"); + return X509CertificateLoader.LoadPkcs12FromFile(certPath, "testPassword"); } } } diff --git a/src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/WebSocketsTransportTests.cs b/src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/WebSocketsTransportTests.cs index 7be54a8fd003..fd0c0d866c38 100644 --- a/src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/WebSocketsTransportTests.cs +++ b/src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/WebSocketsTransportTests.cs @@ -31,7 +31,7 @@ public async Task HttpOptionsSetOntoWebSocketOptions() var httpOptions = new HttpConnectionOptions(); httpOptions.Cookies.Add(new Cookie("Name", "Value", string.Empty, "fakeuri.org")); - var clientCertificate = new X509Certificate(Array.Empty()); + var clientCertificate = X509CertificateLoader.LoadCertificate(Array.Empty()); httpOptions.ClientCertificates.Add(clientCertificate); httpOptions.UseDefaultCredentials = false; httpOptions.Credentials = Mock.Of(); diff --git a/src/Tools/FirstRunCertGenerator/test/CertificateManagerTests.cs b/src/Tools/FirstRunCertGenerator/test/CertificateManagerTests.cs index 9e32f87d0ca4..508b74c9ae20 100644 --- a/src/Tools/FirstRunCertGenerator/test/CertificateManagerTests.cs +++ b/src/Tools/FirstRunCertGenerator/test/CertificateManagerTests.cs @@ -49,7 +49,7 @@ public void EnsureCreateHttpsCertificate_CreatesACertificate_WhenThereAreNoHttps Assert.Equal(EnsureCertificateResult.Succeeded, result); Assert.True(File.Exists(CertificateName)); - var exportedCertificate = new X509Certificate2(File.ReadAllBytes(CertificateName)); + var exportedCertificate = X509CertificateLoader.LoadCertificate(File.ReadAllBytes(CertificateName)); Assert.NotNull(exportedCertificate); Assert.False(exportedCertificate.HasPrivateKey); @@ -148,7 +148,7 @@ public void EnsureCreateHttpsCertificate_DoesNotCreateACertificate_WhenThereIsAn Assert.Equal(EnsureCertificateResult.ValidCertificatePresent, result); Assert.True(File.Exists(CertificateName)); - var exportedCertificate = new X509Certificate2(File.ReadAllBytes(CertificateName), certificatePassword); + var exportedCertificate = X509CertificateLoader.LoadPkcs12(File.ReadAllBytes(CertificateName), certificatePassword); Assert.NotNull(exportedCertificate); Assert.True(exportedCertificate.HasPrivateKey); @@ -215,7 +215,7 @@ public void EnsureCreateHttpsCertificate_CanExportTheCertInPemFormat_WithoutKey( Assert.Equal(EnsureCertificateResult.ValidCertificatePresent, result); Assert.True(File.Exists(CertificateName)); - var exportedCertificate = new X509Certificate2(CertificateName); + var exportedCertificate = X509CertificateLoader.LoadCertificateFromFile(CertificateName); Assert.NotNull(exportedCertificate); Assert.False(exportedCertificate.HasPrivateKey); }