Click here to Skip to main content
15,897,187 members
Articles / Programming Languages / C#
Article

Mentalis Based SecureSocketClient

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
28 Feb 2008CPOL 21.5K   108   9   1
Mentalis based SecureSocketClient

Introduction

The idea of this article is to show how to use SecureSocketClient - especially for OnVerify and OnCertificateRequest methods.

The SecureSocketClient class is thread safe.

Background

When SSL or TSL connection is established, the server and client have to have valid certificates installed.

When the client validates a server, the OnVerify method is called and when the server validates a client, the OnCertificateRequest is called.

Don't forget to download and add a reference to the Mentalis DLL.

Using the Code

C#
SecureSocketClient code 
/// <summary>
/// 
/// </summary>
/// <param name=&quot;secureSocket&quot;>true to use a TLS1 otherwise regular socket</param>
public void InitSocket(bool secureSocket)
{
    string serverCN = &quot;ANY COMMON NAME.COM&quot;;
    SecurityOptions options = null;
         if (secureSocket)
            {
                // initialize the security options
                // most of the security parameters can be null for 
                // a non secure connection
                options = new SecurityOptions(
                // protocol to use, here TLS1. 
                // For a regular, non secure TCP connection, use SecureProtocol.None
                SecureProtocol.Tls1,
                null,
                    // this is the client side
                ConnectionEnd.Client,
                    //manual certificate verification
                CredentialVerification.Manual,
                    // callback for certificate verification
                new CertVerifyEventHandler(OnVerify),
                    // this is the common name of the web server
                serverCN,
                    // use the default security flags
                SecurityFlags.Default,
                    // only use the RSA_AES_128 cipher
                SslAlgorithms.RSA_AES_128_SHA | SslAlgorithms.NULL_COMPRESSION,
                    // callback to process certificate request
                new CertRequestEventHandler(OnCertificateRequest));
                m_SecureSocket = new SecureSocket(AddressFamily.InterNetwork, 
                                 SocketType.Stream, ProtocolType.Tcp, options);
            }
            else
            {
                m_SecureSocket = new SecureSocket
                     (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }

        } 
  /// <summary>
  /// Verifies a certificate received from the remote host.
  /// </summary>
  /// <param name=&quot;socket&quot;>The SecureSocket that received the certificate.</param>
  /// <param name=&quot;remote&quot;>The received certificate.</param>
  /// <param name=&quot;e&quot;>The event parameters.</param>
  private void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e)
  {
      CertificateChain cc = new CertificateChain(remote, new CertificateStore(&quot;ROOT&quot;));
      Certificate[] cchain = cc.GetCertificates();
      CertificateStatus cs = cc.VerifyChain(socket.CommonName, AuthType.Server);
      m_Cert = cs;
      m_CertVerified.Set();
  }
/// <summary>
/// Verifies a certificate received from the remote host.
/// </summary>
/// <param name=&quot;socket&quot;>The SecureSocket that received the certificate.</param>
/// <param name=&quot;remote&quot;>The received certificate.</param>
/// <param name=&quot;e&quot;>The event parameters.</param>
private void OnCertificateRequest(SecureSocket socket, DistinguishedNameList acceptable, RequestEventArgs e)
{
    //Load the PFX certificate
    string file = @&quot;..\..\client.pfx&quot;;// client cert file
    string pass = &quot;password&quot;;

    Certificate cert = Certificate.CreateFromPfxFile(file, pass, true);

    //save certificate information
    e.Certificate = cert;
}
 
public SecureSocketClientTest()
{
    //false for open communication,true for TLS1
    SecureSocketClient.Instance.InitSocket(false);
    SecureSocketClient.Instance.Connect(&quot;15.9.9.99&quot;, 12345);
    SecureSocketClient.Instance.OnDataReceivedEvent += 
            new OnDataReceivedDelegate(OnReceived);
}

//This is a delegate that is registered with the SecureSocketClient 
//and is invoked when reply arrived from a remote end
private void OnReceived(byte[] reply,int size)
 {
      if (textBox1.InvokeRequired)
      {
         textBox1.Invoke(new OnDataReceivedDelegate(OnReceived), new object[2] 
                { reply, size });
      }
      else
      {
         string rep = Encoding.ASCII.GetString(reply,0,size);
         textBox1.Text += rep;
      }
}
private void Send_Click(object sender, EventArgs e)
{
    string cmd = &quot;(CMD GetStatus)&quot;
    SecureSocketClient.Instance.Post(Encoding.ASCII.GetBytes(cmd));
}

History

  • 28th February, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMentalis doesn't support .NET 2.0 x64 Pin
Michael B. Hansen5-Mar-08 0:50
Michael B. Hansen5-Mar-08 0:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.