Esempio n. 1
0
 private void ButtonEncrypt_Click(object sender, EventArgs e)
 {
     using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) {
         key = aes.Key;
         iv  = aes.IV;
         using (SymmetricsSI symmetrics = new SymmetricsSI(aes)) {
             textBoxEncryptedText.Text = Convert.ToBase64String(symmetrics.Encrypt(Encoding.UTF8.GetBytes(textBoxTextToEncrypt.Text)));
         }
     }
 }
        private void btnSendFileReceiveSignature_Click(object sender, EventArgs e)
        {
            try {
                encryptedData = symmetricsSI.Encrypt(File.ReadAllBytes(FILE));
                var msg = protocol.Make(ProtocolSICmdType.DATA, encryptedData);
                netStream.Write(msg, 0, msg.Length);

                lblSendFile.Visible = true;
            } catch (Exception ex) {
                MessageBox.Show("ERROR: " + ex.Message);
                throw;
            }
        }
Esempio n. 3
0
 private void ButtonEncrypt_Click(object sender, EventArgs e)
 {
     try
     {
         byte[] textFileBytes  = Encoding.UTF8.GetBytes(textFile); //a var textFile vem da funcao ButtonChooseFile
         string textFile64     = Convert.ToBase64String(textFileBytes);
         byte[] clearBytes     = Encoding.UTF8.GetBytes(textFile64);
         byte[] encryptedBytes = null;
         encryptedBytes = symmetricsSI.Encrypt(clearBytes);
         if (encryptedBytes.Length >= 100)
         {
             for (int i = 0; i < 100; i++)
             {
                 textBoxEncryptedData.AppendText(encryptedBytes[i].ToString());
             }
         }
         else
         {
             for (int i = 0; i < encryptedBytes.Length; i++)
             {
                 textBoxEncryptedData.AppendText(encryptedBytes[i].ToString());
             }
         }
         fileStreamWriter = new StreamWriter("temp.dat");
         fileStreamWriter.WriteLine(Convert.ToBase64String(encryptedBytes));//Os valores são escritos
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     finally
     {
         if (file != null)
         {
             file.Close();
         }
         if (fileStreamReader != null)
         {
             fileStreamReader.Dispose();
         }
         if (fileStreamWriter != null)
         {
             fileStreamWriter.Dispose();
         }
     }
 }
Esempio n. 4
0
        private void ButtonEncryptFile_Click(object sender, EventArgs e)
        {
            string filenameOriginal = "";

            byte[]       fileClearContent     = null;
            byte[]       fileEncryptedContent = null;
            SymmetricsSI symmetrics           = null;

            using (OpenFileDialog openFile = new OpenFileDialog()) {
                if (openFile.ShowDialog() == DialogResult.OK)
                {
                    filenameOriginal = openFile.FileName;
                    //MessageBox.Show(filenameOriginal);

                    fileClearContent = File.ReadAllBytes(filenameOriginal);
                    using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) {
                        aes.Key              = secretKey;
                        aes.IV               = iv;
                        symmetrics           = new SymmetricsSI(aes);
                        fileEncryptedContent = symmetrics.Encrypt(fileClearContent);
                    }
                    //Save Assymetric keys
                    File.WriteAllText(FILENAME_PUBLIC_KEY, tbPublicKey.Text);
                    File.WriteAllText(FILENAME_PUBLIC_PRIVATE_KEY, tbBothKeys.Text);

                    //Save symmetric components BUT encrypted (key + IV)
                    File.WriteAllBytes(@"EncryptedFile.txt", fileEncryptedContent);
                    File.WriteAllBytes(@"EncriptedSecretKey.txt", secretKeyEncrypted);
                    File.WriteAllBytes(@"EncriptedIV.txt", ivEncrypted);

                    MessageBox.Show("File Encrypted and components saved");
                }
            }

            //if (fileClearContent != null)
            //{
            //    //cifrar o ficheiro com um algoritmo simétrico
            //}
        }
Esempio n. 5
0
        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
Esempio n. 6
0
        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();
        }
Esempio n. 7
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();
        }
