private void buttonDecryptFile_Click(object sender, EventArgs e)
        {
            //open all files
            byte[]       encryptedFileContent = File.ReadAllBytes("EncryptedFile.txt");
            byte[]       encryptedSecretKey   = File.ReadAllBytes("EncriptedSecretKey.txt");
            byte[]       encryptedIV          = File.ReadAllBytes("EncriptedIV.txt");
            string       privateAndPublicKey  = File.ReadAllText(FILENAME_PUBLIC_PRIVATE_KEY);
            SymmetricsSI symmetricSI          = null;

            using (RSACryptoServiceProvider assymetricAlg = new RSACryptoServiceProvider()) {
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) {
                    assymetricAlg.FromXmlString(privateAndPublicKey);

                    byte[] secretKey = assymetricAlg.Decrypt(encryptedSecretKey, true);
                    byte[] iv        = assymetricAlg.Decrypt(encryptedIV, true);

                    aes.Key = secretKey;
                    aes.IV  = iv;

                    symmetricSI = new SymmetricsSI(aes);

                    File.WriteAllBytes("Decrypted.txt", symmetricSI.Decrypt(encryptedFileContent));
                }
            }
            MessageBox.Show("File Descrypted");
        }
 private void ButtonDecrypt_Click(object sender, EventArgs e)
 {
     using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) {
         aes.Key = key;
         aes.IV  = iv;
         using (SymmetricsSI symmetrics = new SymmetricsSI(aes)) {
             textBoxDecryptedText.Text = Encoding.UTF8.GetString(symmetrics.Decrypt(Convert.FromBase64String(textBoxEncryptedText.Text)));
         }
     }
 }
        private void btnVerifySignature_Click(object sender, EventArgs e)
        {
            try {
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                var signature = symmetricsSI.Decrypt(protocol.GetData());

                bool status = rsaServer.VerifyData(File.ReadAllBytes(FILE), new SHA256CryptoServiceProvider(), signature);
                MessageBox.Show(status ? "Assinatura é válida" : "Assinatura não é válida");
                lblVerify.Visible = true;
            } catch (Exception ex) {
                MessageBox.Show("ERROR: " + ex.Message);
                throw;
            }
        }
