Skip to content

Instantly share code, notes, and snippets.

@copernicus365
Forked from bobuva/ssl-alpn-test.txt
Created March 30, 2018 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save copernicus365/a2351d3c82ca78dac485d40979a9f557 to your computer and use it in GitHub Desktop.
Save copernicus365/a2351d3c82ca78dac485d40979a9f557 to your computer and use it in GitHub Desktop.
SSL ALPN Negotiation with .NET Core 2.1 Preview
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