Mentalis.org Security Library documentation

SSL and TLS

Upgrading network projects to use SSL/TLS

Upgrading existing .NET projects to use SSL or TLS is pretty easy with the Mentalis.org Security Library. Many projects only require a few lines of code per socket to upgrade to SSL and TLS.

In this tutorial, we'll upgrade an existing HTTP client to an HTTPS client. For simplicity reasons, we'll use a very small and straightforward client.

Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(endpoint);
byte[] buffer = Encoding.ASCII.GetBytes(request);
int sent = s.Send(buffer, 0, buffer.Length, SocketFlags.None);
buffer = new byte[4096];
int ret = s.Receive(buffer);
while(ret != 0) {
    Console.Write(Encoding.ASCII.GetString(buffer, 0, ret));
    ret = s.Receive(buffer);
}
s.Shutdown(SocketShutdown.Both);
s.Close();

The above code connects to a server, sends a HTTP request, waits for the reply of the server and closes the connection when the reply has been received. request is a string that contains the HTTP request and endPoint is the IPEndPoint of the server it's trying to connect to.
Now lets say we want to upgrade this code to support HTTPS instead of HTTP. This means we must use SSL or TLS to connect to the web server and send our HTTP data over that secure connection. Here's how you can do it with the Security Library:

SecurityOptions options = new SecurityOptions(SecureProtocol.Tls1 | SecureProtocol.Ssl3, null, ConnectionEnd.Client);
SecureSocket s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
s.Connect(endpoint);
byte[] buffer = Encoding.ASCII.GetBytes(request);
int sent = s.Send(buffer, 0, buffer.Length, SocketFlags.None);
buffer = new byte[4096];
int ret = s.Receive(buffer);
while(ret != 0) {
    Console.Write(Encoding.ASCII.GetString(buffer, 0, ret));
    ret = s.Receive(buffer);
}
s.Shutdown(SocketShutdown.Both);
s.Close();

As you can see, the Socket instances are redefined as SecureSocket instances and the SecureSocket constructor takes one parameter more than the Socket constructor. The options variable is a SecurityOptions object that holds various the SSL and TLS settings. The different fields of the SecurityOptions class are well documented.