Beispiel #4
0
 private void ButtonDecrypt_Click(object sender, EventArgs e)
 {
     try
     {
         fileStreamReader = new StreamReader("temp.dat");
         textFileTemp     = fileStreamReader.ReadToEnd();
         byte[] encryptedBytes = Convert.FromBase64String(textFileTemp);
         byte[] clearBytes     = null;
         clearBytes = symmetricsSI.Decrypt(encryptedBytes); //Após a funcao, os valores não são os mesmos aos originais
         if (clearBytes.Length >= 200)
         {
             for (int i = 0; i < 200; i++)
             {
                 textBoxDecryptedData.AppendText(clearBytes[i].ToString());
             }
         }
         else
         {
             for (int i = 0; i < clearBytes.Length; i++)
             {
                 textBoxDecryptedData.AppendText(clearBytes[i].ToString());
             }
         }
         fileStreamReader.Close();
         fileStreamWriter = new StreamWriter("temp.dat");
         //fileStreamWriter.WriteLine(Encoding.UTF8.GetString(encryptedBytes))
         fileStreamWriter.WriteLine(Convert.ToBase64String(clearBytes));//assim como os resultados no file
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     finally
     {
         if (fileStreamReader != null)
         {
             fileStreamReader.Dispose();
         }
         if (fileStreamWriter != null)
         {
             fileStreamWriter.Dispose();
         }
     }
 }
        static void Main(string[] args)
        {
            IPEndPoint                  listenEndPoint;
            TcpListener                 listener      = null;
            TcpClient                   client        = null;
            NetworkStream               networkStream = null;
            ProtocolSI                  protocol      = null;
            RSACryptoServiceProvider    rsaClient     = null;
            RSACryptoServiceProvider    rsaServer     = null;
            AesCryptoServiceProvider    aes           = null;
            SymmetricsSI                symmetricsSI  = null;
            SHA256CryptoServiceProvider sha256        = null;

            try
            {
                Console.WriteLine($"** SERVER: Practical Exam on {DateTime.Today.ToLongDateString()} **");

                listenEndPoint = new IPEndPoint(IPAddress.Any, 10000);
                listener       = new TcpListener(listenEndPoint);

                Console.Write("Waiting for client... ");
                listener.Start();
                client        = listener.AcceptTcpClient();
                networkStream = client.GetStream();
                Console.WriteLine("OK.");

                protocol = new ProtocolSI();
                byte[] ack = protocol.Make(ProtocolSICmdType.ACK);

                rsaServer = new RSACryptoServiceProvider();
                rsaClient = new RSACryptoServiceProvider();
                aes       = new AesCryptoServiceProvider();

                Console.Write("Reading Public Key... ");
                networkStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("OK.");
                String clientPublicKey = protocol.GetStringFromData();
                byte[] packet          = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaServer.ToXmlString(false));
                Console.WriteLine("Sending Public Key... OK.");
                networkStream.Write(packet, 0, packet.Length);


                Console.Write("Reading Secret Key... ");
                networkStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                byte[] encryptedSymKey = protocol.GetData();
                aes.Key = rsaServer.Decrypt(encryptedSymKey, true);
                Console.WriteLine("OK.");
                networkStream.Write(ack, 0, ack.Length);

                Console.Write("Reading IV...");
                networkStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                aes.IV = protocol.GetData();
                Console.WriteLine("OK.");
                networkStream.Write(ack, 0, ack.Length);


                symmetricsSI = new SymmetricsSI(aes);
                Console.Write("Reading File Data... ");
                networkStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("OK.");
                byte[] data = symmetricsSI.Decrypt(protocol.GetData());
                sha256 = new SHA256CryptoServiceProvider();
                byte[] signature = rsaServer.SignData(data, sha256);
                Console.WriteLine("Sending Signature... OK.");
                packet = protocol.Make(ProtocolSICmdType.DATA, symmetricsSI.Encrypt(signature));
                networkStream.Write(packet, 0, packet.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.ToString()}");
            }
            finally
            {
                if (sha256 != null)
                {
                    sha256.Dispose();
                }
                if (aes != null)
                {
                    aes.Dispose();
                }
                if (rsaClient != null)
                {
                    rsaClient.Dispose();
                }
                if (rsaServer != null)
                {
                    rsaServer.Dispose();
                }
                if (networkStream != null)
                {
                    networkStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                }
                if (listener != null)
                {
                    listener.Stop();
                }
                Console.WriteLine("CLIENT should verify the digital signature.");
            }

            Console.Write("End: Press a key...");
            Console.ReadKey();
        } // main
        /// <summary>
        /// IMPORTANTE: a cada RECEÇÃO deve seguir-se, obrigatóriamente, um ENVIO de dados
        /// IMPORTANT: each network .Read() must be fallowed by a network .Write()
        /// </summary>
        static void Main(string[] args)
        {
            byte[]        msg;
            IPEndPoint    listenEndPoint;
            TcpListener   server    = null;
            TcpClient     client    = null;
            NetworkStream netStream = null;
            ProtocolSI    protocol  = null;

            try
            {
                Console.WriteLine("SERVER");

                #region Defenitions
                // Binding IP/port
                listenEndPoint = new IPEndPoint(IPAddress.Any, 9999);

                // Client/Server Protocol to SI
                protocol = new ProtocolSI();


                #endregion

                Console.WriteLine(SEPARATOR);

                #region TCP Listner
                // Start TcpListener
                server = new TcpListener(listenEndPoint);
                server.Start();

                // Waits for a client connection (bloqueant wait)
                Console.Write("waiting for a connection... ");
                client    = server.AcceptTcpClient();
                netStream = client.GetStream();
                Console.WriteLine("ok.");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Data (Unsecure channel)

                Console.WriteLine("waiting for key");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                byte[] key = protocol.GetData();

                Console.Write("Sending a ACK... ");
                msg = protocol.Make(ProtocolSICmdType.ACK);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok.");

                Console.WriteLine("waiting for iv");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                byte[] iv = protocol.GetData();

                Console.Write("Sending a ACK... ");
                msg = protocol.Make(ProtocolSICmdType.ACK);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok.");

                #endregion

                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) {
                    aes.Key = key;
                    aes.IV  = iv;

                    Console.WriteLine("waiting for message");
                    netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                    byte[] encryptedMessage = protocol.GetData();

                    SymmetricsSI symmetric = new SymmetricsSI(aes);

                    try {
                        //aes.Key = aes.IV;
                        string message = Encoding.UTF8.GetString(symmetric.Decrypt(encryptedMessage));

                        Console.WriteLine($"Recieved message: '{message}'");

                        Console.Write("Sending a ACK... ");
                        msg = protocol.Make(ProtocolSICmdType.ACK);
                        netStream.Write(msg, 0, msg.Length);
                        Console.WriteLine("ok.");
                    } catch (Exception) {
                        Console.Write("Sending a NACK... ");
                        msg = protocol.Make(ProtocolSICmdType.NACK);
                        netStream.Write(msg, 0, msg.Length);
                        Console.WriteLine("ok.");
                        throw;
                    }
                }
            } catch (Exception ex)
            {
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Exception: {0}", ex.ToString());
            }
            finally
            {
                // Close connections
                if (netStream != null)
                {
                    netStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                }
                if (server != null)
                {
                    server.Stop();
                }
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Connection with client was closed.");
            }

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key...");
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            byte[]                   msg;
            IPEndPoint               listenEndPoint;
            TcpListener              server       = null;
            TcpClient                client       = null;
            NetworkStream            netStream    = null;
            ProtocolSI               protocol     = null;
            AesCryptoServiceProvider aes          = null;
            SymmetricsSI             symmetricsSI = null;
            RSACryptoServiceProvider rsaClient    = null;
            RSACryptoServiceProvider rsaServer    = null;

            accounts.Add(123, 100.50);
            accounts.Add(456, 200.50);
            accounts.Add(789, 3000);

            try {
                Console.WriteLine("SERVER");

                #region Defenitions
                // algortimos assimétricos
                rsaClient = new RSACryptoServiceProvider();
                rsaServer = new RSACryptoServiceProvider();

                // algoritmos simétrico a usar...
                aes          = new AesCryptoServiceProvider();
                symmetricsSI = new SymmetricsSI(aes);

                // Binding IP/port
                listenEndPoint = new IPEndPoint(IPAddress.Any, 13000);

                // Client/Server Protocol to SI
                protocol = new ProtocolSI();


                #endregion

                Console.WriteLine(SEPARATOR);

                #region TCP Listner
                // Start TcpListener
                server = new TcpListener(listenEndPoint);
                server.Start();

                // Waits for a client connection (bloqueant wait)
                Console.Write("waiting for a connection... ");
                client    = server.AcceptTcpClient();
                netStream = client.GetStream();
                Console.WriteLine("ok");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exhange Public Keys
                // Receive client public key
                Console.Write("waiting for client public key...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                rsaClient.FromXmlString(protocol.GetStringFromData());
                Console.WriteLine("ok");

                // Send public key...
                Console.Write("Sending public key... ");
                msg = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaServer.ToXmlString(false));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Secret Key
                // Receive key
                Console.Write("waiting for key...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                aes.Key = rsaServer.Decrypt(protocol.GetData(), true);
                Console.WriteLine("ok");
                Console.WriteLine("   Received: {0} ", ProtocolSI.ToHexString(aes.Key));

                // Answer with a ACK
                Console.Write("Sending a ACK... ");
                msg = protocol.Make(ProtocolSICmdType.ACK);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");


                // Receive iv
                Console.Write("waiting for iv...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                aes.IV = rsaServer.Decrypt(protocol.GetData(), true);
                Console.WriteLine("ok");
                Console.WriteLine("   Received: {0} ", ProtocolSI.ToHexString(aes.IV));

                // Answer with a ACK
                Console.Write("Sending a ACK... ");
                msg = protocol.Make(ProtocolSICmdType.ACK);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Data (Secure channel)
                // Receive the cipher
                Console.Write("waiting for data...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                byte[] encryptedData = protocol.GetData();
                byte[] data          = symmetricsSI.Decrypt(encryptedData);
                int    account       = BitConverter.ToInt32(data, 0);
                Console.WriteLine("ok");
                Console.WriteLine("   Encrypted: {0}", ProtocolSI.ToHexString(encryptedData));
                Console.WriteLine("   Data: {0} = {1}", account, ProtocolSI.ToHexString(data));

                // Answer with balance
                byte[] clearData = BitConverter.GetBytes(accounts[account]);
                Console.Write("Sending  data... ");
                encryptedData = symmetricsSI.Encrypt(clearData);
                msg           = protocol.Make(ProtocolSICmdType.DATA, encryptedData);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                Console.WriteLine("   Data: {0} = {1}", BitConverter.ToDouble(clearData, 0), ProtocolSI.ToHexString(clearData));
                Console.WriteLine("   Encrypted: {0}", ProtocolSI.ToHexString(encryptedData));
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Sending DIGITAL SIGNATURE
                Console.Write("waiting... ");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine(protocol.GetCmdType());

                Console.Write("Sending digital signature... ");
                msg = protocol.Make(ProtocolSICmdType.DIGITAL_SIGNATURE, rsaServer.SignData(encryptedData, new SHA256CryptoServiceProvider()));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("OK");

                //encryptedData[0] = 0;

                /*bool status = rsaClient.VerifyData(encryptedData, new SHA256CryptoServiceProvider(), signature);
                 * Console.WriteLine("OK");
                 *
                 * Console.WriteLine("STATUS SIGNATURE = " + status);
                 *
                 * Console.Write("Sending (N)ACK...");
                 *
                 * if (status) {
                 *  msg = protocol.Make(ProtocolSICmdType.ACK);
                 * } else {
                 *  msg = protocol.Make(ProtocolSICmdType.NACK);
                 * }
                 * netStream.Write(msg, 0, msg.Length);
                 *
                 * Console.WriteLine("OK");
                 *
                 *
                 * /*if (status) {
                 *  byte[] data = symmetricsSI.Decrypt(encryptedData);
                 *  Console.WriteLine("ok");
                 *  Console.WriteLine("   Encrypted: {0}", ProtocolSI.ToHexString(encryptedData));
                 *  Console.WriteLine("   Data: {0} = {1}", ProtocolSI.ToString(data), ProtocolSI.ToHexString(data));
                 * }*/

                #endregion
            } catch (Exception ex) {
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Exception: {0}", ex.ToString());
            } finally {
                // Close connections
                if (netStream != null)
                {
                    netStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                }
                if (server != null)
                {
                    server.Stop();
                }
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Connection with client was closed.");
            }

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key...");
            Console.ReadKey();
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            byte[]                   msg;
            IPEndPoint               serverEndPoint;
            TcpClient                client       = null;
            NetworkStream            netStream    = null;
            ProtocolSI               protocol     = null;
            AesCryptoServiceProvider aes          = null;
            SymmetricsSI             symmetricsSI = null;
            RSACryptoServiceProvider rsaClient    = null;
            RSACryptoServiceProvider rsaServer    = null;

            try {
                Console.WriteLine("CLIENT");

                #region Defenitions
                // algortimos assimétricos
                rsaClient = new RSACryptoServiceProvider();
                rsaServer = new RSACryptoServiceProvider();

                // algoritmos simétrico a usar...
                aes          = new AesCryptoServiceProvider();
                symmetricsSI = new SymmetricsSI(aes);


                // Client/Server Protocol to SI
                protocol = new ProtocolSI();

                // Defenitions for TcpClient: IP:port (127.0.0.1:13000)
                serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000);
                #endregion

                Console.WriteLine(SEPARATOR);

                #region TCP Connection
                // Connects to Server ...
                Console.Write("Connecting to server... ");
                client = new TcpClient();
                client.Connect(serverEndPoint);
                netStream = client.GetStream();
                Console.WriteLine("ok");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Public Keys
                // Send public key...
                Console.Write("Sending public key... ");
                msg = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaClient.ToXmlString(false));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");

                // Receive server public key
                Console.Write("waiting for server public key...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                rsaServer.FromXmlString(protocol.GetStringFromData());
                Console.WriteLine("ok");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Secret Key
                // Send key...
                Console.Write("Sending  key... ");
                msg = protocol.Make(ProtocolSICmdType.SECRET_KEY, rsaServer.Encrypt(aes.Key, true));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                Console.WriteLine("   Sent: " + ProtocolSI.ToHexString(aes.Key));

                // Receive ack
                Console.Write("waiting for ACK...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");


                // Send iv...
                Console.Write("Sending  iv... ");
                msg = protocol.Make(ProtocolSICmdType.IV, rsaServer.Encrypt(aes.IV, true));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                Console.WriteLine("   Sent: " + ProtocolSI.ToHexString(aes.IV));

                // Receive ack
                Console.Write("waiting for ACK...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");

                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Data (Secure channel)
                // Send data...
                byte[] clearData = BitConverter.GetBytes(ACCOUNT);
                Console.Write("Sending  data... ");
                byte[] encryptedData = symmetricsSI.Encrypt(clearData);
                msg = protocol.Make(ProtocolSICmdType.DATA, encryptedData);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                Console.WriteLine("   Data: {0} = {1}", BitConverter.ToInt32(clearData, 0), ProtocolSI.ToHexString(clearData));
                Console.WriteLine("   Encrypted: {0}", ProtocolSI.ToHexString(encryptedData));

                // Receive answer from server
                Console.Write("waiting for data...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                encryptedData = protocol.GetData();
                byte[] data    = symmetricsSI.Decrypt(encryptedData);
                double balance = BitConverter.ToDouble(data, 0);
                Console.WriteLine("ok");
                Console.WriteLine("   Encrypted: {0}", ProtocolSI.ToHexString(encryptedData));
                Console.WriteLine("   Data: {0} = {1}", balance, ProtocolSI.ToHexString(data));
                #endregion



                #region Ask for Digital Signature
                Console.Write("Asking for digital signature.. ");
                msg = protocol.Make(ProtocolSICmdType.USER_OPTION_1);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("OK");

                Console.Write("waiting for digital signature...");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                var signature = protocol.GetData();

                //encryptedData[0] = 0;
                bool status = rsaServer.VerifyData(encryptedData, new SHA256CryptoServiceProvider(), signature);
                Console.WriteLine("OK");

                Console.WriteLine("STATUS SIGNATURE = " + status);
                #endregion
            } catch (Exception ex) {
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Exception: {0}", ex.ToString());
            } finally {
                // Close connections
                if (netStream != null)
                {
                    netStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                }
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Connection with server was closed.");
            }

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key...");
            Console.ReadKey();
        }
Beispiel #9
0
        /// <summary>
        /// IMPORTANTE: a cada RECEÇÃO deve seguir-se, obrigatóriamente, um ENVIO de dados
        /// IMPORTANT: each network .Read() must be fallowed by a network .Write()
        /// </summary>
        static void Main(string[] args)
        {
            byte[]        msg;
            IPEndPoint    listenEndPoint;
            TcpListener   server    = null;
            TcpClient     client    = null;
            NetworkStream netStream = null;
            ProtocolSI    protocol  = null;
            TripleDESCryptoServiceProvider tripleDES = null;
            SymmetricsSI symmetricsSI = null;

            RSACryptoServiceProvider rsaClient = null;
            RSACryptoServiceProvider rsaServer = null;

            try {
                Console.WriteLine("SERVER");

                #region Definitions
                // Binding IP/port
                listenEndPoint = new IPEndPoint(IPAddress.Any, 9999);

                // Client/Server Protocol to SI
                protocol = new ProtocolSI();

                // algoritmo simétrico a usar
                tripleDES    = new TripleDESCryptoServiceProvider();
                symmetricsSI = new SymmetricsSI(tripleDES);

                rsaClient = new RSACryptoServiceProvider();
                rsaServer = new RSACryptoServiceProvider();

                if (File.Exists(FILENAME_PUBLIC_PRIVATE_KEY))
                {
                    rsaServer.FromXmlString(File.ReadAllText(FILENAME_PUBLIC_PRIVATE_KEY));
                }
                else
                {
                    File.WriteAllText(FILENAME_PUBLIC_PRIVATE_KEY, rsaServer.ToXmlString(true));
                }
                #endregion

                Console.WriteLine(SEPARATOR);

                #region TCP Listner
                // Start TcpListener
                server = new TcpListener(listenEndPoint);
                server.Start();

                // Waits for a client connection (bloqueant wait)
                Console.Write("waiting for a connection... ");
                client    = server.AcceptTcpClient();
                netStream = client.GetStream();
                Console.WriteLine("ok.");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Public Key


                // receber a chave publica do cliente
                Console.Write("Waiting client public key .. ");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                rsaClient.FromXmlString(protocol.GetStringFromData());
                Console.WriteLine("ok");
                Console.WriteLine($"client public key = {protocol.GetStringFromData()}");


                // partilhar a chave publica do servidor com o cliente
                Console.Write("Sending server public key .. ");
                msg = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaServer.ToXmlString(false));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok");
                Console.WriteLine($"server public key = {rsaServer.ToXmlString(false)}");

                #endregion

                #region Exchange Secret Key
                // Receive the key
                Console.Write("waiting for key... ");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                tripleDES.Key = rsaServer.Decrypt(protocol.GetData(), true);
                Console.WriteLine("ok.");
                Console.WriteLine("Received: {0}", ProtocolSI.ToHexString(tripleDES.Key));

                // Answer with a ACK
                Console.Write("Sending a ACK... ");
                msg = protocol.Make(ProtocolSICmdType.ACK);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok.");

                // Receive the iv
                Console.Write("waiting for iv... ");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                tripleDES.IV = rsaServer.Decrypt(protocol.GetData(), true);
                Console.WriteLine("ok.");
                Console.WriteLine("Received: {0}", ProtocolSI.ToHexString(tripleDES.IV));

                // Answer with a ACK
                Console.Write("Sending a ACK... ");
                msg = protocol.Make(ProtocolSICmdType.ACK);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok.");
                #endregion

                Console.WriteLine(SEPARATOR);

                #region Exchange Data  (secure channel)
                // Receive the cipher data
                Console.Write("waiting for data... ");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                byte[] data = symmetricsSI.Decrypt(protocol.GetData());
                Console.WriteLine("ok.");
                Console.WriteLine("Encrypted data received (HEX): {0}", ProtocolSI.ToHexString(protocol.GetData()));
                Console.WriteLine("Decrypted data......... (HEX): {0}", ProtocolSI.ToHexString(data));
                Console.WriteLine("Decrypted data......... (STR): {0}", ProtocolSI.ToString(data));

                // Answer with a ACK
                Console.Write("Sending a ACK... ");
                msg = protocol.Make(ProtocolSICmdType.ACK);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok.");
                #endregion
            } catch (Exception ex) {
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Exception: {0}", ex.ToString());
            } finally {
                // Close connections
                if (netStream != null)
                {
                    netStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                }
                if (server != null)
                {
                    server.Stop();
                }
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Connection with client was closed.");
            }

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key... ");
            Console.ReadKey();
        }