11using System . Net ;
22using System . Net . Sockets ;
3+ using System . Security . Cryptography ;
4+ using System . Security . Cryptography . X509Certificates ;
35using System . Text . Json ;
46using Microsoft . AspNetCore . Builder ;
57using Microsoft . AspNetCore . Http ;
@@ -16,14 +18,14 @@ public sealed class HttpsConnectionSpec : IAsyncLifetime
1618 public async ValueTask InitializeAsync ( )
1719 {
1820 _port = GetFreePort ( ) ;
19- var certPath = Path . Combine ( AppContext . BaseDirectory , "TestCertificates" , "test.pfx" ) ;
21+ var certificate = CreateSelfSignedCertificate ( ) ;
2022
2123 var builder = WebApplication . CreateBuilder ( ) ;
2224 builder . Services . AddTurboKestrel ( options =>
2325 {
2426 options . ListenLocalhost ( _port , listen =>
2527 {
26- listen . UseHttps ( certPath , "testpassword" ) ;
28+ listen . UseHttps ( certificate ) ;
2729 listen . Protocols = HttpProtocols . Http1 ;
2830 } ) ;
2931 } ) ;
@@ -81,4 +83,31 @@ private static ushort GetFreePort()
8183 listener . Stop ( ) ;
8284 return ( ushort ) port ;
8385 }
86+
87+ private static X509Certificate2 CreateSelfSignedCertificate ( )
88+ {
89+ using var rsa = RSA . Create ( 2048 ) ;
90+ var request = new CertificateRequest (
91+ "CN=localhost" ,
92+ rsa ,
93+ HashAlgorithmName . SHA256 ,
94+ RSASignaturePadding . Pkcs1 ) ;
95+
96+ request . CertificateExtensions . Add (
97+ new X509BasicConstraintsExtension ( false , false , 0 , false ) ) ;
98+
99+ var sanBuilder = new SubjectAlternativeNameBuilder ( ) ;
100+ sanBuilder . AddDnsName ( "localhost" ) ;
101+ sanBuilder . AddIpAddress ( IPAddress . Loopback ) ;
102+ request . CertificateExtensions . Add ( sanBuilder . Build ( ) ) ;
103+
104+ var cert = request . CreateSelfSigned (
105+ DateTimeOffset . UtcNow . AddMinutes ( - 1 ) ,
106+ DateTimeOffset . UtcNow . AddHours ( 1 ) ) ;
107+
108+ return X509CertificateLoader . LoadPkcs12 (
109+ cert . Export ( X509ContentType . Pfx ) ,
110+ null ,
111+ X509KeyStorageFlags . Exportable ) ;
112+ }
84113}
0 commit comments