SslStream Sample

Just a quick sample how to get up and running with SslStream in .NET 2.0 (works with november CTP). you can download the source here. enjoy. (8.32 KB)


The Server
It’s pretty straightforward – grab the server certificate from the cert store, open a socket and wait for incoming connections. When a client connects start the SSL authentication handshake. You can then connect the SslStream with a Reader and get input from your clients.

static void Main(string[] args)
  X509Certificate cert = getServerCert();
  TcpListener sslServer = new TcpListener(4242);


  Console.WriteLine(“Waiting for incoming connection…”);
  TcpClient client = sslServer.AcceptTcpClient();

  SslStream sslStream = new SslStream(client.GetStream());
  sslStream.AuthenticateAsServer(cert,false, SslProtocolType.Default, false);

private static X509Certificate getServerCert()
  X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
  X509CertificateCollection cert = store.Certificates.Find(X509FindType.FindBySubjectName, “SslStreamCert”, true);
  return cert[0];

The Client
You open a connection to the server and start the authentication handshake with AuthenticateAsClient. You pass in the expected name of the server certificate (like your browser does when he expects to connect to, e.g. paypal or whatever) and hook up a callback that optionally validates the server certificate. After that you can just pump data through the stream. I omitted the ShowSslInfo method for brevity, this shows you the issuer, thumbprint, public key, expirations dates a.s.o. (but it is included in the download).

static void Main(string[] args)
    string certName = “SslStreamCert”;

    TcpClient sslClient = new TcpClient();
    sslClient.Connect(“localhost”, 4242);

    SslStream sslStream = new SslStream(sslClient.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback));

    showSslInfo(certName, sslStream, true);
    StreamWriter writer = new StreamWriter(sslStream);
    writer.Write(“Hello SslStream”);
  catch (System.Exception ex)

static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  if (sslPolicyErrors != SslPolicyErrors.None)
    Console.WriteLine(“SSL Certificate Validation Error!”);
    return false;
    return true;


This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to SslStream Sample

  1. iosif hamlatzis says:

    the link for the zip file is no longer valid

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s