Esempio n. 8
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[]        key, iv;
            byte[]        msg;
            IPEndPoint    serverEndPoint;
            TcpClient     client    = null;
            NetworkStream netStream = null;
            ProtocolSI    protocol  = null;

            try
            {
                Console.WriteLine("CLIENT");

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

                // Defenitions for TcpClient: IP:port (127.0.0.1:9999)
                serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
                #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 Data (Unsecure channel)

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

                Console.WriteLine("Sending KEY");
                msg = protocol.Make(ProtocolSICmdType.SECRET_KEY, key);
                netStream.Write(msg, 0, msg.Length);

                Console.WriteLine("WAITING ACK");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                Console.WriteLine("Sending IV");
                msg = protocol.Make(ProtocolSICmdType.IV, iv);
                netStream.Write(msg, 0, msg.Length);


                Console.WriteLine("WAITING ACK");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                #endregion

                Console.Write("Indique a mensagem para enviar: ");
                string messageSend = Console.ReadLine();
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) {
                    aes.Key = key;
                    aes.IV  = iv;

                    SymmetricsSI symmetrics = new SymmetricsSI(aes);
                    var          send       = symmetrics.Encrypt(Encoding.UTF8.GetBytes(messageSend));

                    Console.WriteLine("Sending ENCRYPTED MESSAGE");
                    msg = protocol.Make(ProtocolSICmdType.SYM_CIPHER_DATA, send);
                    netStream.Write(msg, 0, msg.Length);

                    Console.WriteLine("WAITING ACK");
                    netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                    Console.WriteLine($"Recieved from server: '{protocol.GetCmdType()}'");
                }
            } 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();
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            TcpClient tcpc = null;
            NetworkStream stream = null;
            TripleDESCryptoServiceProvider crypto = null;
            SymmetricsSI symmetrics = null;

            try
            {
                Console.Write("A ligar ao servidor... ");
                tcpc = new TcpClient();
                tcpc.Connect("", 9999);
                Console.WriteLine("ok");
                stream = tcpc.GetStream();

                ProtocolSI protocol = new ProtocolSI();
                byte[] packet;

                crypto = new TripleDESCryptoServiceProvider();
                symmetrics = new SymmetricsSI(crypto);

                // Send key

                packet = protocol.Make(ProtocolSICmdType.PADDING, (int)crypto.Padding);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                packet = protocol.Make(ProtocolSICmdType.IV, crypto.IV);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                packet = protocol.Make(ProtocolSICmdType.MODE, (int)crypto.Mode);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                packet = protocol.Make(ProtocolSICmdType.SECRET_KEY, crypto.Key);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                packet = protocol.Make(ProtocolSICmdType.EOF);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                var message = symmetrics.Encrypt(Encoding.UTF8.GetBytes("HelloWorld"));
                packet = protocol.Make(ProtocolSICmdType.SYM_CIPHER_DATA, message);
                stream.Write(packet, 0, packet.Length);

                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                if (protocol.GetCmdType() != ProtocolSICmdType.ACK)
                    throw new Exception("Server could not decrypt");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                Console.WriteLine("disconnected");
                if (stream != null) stream.Dispose();
                if (tcpc != null) tcpc.Close();
                if (crypto != null) crypto.Dispose();
                if (symmetrics != null) crypto.Dispose();
            }
        }
Esempio n. 10
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    serverEndPoint;
            TcpClient     client    = null;
            NetworkStream netStream = null;
            ProtocolSI    protocol  = null;
            TripleDESCryptoServiceProvider tripleDES = null;
            SymmetricsSI symmetricsSI = null;

            RSACryptoServiceProvider rsaClient = null;
            RSACryptoServiceProvider rsaServer = null;

            try {
                Console.WriteLine("CLIENT");

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

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

                // 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))
                {
                    rsaClient.FromXmlString(File.ReadAllText(FILENAME_PUBLIC_PRIVATE_KEY));
                }
                else
                {
                    File.WriteAllText(FILENAME_PUBLIC_PRIVATE_KEY, rsaClient.ToXmlString(true));
                }
                #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 Key

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

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

                #endregion


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

                // Receive ack from server
                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(tripleDES.IV, true));
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok.");
                Console.WriteLine("IV: " + ProtocolSI.ToHexString(tripleDES.IV));

                // Receive ack from server
                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     = Encoding.UTF8.GetBytes("hello world!!!");
                byte[] encryptedData = symmetricsSI.Encrypt(clearData);
                Console.Write("Sending  data... ");
                msg = protocol.Make(ProtocolSICmdType.DATA, encryptedData);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok.");
                Console.WriteLine("Data to encrypt.... (STR): {0}", ProtocolSI.ToString(clearData));
                Console.WriteLine("Data to encrypt.... (HEX): {0}", ProtocolSI.ToHexString(clearData));
                Console.WriteLine("Encrypted data sent (HEX): {0}", ProtocolSI.ToHexString(encryptedData));

                // Receive answer from server
                Console.Write("waiting for ACK... ");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok.");
                #endregion
            } catch (Exception ex) {
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Exception: {0}", ex.ToString());
            } finally {
                if (tripleDES != null)
                {
                    tripleDES.Dispose();
                }
                // 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();
        }