// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Security.Cryptography.X509Certificates; using System.IO; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Text; namespace SocketDemo.Binary.SecureHigh.Client { public class Program { private static int HTON(int v) { if(BitConverter.IsLittleEndian) { byte[] buf = BitConverter.GetBytes(v); Array.Reverse(buf); return BitConverter.ToInt32(buf, 0); } else { return v; } } private static int NTOH(int v) { if(BitConverter.IsLittleEndian) { byte[] buf = BitConverter.GetBytes(v); Array.Reverse(buf); return BitConverter.ToInt32(buf, 0); } else { return v; } } private static bool CertCheck(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Console.WriteLine("(server is {0})", certificate.Subject); return true; } private const string HOST = "localhost"; private const int PORT = 12345; public static void Main(string[] args) { // open connection TcpClient cli = new TcpClient(HOST, PORT); // get reader and writer NetworkStream stm = cli.GetStream(); SslStream sslstm = new SslStream(stm, false, CertCheck); sslstm.AuthenticateAsClient("CN=Arne Vajhoej,OU=Demo,O=Personal,L=Coventry,ST=RI,C=US", null, SslProtocols.Tls12, true); BinaryReader br = new BinaryReader(sslstm); BinaryWriter bw = new BinaryWriter(sslstm); Console.WriteLine("(connected)"); // send a and b int a = 123; int b = 456; bw.Write(HTON(a)); bw.Write(HTON(b)); bw.Flush(); // receive c and print int c = NTOH(br.ReadInt32()); Console.WriteLine(c); // send v string v = "ABC"; byte[] vb = Encoding.UTF8.GetBytes(v); bw.Write((byte)vb.Length); bw.Write(vb); bw.Flush(); // receive v2 and print int buflen = br.ReadByte(); byte[] buf = new byte[buflen]; int ix = 0; while (ix < buf.Length) { ix += br.Read(buf, ix, buf.Length - ix); } string v2 = Encoding.UTF8.GetString(buf); Console.WriteLine(v2); // close connection br.Close(); bw.Close(); cli.Close(); } } }