using System; using System.Runtime.InteropServices; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using wolfSSL.CSharp; public class wolfSSL_TLS_CSHarp { /// /// Example of a logging function /// /// level of log /// message to log public static void standard_log(int lvl, StringBuilder msg) { Console.WriteLine(msg); } public static void Main(string[] args) { IntPtr ctx; IntPtr ssl; Socket fd; /* These paths should be changed for use */ string fileCert = @"server-cert.pem"; string fileKey = @"server-key.pem"; StringBuilder dhparam = new StringBuilder("dh2048.pem"); StringBuilder buff = new StringBuilder(1024); StringBuilder reply = new StringBuilder("Hello, this is the wolfSSL C# wrapper"); //example of function used for setting logging wolfssl.SetLogging(standard_log); wolfssl.Init(); Console.WriteLine("Calling ctx Init from wolfSSL"); ctx = wolfssl.CTX_new(wolfssl.usev23_server()); Console.WriteLine("Finished init of ctx .... now load in cert and key"); if (!File.Exists(fileCert) || !File.Exists(fileKey)) { Console.WriteLine("Could not find cert or key file"); return; } if (wolfssl.CTX_use_certificate_file(ctx, fileCert, wolfssl.SSL_FILETYPE_PEM) != wolfssl.SUCCESS) { Console.WriteLine("Error in setting cert file"); return; } if (wolfssl.CTX_use_PrivateKey_file(ctx, fileKey, wolfssl.SSL_FILETYPE_PEM) != wolfssl.SUCCESS) { Console.WriteLine("Error in setting key file"); return; } StringBuilder ciphers = new StringBuilder(new String(' ', 4096)); wolfssl.get_ciphers(ciphers, 4096); Console.WriteLine("Ciphers : " + ciphers.ToString()); short minDhKey = 128; wolfssl.CTX_SetMinDhKey_Sz(ctx, minDhKey); /* set up TCP socket */ IPAddress ip = IPAddress.Parse("0.0.0.0"); //bind to any TcpListener tcp = new TcpListener(ip, 11111); tcp.Start(); Console.WriteLine("Started TCP and waiting for a connection"); fd = tcp.AcceptSocket(); ssl = wolfssl.new_ssl(ctx); Console.WriteLine("Connection made wolfSSL_accept "); if (wolfssl.set_fd(ssl, fd) != wolfssl.SUCCESS) { /* get and print out the error */ Console.Write(wolfssl.get_error(ssl)); return; } wolfssl.SetTmpDH_file(ssl, dhparam, wolfssl.SSL_FILETYPE_PEM); if (wolfssl.accept(ssl) != 1) { /* get and print out the error */ Console.Write(wolfssl.get_error(ssl)); return; } /* print out results of TLS/SSL accept */ Console.WriteLine("SSL version is " + wolfssl.get_version(ssl)); Console.WriteLine("SSL cipher suite is " + wolfssl.get_current_cipher(ssl)); /* read and print out the message then reply */ if (wolfssl.read(ssl, buff, 1023) < 0) { Console.WriteLine("Error in read"); return; } Console.WriteLine(buff); if (wolfssl.write(ssl, reply, reply.Length) != reply.Length) { Console.WriteLine("Error in write"); return; } wolfssl.shutdown(ssl); wolfssl.free(ssl); fd.Close(); wolfssl.CTX_free(ctx); wolfssl.Cleanup(); } }