Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ssl/tls with socket tcp

Tags:

c#

tcp

ssl

I am new in C# development. I am trying to use ssl/tls over tcp but in my code, system.net.sockets.socket (bare socket) is used not tcpclient or tcplistner. I have searched over net atleast 200 links but I didn't get anything related that. I want to use less coding and done ssl or tsll over tcp socket connection. I have client, server, ca certificate, key in .key format. Please help with example or link. You can ask questions if u feel more details.

like image 781
Bittu Shah Avatar asked Sep 03 '16 07:09

Bittu Shah


1 Answers

Why don't you want to use TcpClient? Creating a SSL connection with TcpClient and Ssltream is quite easy. Unless you require thousands of simultaneous connections I would stick with TcpClient and SSLStream.

A basic TcpClient and SslStream example would be as follows:

static void Main(string[] args)
{
    string server = "127.0.0.1";
    TcpClient client = new TcpClient(server, 443);

    using (SslStream sslStream = new SslStream(client.GetStream(), false,
        new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
    {
        sslStream.AuthenticateAsClient(server);
        // This is where you read and send data
    }
    client.Close();
}

public static bool ValidateServerCertificate(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true;
}

High performance socket code can be difficult to write in .NET but there are good examples out there. You have a number of choices. I'm not sure one solution fits all so I'll list a few here.

  1. Using an [Asynchronous Client Socket] maybe be a good place to start
  2. There are a few existing libraries you can make use of. I've used Nito/Async however I don't think it has been updated since 2009. There was talk of a version 2 but I don't believe it materialized.
  3. I'm not familar with it but CodeProject has C# SocketAsyncEventArgs High Performance Socket Code
  4. Review Microsoft's guidance, High Performance .NET Socket Server Using Async Winsock
  5. Read everything that Stephen Toub has to say including Awaiting Socket Operations

I didn't address SSL specifically but look into the SslStream Class.

You'll also want to look into buffer pooling. If you're serving thousands of clients garbage collection will be a problem. An excellent introduction to this is Sunny Ahuwanya's Blog


https://github.com/StephenCleary/AsyncEx

before.

like image 103
Mark Avatar answered Sep 21 '22 15:09

Mark