Click here to Skip to main content
Licence CPOL
First Posted 28 Feb 2008
Views 8,361
Downloads 40
Bookmarked 9 times

Mentalis Based SecureSocketClient

By | 28 Feb 2008 | Article
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

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)

About the Author

Igor Sokolsky

Software Developer (Senior)

Canada Canada

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMentalis doesn't support .NET 2.0 x64 PinmemberMichael B. Hansen0:50 5 Mar '08  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 28 Feb 2008
Article Copyright 2008 by Igor Sokolsky
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid