Last active
September 18, 2020 12:34
-
-
Save bobuva/0026b8760a44b9c4e60f4649978f1766 to your computer and use it in GitHub Desktop.
SSL ALPN Negotiation with .NET Core 2.1 Preview
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
using System; | |
using System.Threading; | |
using System.Collections.Generic; | |
using System.Net.Security; | |
using System.Net.Sockets; | |
using System.Security.Authentication; | |
using System.Security.Cryptography.X509Certificates; | |
using System.Threading.Tasks; | |
namespace ssltest | |
{ | |
class Program | |
{ | |
const int TIMEOUT_MSEC = 10000; | |
const string TargetHost = "[YOUR TARGET HOST]"; | |
static void Main(string[] args) | |
{ | |
DoConnectAsync(); | |
Console.WriteLine("Press any key to exit..."); | |
Console.ReadKey(); | |
} | |
// The following method is invoked by the RemoteCertificateValidationDelegate. | |
public static bool ValidateServerCertificate( | |
object sender, | |
X509Certificate certificate, | |
X509Chain chain, | |
SslPolicyErrors sslPolicyErrors) | |
{ | |
if (sslPolicyErrors == SslPolicyErrors.None) | |
return true; | |
Console.WriteLine("Certificate error: {0}", sslPolicyErrors); | |
// Do not allow this client to communicate with unauthenticated servers. | |
return false; | |
} | |
private static async void DoConnectAsync() | |
{ | |
// let exceptions bubble up to console UI for now. | |
//try | |
//{ | |
TcpClient tcpClient = new TcpClient(); | |
Task task = tcpClient.ConnectAsync(TargetHost, 443); | |
await task; | |
SslStream sslStream = new SslStream(tcpClient.GetStream(), false); | |
X509Certificate2 certificate = new X509Certificate2("[FILENAME OF CERTIFICATE GOES HERE]"); | |
X509Certificate2Collection certColl = new X509Certificate2Collection(certificate); | |
SslClientAuthenticationOptions authOptions = new SslClientAuthenticationOptions(); | |
authOptions.ApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http2 }; | |
authOptions.EnabledSslProtocols = SslProtocols.Tls12; | |
authOptions.TargetHost = TargetHost; | |
//authOptions.AllowRenegotiation = true; | |
authOptions.ClientCertificates = certColl; | |
authOptions.RemoteCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); | |
await sslStream.AuthenticateAsClientAsync(authOptions, new CancellationToken(false)); | |
// At this point we made a Grpc channel and client and connected using the GRPC protocol. | |
// Not including with this sample. | |
//} | |
//catch(Exception e) | |
//{ | |
// Console.WriteLine("DoConnect exception: {0}", e.Message); | |
//} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment