Ejemplo n.º 1
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try {
                IPAddress ip   = IPAddress.Parse(txtIPAddress.Text);
                int       port = int.Parse(txtTCPPort.Text);

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

                aes          = new AesCryptoServiceProvider();
                symmetricsSI = new SymmetricsSI(aes);


                protocol = new ProtocolSI();

                serverEndPoint = new IPEndPoint(ip, port);

                client = new TcpClient();

                client.Connect(serverEndPoint);

                netStream = client.GetStream();
            } catch (Exception ex) {
                MessageBox.Show("ERROR: " + ex.Message);
                throw;
            }
        }
Ejemplo n.º 2
0
        private void Form1_Load(object sender, EventArgs e)
        {
            ProtocolSI protocolSI = new ProtocolSI(); //instanciar protocolo de comunicaçao

            //instaciar cript assimetrica
            string publickeystring = rsa.ToXmlString(false); //buscar chave publica

            byte[] publicKeyPacket = protocolSI.Make(ProtocolSICmdType.PUBLIC_KEY, publickeystring);
            networkStream.Write(publicKeyPacket, 0, publicKeyPacket.Length); //mandar chave publica para servidor

            while (protocolSI.GetCmdType() != ProtocolSICmdType.SECRET_KEY)  //receber chave simetrica e desencriptar
            {
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                byte[] simetrickeypacket = protocolSI.GetData();
                byte[] decryptedkey      = rsa.Decrypt(simetrickeypacket, true);
                aes.Key = decryptedkey;

                //comfirmar receçao
                byte[] keycomfirmreceived = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                networkStream.Write(keycomfirmreceived, 0, keycomfirmreceived.Length);
            }

            while (protocolSI.GetCmdType() != ProtocolSICmdType.IV) //receber IV e desencriptar
            {
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                byte[] IVpacket    = protocolSI.GetData();
                byte[] decryptedIV = rsa.Decrypt(IVpacket, true);
                aes.IV = decryptedIV;

                //comfirmarrececao
                byte[] IVcomfirmreceived = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                networkStream.Write(IVcomfirmreceived, 0, IVcomfirmreceived.Length);
            }
        }
Ejemplo n.º 3
0
        private void threadHandler()
        {
            // Definição das variáveis networkStream e protocolSI
            NetworkStream networkStream = this.client.GetStream();
            ProtocolSI    protocolSI    = new ProtocolSI();

            // Ciclo a ser executado até ao fim da transmissão.
            while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT)
            {
                int    bytesRead = networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                byte[] ack;

                // "Alteração"/mudança entre a apresentação da mensagem e o fim da tranmissão.
                switch (protocolSI.GetCmdType())
                {
                //Dica do ALT
                case ProtocolSICmdType.DATA:
                    Console.WriteLine(clientID + " : " + DateTime.Now.ToShortTimeString() + " " + protocolSI.GetStringFromData());
                    ack = protocolSI.Make(ProtocolSICmdType.ACK);
                    networkStream.Write(ack, 0, ack.Length);
                    break;

                case ProtocolSICmdType.EOT:
                    Console.WriteLine("Ending Thread from Client {0}", clientID);
                    ack = protocolSI.Make(ProtocolSICmdType.ACK);
                    networkStream.Write(ack, 0, ack.Length);
                    break;
                }
            }

            // Fecho do networkStream e do cliente (TcpClient)
            networkStream.Close();
            client.Close();
        }
Ejemplo n.º 4
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            ProtocolSI protocolSI = new ProtocolSI();

            byte[] endtrasmission = protocolSI.Make(ProtocolSICmdType.EOT);
            networkStream.Write(endtrasmission, 0, endtrasmission.Length);
        }
            private void threadHandler()
            {
                NetworkStream networkStream = this.client.GetStream();
                ProtocolSI    protocolSI    = new ProtocolSI();

                while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT)
                {
                    int bytesRead = networkStream.Read(protocolSI.Buffer, 0,
                                                       protocolSI.Buffer.Length);
                    byte[] ack;
                    switch (protocolSI.GetCmdType())
                    {
                    case ProtocolSICmdType.DATA:
                        Console.WriteLine("Client " + clientID + ":" + protocolSI.GetStringFromData());

                        ack = protocolSI.Make(ProtocolSICmdType.ACK);
                        networkStream.Write(ack, 0, ack.Length);
                        break;

                    case ProtocolSICmdType.EOT:
                        Console.WriteLine("Client {0} has disconnected", clientID);
                        ack = protocolSI.Make(ProtocolSICmdType.ACK);
                        networkStream.Write(ack, 0, ack.Length);
                        break;
                    }
                }
                networkStream.Close();
                client.Close();
            }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            TcpListener tcpl = null;
            TcpClient tcpc = null;
            NetworkStream stream = null;

            try
            {
                tcpl = new TcpListener(IPAddress.Any, 9999);
                tcpl.Start();
                Console.Write("Waiting for client... ");
                tcpc = tcpl.AcceptTcpClient();
                Console.WriteLine("ok");
                stream = tcpc.GetStream();

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

                do
                {
                    stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                    command = protocol.GetCmdType();

                    switch (protocol.GetCmdType())
                    {
                        case ProtocolSICmdType.NORMAL:
                            Console.WriteLine("inteiro: " + protocol.GetIntFromData().ToString());
                            break;
                        case ProtocolSICmdType.DATA:
                            Console.WriteLine("string: " + protocol.GetStringFromData());
                            break;
                        case ProtocolSICmdType.EOT:
                            Console.WriteLine("end");
                            break;
                        default:
                            Console.WriteLine("not expected");
                            break;
                    }

                } while (command != ProtocolSICmdType.EOT);

                packet = protocol.Make(ProtocolSICmdType.ACK);
                stream.Write(packet, 0, packet.Length);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                Console.WriteLine("disconnected");
                if (stream != null) stream.Dispose();
                if (tcpc != null) tcpc.Close();
                if (tcpl != null) tcpl.Stop();
            }
        }
Ejemplo n.º 7
0
        public FormCliente(NetworkStream ns, ProtocolSI psi, TcpClient tcp)
        {
            this.networkStream = ns;
            this.protocolSI    = psi;
            this.tcpClient     = tcp;

            InitializeComponent();
        }
Ejemplo n.º 8
0
        public Form1()
        {
            InitializeComponent();
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, Port);

            client = new TcpClient();
            client.Connect(endpoint);
            networkstream = client.GetStream();
            protocolSI    = new ProtocolSI();
        }
Ejemplo n.º 9
0
        public FormLogin()
        {
            InitializeComponent();

            IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, PORT); // Instancia o endPoint com a PORT

            tcpClient = new TcpClient();                                    // Instancia o cliente TCP
            tcpClient.Connect(endPoint);                                    // Conecta o cliente pelo EndPoint

            networkStream = tcpClient.GetStream();
            protocolSI    = new ProtocolSI();
        }
Ejemplo n.º 10
0
        private void Form1_Load(object sender, EventArgs e)
        {
            protocolSI = new ProtocolSI();

            try
            {
                aes       = new AesCryptoServiceProvider();
                rsa       = new RSACryptoServiceProvider();
                tcpClient = new TcpClient();
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, PORT);

                MessageBox.Show("Connecting...");

                tcpClient.Connect(endPoint);
                MessageBox.Show("Connected to Server");

                networkStream = tcpClient.GetStream();


                // DÁ A PUBLIC KEY DO SERVIDOR PARA VERIFICAR SE A LIGAÇÃO ESTÁ SEGURA

                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                if (protocolSI.GetCmdType() == ProtocolSICmdType.PUBLIC_KEY)
                {
                    rsa.FromXmlString(protocolSI.GetStringFromData());  //

                    byte[] secretKey = protocolSI.Make(ProtocolSICmdType.SECRET_KEY, rsa.Encrypt(aes.Key, true));
                    networkStream.Write(secretKey, 0, secretKey.Length);

                    //Receive ack
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    if (protocolSI.GetCmdType() != ProtocolSICmdType.ACK)
                    {
                        MessageBox.Show("Erro!");
                    }

                    secretKey = protocolSI.Make(ProtocolSICmdType.IV, rsa.Encrypt(aes.IV, true));
                    networkStream.Write(secretKey, 0, secretKey.Length);

                    //Receive ack
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    if (protocolSI.GetCmdType() != ProtocolSICmdType.ACK)
                    {
                        MessageBox.Show("Erro!");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            protocolSI = new ProtocolSI();
            TcpClient     tcpClient     = null;
            NetworkStream networkStream = null;

            try {
                Console.WriteLine("Starting client... ");
                tcpClient = new TcpClient();
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, PORT);

                Console.WriteLine("Start connection? Press any key.");
                Console.ReadKey();

                tcpClient.Connect(endPoint);

                Console.WriteLine("Connected to the Server.");
                networkStream = tcpClient.GetStream();

                #region Send String Message



                string msg     = "Hello from client!";
                byte[] msgByte = Encoding.UTF8.GetBytes(msg);
                byte[] packet  = protocolSI.Make(ProtocolSICmdType.DATA, msgByte);
                networkStream.Write(packet, 0, packet.Length);



                byte[] buffer    = new byte[2];
                int    bytesRead = networkStream.Read(buffer, 0, 2);
                Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, buffer.Length));

                #endregion
            } catch (Exception) {
                throw;
            } finally {
                if (networkStream != null)
                {
                    networkStream.Close();
                }
                if (tcpClient != null)
                {
                    tcpClient.Close();
                }
            }

            Console.WriteLine("Client");
            Console.ReadKey();
        }
        private void buttonEnviarFicheiro_Click(object sender, EventArgs e)
        {
            string     valor     = "3";
            IPEndPoint endPoint  = new IPEndPoint(IPAddress.Loopback, PORT);
            TcpClient  tcpClient = new TcpClient();

            tcpClient.Connect(endPoint);
            NetworkStream networkStream = tcpClient.GetStream();

            ProtocolSI protocolSI = new ProtocolSI();

            byte[] enviofuncao = protocolSI.Make(ProtocolSICmdType.DATA, "3");
            networkStream.Write(enviofuncao, 0, enviofuncao.Length);
            Thread.Sleep(1000);
        }
Ejemplo n.º 13
0
        public Chat(string username)
        {
            InitializeComponent();
            ApresentarAmigos();
            ApresentarMensagens();
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, PORT);

            client = new TcpClient();
            client.Connect(endpoint);
            networkStream = client.GetStream();
            protocolSI    = new ProtocolSI();
            SqlDataReader reader = LerBaseDados(username);
            //Obter Nickname
            string nick = (string)reader["Name"];

            labelNick.Text     = nick;
            labelUsername.Text = username;
        }
Ejemplo n.º 14
0
        private void buttonLogin_Click(object sender, EventArgs e)
        {
            ProtocolSI protocolSI = new ProtocolSI();

            if (textBoxPassword.Text == "" || textBoxUsername.Text == "")
            {
                MessageBox.Show("Introduza os Valores em falta!", "Erro",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                byte[] username = Encoding.UTF8.GetBytes(stringencrypter(textBoxUsername.Text));

                byte[] password = Encoding.UTF8.GetBytes(stringencrypter(textBoxPassword.Text));

                byte[] userpacket = protocolSI.Make(ProtocolSICmdType.USER_OPTION_2, username);
                networkStream.Write(userpacket, 0, userpacket.Length);

                byte[] passpacket = protocolSI.Make(ProtocolSICmdType.DATA, password);
                networkStream.Write(passpacket, 0, passpacket.Length);

                string comfirmationreceived = "idle";
                while (comfirmationreceived == "idle")
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    comfirmationreceived = protocolSI.GetStringFromData();
                }

                if (comfirmationreceived == "True")
                {
                    this.Close();

                    MessageBox.Show("Login was Successfull", "Login",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Login was not Successfull", "Login",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Ejemplo n.º 15
0
        public formCliente1(string nome)
        {
            InitializeComponent();

            //copia o valor enviado do form Login para a variavel globar User
            User = nome;

            //Criar conjunto IP+PORT do servidor
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, PORT);

            //Criar o cliente TCP
            client = new TcpClient();

            //Efetuar a ligação ao servidor
            client.Connect(endPoint);

            //Obter a ligação do servidor
            networkStream = client.GetStream();
            protocolSI    = new ProtocolSI();

            //Envia uma mensagem de avisoa a informar que o utilizador entrou
            MensagemDeEntrada();

            //carrega a conversa guardada no ficheiro txt
            carregarConversa();

            //Permite que de 1 em 1 segundos verifique se ouve alteração na conversa
            timer1.Start();

            //concatna ao nome do forme uma string a informar o nome do utilizador que inicioiu sessao
            this.Text = this.Text + " - Session of " + User;

            //limpa os valores da tbxConversa
            tbxConversa.Text = "";

            //posiciona a scrollbar no fundo
            tbxConversa.SelectionStart = tbxConversa.TextLength;
            tbxConversa.ScrollToCaret();
        }
Ejemplo n.º 16
0
        public Menu(TcpClient tcpClient, TcpListener tcpListener, NetworkStream networkStream, RSACryptoServiceProvider rsa2)
        {
            InitializeComponent();
            protocolSI         = new ProtocolSI();
            rsa                = rsa2;
            this.networkStream = networkStream;
            byte[] request = Encoding.UTF8.GetBytes("FileList");
            networkStream.Write(request, 0, request.Length);

            int bufferResponse = tcpClient.ReceiveBufferSize;
            int bytesRead      = 0;

            byte[] response = new byte[bufferResponse];
            bytesRead = networkStream.Read(response, 0, bufferResponse);

            ShowFiles(response, bytesRead);


            if (File.Exists(fileName))
            {
                Process.Start(fileName);
            }


            string[] filesCollection = Directory.GetFiles(pathFilesFolder);

            string files = "";

            byte[] bufferFiles;


            for (int i = 0; i < filesCollection.Count(); i++)
            {
                files += Path.GetFileName(filesCollection[i]);
                files += ";";
            }

            bufferFiles = Encoding.UTF8.GetBytes(files);
        }
Ejemplo n.º 17
0
        private void btnListaFicheiros_Click(object sender, EventArgs e)
        {
            ProtocolSI protocolSI = new ProtocolSI(); //instanciar protocolo de comunicaçao

            byte[] getfiles = protocolSI.Make(ProtocolSICmdType.USER_OPTION_3);
            networkStream.Write(getfiles, 0, getfiles.Length); //enviar pedido

            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            if (protocolSI.GetStringFromData() == "true")// comfirmar permissao de acesso
            {
                bool filesreceived = false;

                while (filesreceived == false)
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length); //receber lista

                    if (protocolSI.GetCmdType() == ProtocolSICmdType.DATA)
                    {
                        byte[] bytes     = bytedecrypter(protocolSI.GetData());
                        string ficheiros = Encoding.UTF8.GetString(bytes);

                        listBoxListaFicheiros.Items.Clear();

                        foreach (var item in ficheiros.Split('|'))
                        {
                            listBoxListaFicheiros.Items.Add(item);
                        }

                        filesreceived = true;
                    }
                }
            }
            else
            {
                MessageBox.Show("Acess not granted", "Send Files",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 18
0
        // Conecta o servidor
        public void ConnectToServer(string ip)
        {
            try
            {
                // Incia o TCP Cliente
                tcpClient = new TcpClient();

                // Conecta ao servidor
                tcpClient.Connect(ip, PORT);

                // Recebe a stream de dados
                networkStream = tcpClient.GetStream();

                // Cria protoclo SI
                protocolSI = new ProtocolSI();

                // Envia a chave publica para o servidor
                ExchangeKeys();
            }
            catch (Exception)
            {
                return;
            }
        }
Ejemplo n.º 19
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;

            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();
        }
Ejemplo n.º 20
0
        public Form1()
        {
            InitializeComponent();
            this.Width = 670;
            //Desabilita os botões que não possuem funcionalidade de imediato
            btConectar.Enabled      = false;
            btMensagem.Enabled      = false;
            btSair.Enabled          = false;
            tbMensagem.Enabled      = false;
            tbSala.Enabled          = false;
            btTrocarPosicao.Enabled = false;
            btVarJogadores.Enabled  = false;
            tbProxJogador.Enabled   = false;
            buttons = new List <Button>();
            buttons.Add(bt00); buttons.Add(bt01); buttons.Add(bt02);
            buttons.Add(bt10); buttons.Add(bt11); buttons.Add(bt12);
            buttons.Add(bt20); buttons.Add(bt21); buttons.Add(bt22);
            setButtons(false);
            //Inicializa o background que é responsável por ficar a escuta do servidor
            BackgroundWorker backgroundWorker1 = new BackgroundWorker();

            backgroundWorker1.DoWork             += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

            IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, PORT);

            tcpClient = new TcpClient();
            tcpClient.Connect(endPoint);
            //Obtem um fluxo para leitura e escrita.
            networkStream = tcpClient.GetStream();
            //Preparação da comunidade utilizando a classe desenvolvida pelo SI
            protocolSI = new ProtocolSI();

            //Cria a classe segura que contém as chaves públicas e privada
            protocolSecurity = new securityData();

            //Prepara o envio da chave pública
            byte[] pctPublicKey = protocolSI.Make(ProtocolSICmdType.PUBLIC_KEY, protocolSecurity.getChavePublica());

            //Envia a chave pública
            networkStream.Write(pctPublicKey, 0, pctPublicKey.Length);
            esperaACK();

            //Espera a chave simétrica
            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            while (protocolSI.GetCmdType() != ProtocolSICmdType.SYM_CIPHER_DATA)
            {
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            }
            enviaACK();
            protocolSecurity.setChaveSimetrica(protocolSI.GetStringFromData());

            //Espera o IV
            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            while (protocolSI.GetCmdType() != ProtocolSICmdType.IV)
            {
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            }
            enviaACK();
            protocolSecurity.setIV(protocolSI.GetStringFromData());
        }
Ejemplo n.º 21
0
        private void ThreadHandler()
        {
            networkStream = client.GetStream();

            protocolSI = new ProtocolSI();

            // Repete ate receber a mensagem de fim de transmissao
            while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT)
            {
                try
                {
                    // Recebe as mensagens do cliente
                    int bytesRead = networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Erro: " + ex);
                    return;
                }

                byte[] ack;

                // Verifica o tipo de mensagem
                switch (protocolSI.GetCmdType())
                {
                // Se for uma mensagem do chat
                case ProtocolSICmdType.DATA:
                {
                    byte[] msgBytes = null;

                    try
                    {
                        msgBytes = protocolSI.GetData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    string msgRecebida = Decifra(msgBytes);

                    string hash = msgRecebida.Substring(0, msgRecebida.IndexOf(" "));
                    msgRecebida = msgRecebida.Substring(msgRecebida.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(msgRecebida, hash))
                    {
                        string msg = user.Username + ": " + msgRecebida;
                        Console.WriteLine("    Cliente " + msg);

                        // Guarda os dados no ficheiro
                        FileHandler.SaveData(currentRoom.ToString(), msg);

                        try
                        {
                            // Envia o ACK para o cliente
                            ack = protocolSI.Make(ProtocolSICmdType.ACK);
                            networkStream.Write(ack, 0, ack.Length);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Erro: " + ex);
                            return;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                }
                break;

                // Se for para fechar a comunicacao
                case ProtocolSICmdType.EOT:
                {
                    try
                    {
                        // Envia o ACK para o cliente
                        ack = protocolSI.Make(ProtocolSICmdType.ACK);
                        networkStream.Write(ack, 0, ack.Length);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }
                } break;

                // Envia log do chat
                case ProtocolSICmdType.USER_OPTION_1:
                {
                    string log = FileHandler.LoadData(currentRoom.ToString());

                    // Variavel auxiliar
                    string stringChunk = "";

                    // Tamanho da resposta
                    int stringLenght = log.Length;

                    for (int i = 0; i < log.Length; i = i + CHUNKSIZE)
                    {
                        if (CHUNKSIZE > stringLenght)
                        {
                            stringChunk = log.Substring(i);
                        }
                        else
                        {
                            stringLenght = stringLenght - CHUNKSIZE;
                            stringChunk  = log.Substring(i, CHUNKSIZE);
                        }

                        // Cifra a mensagem
                        byte[] msgCifrada = Cifra(stringChunk);

                        Thread.Sleep(100);

                        Send(msgCifrada, ProtocolSICmdType.DATA);
                    }
                    Thread.Sleep(100);

                    try
                    {
                        // Envia EOF
                        byte[] eof = protocolSI.Make(ProtocolSICmdType.EOF);
                        networkStream.Write(eof, 0, eof.Length);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }
                } break;

                // Troca de chaves
                case ProtocolSICmdType.USER_OPTION_2:
                {
                    string pk = "";
                    try
                    {
                        // Recebe a chave publica do cliente
                        pk = protocolSI.GetStringFromData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    string hash = pk.Substring(0, pk.IndexOf(" "));
                    pk = pk.Substring(pk.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(pk, hash))
                    {
                        // Cria uma chave simétrica
                        aes = new AesCryptoServiceProvider();

                        // Guarda a chave simetrica
                        key = aes.Key;
                        iv  = aes.IV;

                        // Cria chave publica do cliente para poder encriptar
                        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                        rsa.FromXmlString(pk);

                        // Cria um array com as duas keys
                        byte[] keys = Encoding.UTF8.GetBytes(Convert.ToBase64String(key) + " " + Convert.ToBase64String(iv));

                        // Encripta a key e o iv
                        byte[] keyEnc = rsa.Encrypt(keys, true);

                        Send(keyEnc, ProtocolSICmdType.USER_OPTION_2);
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                } break;

                // Login
                case ProtocolSICmdType.USER_OPTION_3:
                {
                    // Recebe os dados do cliente
                    byte[] credenciaisBytes = protocolSI.GetData();

                    string credenciais = Decifra(credenciaisBytes);

                    string hash = credenciais.Substring(0, credenciais.IndexOf(" "));
                    credenciais = credenciais.Substring(credenciais.IndexOf(" ") + 1);
                    string username = credenciais.Substring(0, credenciais.IndexOf(" "));
                    string password = credenciais.Substring(credenciais.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(username + " " + password, hash))
                    {
                        // Verifica se o utilizador existe na base de dados
                        User utilizador = (from User in spksContainer.Users
                                           where User.Username.Equals(username)
                                           select User).FirstOrDefault();

                        int state;

                        // Utilizador nao existe ou nome de utilizador errado
                        if (utilizador == null)
                        {
                            state = 2;
                        }
                        // Password errada
                        else if (utilizador.Password != Common.HashPassword(password, utilizador.Salt))
                        {
                            state = 1;
                        }
                        // Utilizador existe e passowrd está certa
                        else
                        {
                            user  = utilizador;
                            state = 0;
                        }

                        byte[] msgCifrada = Cifra(state.ToString());

                        Send(msgCifrada, ProtocolSICmdType.USER_OPTION_3);
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                }
                break;

                // Cria conta
                case ProtocolSICmdType.USER_OPTION_4:
                {
                    byte[] credenciaisBytes;
                    try
                    {
                        // Recebe os dados do cliente
                        credenciaisBytes = protocolSI.GetData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    // Decifra e guarda as credenciais
                    string credenciais = Decifra(credenciaisBytes);

                    string hash = credenciais.Substring(0, credenciais.IndexOf(" "));
                    credenciais = credenciais.Substring(credenciais.IndexOf(" ") + 1);
                    string username = credenciais.Substring(0, credenciais.IndexOf(" "));
                    string password = credenciais.Substring(credenciais.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(username + " " + password, hash))
                    {
                        User newUser = new User(username, password);
                        spksContainer.Users.Add(newUser);
                        spksContainer.SaveChanges();

                        Console.WriteLine("Utilizador " + username + " criado");
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                }
                break;

                // Jogo
                case ProtocolSICmdType.USER_OPTION_5:
                {
                    byte[] msgBytes = null;

                    try
                    {
                        msgBytes = protocolSI.GetData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    // Decifra e guarda jogada
                    string jogada = Decifra(msgBytes);

                    string hash = jogada.Substring(0, jogada.IndexOf(" "));
                    jogada = jogada.Substring(jogada.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(jogada, hash))
                    {
                        Console.WriteLine("    Cliente " + user.Username + " jogou: " + jogada);

                        if (currentRoom.GetPlayer1Name() == user.Username)
                        {
                            currentRoom.Player1Play = jogada;
                        }
                        else
                        {
                            currentRoom.Player2Play = jogada;
                        }

                        try
                        {
                            // Envia o ACK para o cliente
                            ack = protocolSI.Make(ProtocolSICmdType.ACK);
                            networkStream.Write(ack, 0, ack.Length);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Erro: " + ex);
                            return;
                        }

                        while (true)
                        {
                            if (lastState != currentRoom.GameState)
                            {
                                string msg = currentRoom.Player1Pontos.ToString() + " " + currentRoom.Player2Pontos.ToString() + " " + currentRoom.GameState;
                                // BUG: Inserir breakpoint na linha de baixo para o jogo funcionar
                                Send(Cifra(msg), ProtocolSICmdType.USER_OPTION_5);
                                lastState = currentRoom.GameState;
                                break;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                } break;

                // Adiciona o jogador a sala
                case ProtocolSICmdType.USER_OPTION_6:
                {
                    byte[] msgBytes = null;

                    try
                    {
                        msgBytes = protocolSI.GetData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    // Decifra e guarda sala
                    string sala = Decifra(msgBytes);

                    string hash = sala.Substring(0, sala.IndexOf(" "));
                    sala = sala.Substring(sala.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(sala, hash))
                    {
                        // Verifica existem salas
                        if (Game.rooms.Count == 0)
                        {
                            CriaSala(sala);
                        }
                        else
                        {
                            try
                            {
                                foreach (Room room in Game.rooms)
                                {
                                    if (room.ToString() == sala)
                                    {
                                        JuntaSala(room);
                                    }
                                    else if (room == Game.rooms.Last() && room.ToString() == sala)
                                    {
                                        JuntaSala(room);
                                        break;
                                    }
                                    else if (room == Game.rooms.Last())
                                    {
                                        CriaSala(sala);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                }
                break;

                default:
                    break;
                }
            }

            // Fecha as conecoes
            networkStream.Close();
            client.Close();

            Console.WriteLine("O Cliente {0} desconnectou-se", clientId);
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            Console.WriteLine(" == SERVER == ");
            Console.Title = "SERVER";

            TcpListener   listener = null;
            TcpClient     client   = null;
            NetworkStream stream   = null;
            ProtocolSI    protocol = null;

            byte[] packet = null;

            int bytesRead;

            try {
                protocol = new ProtocolSI();

                listener = new TcpListener(IPAddress.Any, PORT);
                listener.Start();

                client = listener.AcceptTcpClient();
                stream = client.GetStream();

                ProtocolSICmdType cmd;

                do
                {
                    Console.WriteLine("Waiting for client..");
                    stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                    cmd = protocol.GetCmdType();

                    switch (cmd)
                    {
                    case ProtocolSICmdType.NORMAL:
                        Console.WriteLine($"Recebido: {protocol.GetIntFromData()}");
                        break;

                    case ProtocolSICmdType.DATA:
                        Console.WriteLine($"Recebido: {protocol.GetStringFromData()}");
                        break;

                    case ProtocolSICmdType.EOT:
                        Console.WriteLine("Recebido: EOT");
                        break;

                    default:
                        Console.WriteLine("Opção inválida.");
                        break;
                    }
                    packet = protocol.Make(ProtocolSICmdType.ACK);
                    // enviar o ACK
                    stream.Write(packet, 0, packet.Length);
                    Console.WriteLine("ack enviado");
                } while (cmd != ProtocolSICmdType.EOT);
                Console.WriteLine("Comunicação Terminada. <tecla para terminar>");
            } catch (Exception ex) {
                Console.WriteLine($"Error: {ex.Message}");
            } finally {
                if (client != null)
                {
                    client.Dispose();
                }
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (listener != null)
                {
                    listener.Stop();
                }
            }


            Console.ReadKey();
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            TcpListener tcpl = null;
            TcpClient tcpc = null;
            NetworkStream stream = null;
            TripleDESCryptoServiceProvider crypt3des = null;
            SymmetricsSI symmetrics = null;
            RSACryptoServiceProvider rsaClient = null;
            RSACryptoServiceProvider rsaServer = null;

            try
            {
                Console.WriteLine("SERVER\n");
                tcpl = new TcpListener(IPAddress.Any, 9999);
                tcpl.Start();
                tcpc = tcpl.AcceptTcpClient();
                stream = tcpc.GetStream();

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

                crypt3des = new TripleDESCryptoServiceProvider();
                symmetrics = new SymmetricsSI(crypt3des);
                rsaClient = new RSACryptoServiceProvider();
                rsaServer = new RSACryptoServiceProvider();
                string privateAndPublicKeyFilename = "serverpvpbkey.txt";
                if (File.Exists(privateAndPublicKeyFilename)) rsaServer.FromXmlString(File.ReadAllText(privateAndPublicKeyFilename));
                else File.WriteAllText(privateAndPublicKeyFilename, rsaServer.ToXmlString(true));

                Console.WriteLine("waiting for client public key");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                rsaClient.FromXmlString(protocol.GetStringFromData());
                Console.WriteLine("ok");
                Console.WriteLine("CLIENT PUBLIC KEY: " + rsaServer.ToXmlString(false));

                Console.WriteLine("sending for server public key");
                packet = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaServer.ToXmlString(false));
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");

                Console.WriteLine("sending for 3des key");
                packet = protocol.Make(ProtocolSICmdType.SECRET_KEY, rsaServer.Encrypt(crypt3des.Key, false));
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");

                Console.WriteLine("sending for 3des iv");
                packet = protocol.Make(ProtocolSICmdType.IV, rsaServer.Encrypt(crypt3des.IV, false));
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");

                Console.WriteLine("sending for 3des padding");
                packet = protocol.Make(ProtocolSICmdType.IV, rsaServer.Encrypt(BitConverter.GetBytes((int)crypt3des.Padding), false));
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");

                Console.WriteLine("sending for 3des mode");
                packet = protocol.Make(ProtocolSICmdType.MODE, rsaServer.Encrypt(BitConverter.GetBytes((int)crypt3des.Mode), false));
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                Console.WriteLine("disconnected");
                if (stream != null) stream.Dispose();
                if (tcpc != null) tcpc.Close();
                if (tcpl != null) tcpl.Stop();
            }
        }
Ejemplo n.º 24
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();
            }
        }
Ejemplo n.º 25
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
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            TcpClient tcpc = null;
            NetworkStream stream = 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;
                char key;
                var random = new Random();

                do
                {
                    Console.WriteLine();
                    Console.WriteLine("1 - Send Integer");
                    Console.WriteLine("2 - Send Date");
                    Console.WriteLine("0 - End Transmission");
                    key = Console.ReadKey().KeyChar;

                    switch (key)
                    {
                        case '1':
                            packet = protocol.Make(ProtocolSICmdType.NORMAL, random.Next());
                            break;
                        case '2':
                            packet = protocol.Make(ProtocolSICmdType.DATA, DateTime.Now.ToString());
                            break;
                        case '0':
                            packet = protocol.Make(ProtocolSICmdType.EOT);
                            break;
                        default:
                            Console.WriteLine();
                            Console.WriteLine("Invalid Key!!!");
                            continue;
                    }

                    stream.Write(packet, 0, packet.Length);

                } while (key != '0');

                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                Console.WriteLine("disconnected");
                if (stream != null) stream.Dispose();
                if (tcpc != null) tcpc.Close();
            }
        }
Ejemplo n.º 27
0
        //------------

        static void Main(string[] args)
        {
            byte[] requestClient            = null;
            byte[] requestClientBytes       = null;
            string requestClienteDecriptada = null;

            protocolSI = new ProtocolSI();

            //inicia o servidor e os vários serviços.
            ServerStart();
            ServerLogin();

            //o programa está sempre neste ciclo.
            while (true)
            {
                //verifica se está ligado
                if (tcpClient.Connected)
                {
                    //se estiver ligado vai ler da networkStream, um buffer, com o request, ou seja o que o cliente deseja fazer.
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    //obtêm a string dos dados do buffer do request lido anteriormente
                    requestClient = protocolSI.GetData();

                    requestClientBytes = servicoCriptografiaSimetrica.DecryptDados(requestClient);

                    requestClienteDecriptada = Encoding.UTF8.GetString(requestClientBytes);

                    //Enviar mensagem com o que o cliente deseja fazer.
                    //Serve APENAS para escrever na consola do server. !=networkstream.write();
                    Console.WriteLine("Client Request ->" + requestClienteDecriptada);

                    //vai verificar se o request é para obter lista de ficheiros
                    if (requestClienteDecriptada == "GETLIST")
                    {
                        //se sim, executa o procedimento ServerSendList();
                        ServerSendList();
                    }

                    else if (requestClienteDecriptada == "GETFILE")
                    {
                        //se for getfile;
                        byte[] requestFile      = null;
                        byte[] requestFileBytes = null;

                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                        //Recebe do cliente, um buffer com o request, ou seja, o ficheiro pedido pelo cliente.
                        requestFile = protocolSI.GetData();

                        requestFileBytes = servicoCriptografiaSimetrica.DecryptDados(requestFile);

                        string requestFileDecriptado = Encoding.UTF8.GetString(requestFileBytes);
                        //obtem uma string com o nome do ficheiro, através do buffer.

                        Console.WriteLine("Sending File '" + requestFileDecriptado + "' ...");
                        //Escreve na consola a dizer que está a enviar o ficheiro pedido.
                        //Envia o ficheiro.
                        ServerSendFile(requestFileDecriptado);
                    }
                    else if (requestClienteDecriptada == "SHUTDOWN")
                    {
                        Console.WriteLine("Shutting Down ...");
                        //caso o request seja para fechar
                        StopServer();
                        //quebra o ciclo infinito, parando todos os serviços ativos.
                        break;
                    }
                }

                else
                {
                    //se não estiver conectado pára o servidor.
                    StopServer();
                    break;
                }
            }
        }
Ejemplo n.º 28
0
        public Form_Autenticar()
        {
            InitializeComponent();

            //PARA A ENCRIPATAÇÃO
            aes = new AesCryptoServiceProvider();

            //PARA A HASH PARA VALIDAÇÃO DE DADOS (INTEGRIDADE)
            sha512 = SHA512.Create();

            //INICIA O CLIENTE TCP
            endpoint  = new IPEndPoint(IPAddress.Loopback, ipPort);
            tcpClient = new TcpClient();


            try
            {
                //LIGA-SE AO SERVIDOR
                tcpClient.Connect(endpoint);

                //OBTEM A STREAM DE COMUNICAÇÃO
                networkStream = tcpClient.GetStream();

                //INICIA O PROTOCOLO SI PARA TRATAR DAS MENSAGENS
                protocolSI = new ProtocolSI();

                //CRIAR AS CHAVES
                rSA = new RSACryptoServiceProvider();

                //GUARDAR AS CHAVES
                publickey = rSA.ToXmlString(false); //Chave Pública
                bothkeys  = rSA.ToXmlString(true);  // Chave Privada + Pública

                //1 - CONVERTER OS DADOS PARA BYTE[]
                byte[] chavePublica = Encoding.UTF8.GetBytes(publickey);

                //ENVIAR PARA O SERVIDOR

                if (EnviarChaveServidor(ProtocolSICmdType.USER_OPTION_1, chavePublica) == 1)
                {
                    int i;

                    for (i = 1; i <= 3; i++)
                    {
                        //esperar pela chave simetrica
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);

                        switch (protocolSI.GetCmdType())
                        {
                        case ProtocolSICmdType.SECRET_KEY:

                            //receber chave simetrica
                            aes.Key = rSA.Decrypt(protocolSI.GetData(), true);
                            Enviar_ACK();
                            break;

                        case ProtocolSICmdType.IV:

                            //receber vetor da chave simetrica
                            aes.IV = rSA.Decrypt(protocolSI.GetData(), true);
                            Enviar_ACK();
                            break;

                        case ProtocolSICmdType.SYM_CIPHER_DATA:

                            // receber a publica do servidor cifrada
                            byte[] chavePublicaServidorEncriptada = protocolSI.GetData();

                            //decifrar chave publica
                            chavePublicaServidor = emString(decifrarComChaveSimetrica(chavePublicaServidorEncriptada));

                            Enviar_ACK();

                            break;

                        case ProtocolSICmdType.NACK:
                            MessageBox.Show("Ocorreu um erro. Por favor reinicie a aplicação! ");
                            break;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Não foi possivel conectar ao servidor. Tente outra vez! ");
                    return;
                }
            }
            catch (SocketException)
            {
                MessageBox.Show("Não foi possivel conectar ao servidor. Tente outra vez! ");
                return;
            }
        }
Ejemplo n.º 29
0
            public void threadHandler1()
            {
                ProtocolSI    protocolSI    = new ProtocolSI();
                NetworkStream networkStream = this.tcpClient.GetStream();

                while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT)
                {
                    byte[] ack = protocolSI.Make(ProtocolSICmdType.ACK); // Guarda uma mensagem tipo ACK(Acknowlodge) no array de bytes

                    try
                    {
                        int bytesRead = networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length); // Guarda o numero de bytes lidos

                        switch (protocolSI.GetCmdType())
                        {
                        case ProtocolSICmdType.DATA:
                            byte[] packetData;
                            string userMsg  = protocolSI.GetStringFromData();
                            string response = "";

                            Console.WriteLine($"Client {clientID}: " + userMsg);

                            if (userMsg.StartsWith("!"))
                            {
                                userMsg = userMsg.ToLower();

                                switch (userMsg)
                                {
                                case "!horas":
                                    response = DateTime.Now.ToString("HH:mm");
                                    break;

                                case "!data":
                                    response = DateTime.Now.ToString("dd/MM/yyyy");
                                    break;

                                case "!piada":
                                    response = "\nComo se chama a neta do Super Mario?\nMarioneta";
                                    break;

                                default:
                                    response = "Comando Invalido";
                                    break;
                                }

                                packetData = protocolSI.Make(ProtocolSICmdType.DATA, response);
                                networkStream.Write(packetData, 0, packetData.Length);
                            }
                            break;

                        case ProtocolSICmdType.PUBLIC_KEY:
                            break;

                        case ProtocolSICmdType.SECRET_KEY:
                            break;

                        case ProtocolSICmdType.USER_OPTION_1:     // USERNAME
                            username = protocolSI.GetStringFromData();
                            break;

                        case ProtocolSICmdType.USER_OPTION_2:     // PASSWORD e Registo
                            byte[] packetRegister;

                            try
                            {
                                pass = protocolSI.GetData();

                                salt = GenerateSalt(SALTSIZE);

                                saltedHash = GenerateSaltedHash(pass, salt);

                                Console.WriteLine("\nA Fazer Registo ...");

                                Register(username, saltedHash, salt);

                                packetRegister = protocolSI.Make(ProtocolSICmdType.DATA, "Sucesso!");
                                Console.WriteLine("Regiso com Sucesso");
                            }
                            catch (Exception)
                            {
                                packetRegister = protocolSI.Make(ProtocolSICmdType.DATA, "Erro no Registo!");
                                Console.WriteLine("Erro no Registo");
                            }

                            networkStream.Write(packetRegister, 0, packetRegister.Length);
                            break;

                        case ProtocolSICmdType.USER_OPTION_3:     // PASSWORD e Login
                            byte[] packetLogin;

                            try
                            {
                                Console.WriteLine("\nA Fazer Login ...");

                                if (VerifyLogin(username, protocolSI.GetStringFromData()))
                                {
                                    packetLogin = protocolSI.Make(ProtocolSICmdType.DATA, "Sucesso!");
                                    Console.WriteLine("Login com Sucesso");
                                }
                                else
                                {
                                    packetLogin = protocolSI.Make(ProtocolSICmdType.DATA, "Login Incorreto!");
                                    Console.WriteLine("Login Incorreto");
                                }
                            }
                            catch (Exception)
                            {
                                packetLogin = protocolSI.Make(ProtocolSICmdType.DATA, $"Erro no Login!");
                            }

                            networkStream.Write(packetLogin, 0, packetLogin.Length);
                            break;

                        case ProtocolSICmdType.EOT:
                            Console.WriteLine($"Client {clientID} has disconnected");
                            break;
                        }

                        networkStream.Write(ack, 0, ack.Length); // Insere o ack na Stream
                    }
                    catch (Exception err)
                    {
                        Console.WriteLine($"Cliente {clientID} perdeu a ligação ao servidor!\n*Erro - {err.Message}");
                    }
                }

                networkStream.Close(); // Fecha o servico da Stream
                tcpClient.Close();     // Encerra o cliente TCP
            }
Ejemplo n.º 30
0
        //----------------obter nomes dos ficheiros numa pasta---------------------
        //static string pathFilesFolder = Path.Combine(Environment.CurrentDirectory, @"Files\");
        //string[] filesCollection = Directory.GetFiles(pathFilesFolder);

        //  public static object ProtocolSICmdType { get; private set; }

        static void Main(string[] args)
        {
            aes        = new AesCryptoServiceProvider();
            protocolSI = new ProtocolSI();
            TcpListener tcpListener = null;
            TcpClient   tcpClient   = null;

            //NetworkStream networkStream = null;
            GenerateKeys();

            //try
            // {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, PORT);

            tcpListener = new TcpListener(endPoint);

            tcpListener.Start();

            tcpClient = tcpListener.AcceptTcpClient();

            networkStream = tcpClient.GetStream();


            //RECEBE A PUBLIC KEY DO CLIENTE
            byte[] packet = protocolSI.Make(ProtocolSICmdType.PUBLIC_KEY, chavePublica);
            networkStream.Write(packet, 0, packet.Length);

            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            if (protocolSI.GetCmdType() == ProtocolSICmdType.SECRET_KEY)
            {
                aes.Key = rsa.Decrypt(protocolSI.GetData(), true);
            }

            //send ack
            packet = protocolSI.Make(ProtocolSICmdType.ACK);
            networkStream.Write(packet, 0, packet.Length);


            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            if (protocolSI.GetCmdType() == ProtocolSICmdType.IV)
            {
                aes.IV = rsa.Decrypt(protocolSI.GetData(), true);
            }

            //send ack
            packet = protocolSI.Make(ProtocolSICmdType.ACK);
            networkStream.Write(packet, 0, packet.Length);


            //Autenticação
            //byte[] login = protocolSI.Make(ProtocolSICmdType.USER_OPTION_5, //encrypt_symmetric("USERNAME"));
            //networkStream.Write(login, 0 ,login.Length);

            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            login_decrypted = decrypt_symmetric(protocolSI.GetData());
            user            = Encoding.UTF8.GetString(login_decrypted);

            //send ACK
            packet = protocolSI.Make(ProtocolSICmdType.ACK);
            networkStream.Write(packet, 0, packet.Length);

            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            login_decrypted = decrypt_symmetric(protocolSI.GetData());
            pass            = Encoding.UTF8.GetString(login_decrypted);

            //send ACK
            packet = protocolSI.Make(ProtocolSICmdType.ACK);
            networkStream.Write(packet, 0, packet.Length);

            string login_bool = "";

            if (VerifyLogin(user, pass))
            {
                login_bool = "True";
            }
            else
            {
                login_bool = "False";
            }

            packet = protocolSI.Make(ProtocolSICmdType.DATA, login_bool);
            networkStream.Write(packet, 0, packet.Length);


            int bytesRead = 0;


            //############################

            int requestListSize;

            byte[] bufferRequestList;

            requestListSize   = tcpClient.ReceiveBufferSize;
            bufferRequestList = new byte[requestListSize];

            networkStream.Read(bufferRequestList, 0, requestListSize);

            byte[] fileList = GetFiles();
            networkStream.Write(fileList, 0, fileList.Length);



            //*********************************

            /*
             * networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
             * if (protocolSI.GetCmdType() == ProtocolSICmdType.USER_OPTION_1)
             * {
             *  Console.WriteLine(protocolSI.GetStringFromData());
             *
             * }*/

            //*********************************

            //############################

            //-------------
            bool status = true;

            do
            {
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);

                if (protocolSI.GetStringFromData() == "file")
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    string file = protocolSI.GetStringFromData();
                    sendFile(file);
                }
                else if (protocolSI.GetStringFromData() == "shutdown")
                {
                    status = false;
                }
            } while (status);



            if (networkStream != null)
            {
                networkStream.Close();
            }

            if (tcpClient != null)
            {
                tcpClient.Close();
            }

            if (tcpListener != null)
            {
                tcpListener.Stop();
            }



            //------------------------


            //Enviar ack

            /*Byte[] ack = Encoding.UTF8.GetBytes("OK");
             * networkStream.Write(ack, 0, ack.Length);*/


            //}
        }
Ejemplo n.º 31
0
        private void buttonNewUser_Click(object sender, EventArgs e)
        {
            ProtocolSI protocolSI = new ProtocolSI();

            if (textBoxComPassword.Text == "" || textBoxPassword.Text == "" || textBoxUsername.Text == "")
            {
                MessageBox.Show("Introduza os Valores em falta!", "Erro",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (textBoxPassword.Text != textBoxComPassword.Text)
            {
                MessageBox.Show("As passwords são diferentes!", "Erro",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                byte[] username = Encoding.UTF8.GetBytes(stringencrypter(textBoxUsername.Text));

                byte[] saltpreencrypt = GenerateSalt(8);
                byte[] saltposencrypt = byteencrypter(saltpreencrypt);

                byte[] password = Encoding.UTF8.GetBytes(textBoxPassword.Text);

                byte[] saltyPassword = byteencrypter(GenerateSaltedHash(password, saltpreencrypt));

                //start
                byte[] usernamepacket = protocolSI.Make(ProtocolSICmdType.USER_OPTION_1, username);
                networkStream.Write(usernamepacket, 0, usernamepacket.Length);

                byte[] passpacket = protocolSI.Make(ProtocolSICmdType.DATA, saltyPassword);
                networkStream.Write(passpacket, 0, passpacket.Length);

                string comfirmationreceived = "idle";
                while (comfirmationreceived == "idle")
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    comfirmationreceived = protocolSI.GetStringFromData();
                }

                byte[] saltpacket = protocolSI.Make(ProtocolSICmdType.ACK, saltposencrypt);
                networkStream.Write(saltpacket, 0, saltpacket.Length);

                comfirmationreceived = "idle";
                while (comfirmationreceived == "idle")
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    comfirmationreceived = protocolSI.GetStringFromData();
                }

                if (comfirmationreceived == "true")
                {
                    this.Close();

                    MessageBox.Show("Register was Successfull", "Register",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Register was not Successfull", "Register",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            Console.WriteLine("CLIENT\n");
            TcpClient tcpc = null;
            NetworkStream stream = null;
            TripleDESCryptoServiceProvider crypt3des = null;
            SymmetricsSI symmetrics = null;
            RSACryptoServiceProvider rsaClient = null;
            RSACryptoServiceProvider rsaServer = null;

            try
            {
                tcpc = new TcpClient();
                tcpc.Connect("", 9999);
                stream = tcpc.GetStream();

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

                crypt3des = new TripleDESCryptoServiceProvider();
                symmetrics = new SymmetricsSI(crypt3des);
                rsaClient = new RSACryptoServiceProvider();
                string privateAndPublicKeyFilename = "clientpvpbkey.txt";
                rsaServer = new RSACryptoServiceProvider();
                if (File.Exists(privateAndPublicKeyFilename)) rsaClient.FromXmlString(File.ReadAllText(privateAndPublicKeyFilename));
                else File.WriteAllText(privateAndPublicKeyFilename, rsaClient.ToXmlString(true));

                var ack = protocol.Make(ProtocolSICmdType.ACK);

                // Send key
                Console.WriteLine("sending for client public key");
                packet = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaClient.ToXmlString(false));
                stream.Write(packet, 0, packet.Length);
                Console.WriteLine("ok");

                Console.WriteLine("waiting for server public key");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                rsaServer.FromXmlString(protocol.GetStringFromData());
                Console.WriteLine("ok");
                Console.WriteLine("SERVER PUBLIC KEY: " + rsaServer.ToXmlString(false));

                Console.WriteLine("waiting for 3des key");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                crypt3des.Key = rsaServer.Decrypt(protocol.GetData(), false);
                Console.WriteLine("ok");
                Console.WriteLine("3DES KEY: " + crypt3des.Key.ToString());

                Console.WriteLine("waiting for 3des iv");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                crypt3des.IV = rsaServer.Decrypt(protocol.GetData(), false);
                Console.WriteLine("ok");
                Console.WriteLine("3DES IV: " + crypt3des.IV.ToString());

                Console.WriteLine("waiting for 3des padding");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                crypt3des.Padding = (PaddingMode)BitConverter.ToInt32(rsaServer.Decrypt(protocol.GetData(), false), 0);
                Console.WriteLine("ok");
                Console.WriteLine("3DES PADDING: " + crypt3des.Padding.ToString());

                Console.WriteLine("waiting for 3des mode");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                crypt3des.Mode = (CipherMode)BitConverter.ToInt32(rsaServer.Decrypt(protocol.GetData(), false), 0);
                Console.WriteLine("ok");
                Console.WriteLine("3DES MODE: " + crypt3des.Mode.ToString());

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                Console.WriteLine("disconnected");
                if (stream != null) stream.Dispose();
                if (tcpc != null) tcpc.Close();
                if (crypt3des != null) crypt3des.Dispose();
                if (symmetrics != null) crypt3des.Dispose();
                if (rsaClient != null) rsaClient.Dispose();
                if (rsaServer != null) rsaServer.Dispose();
            }
        }
Ejemplo n.º 33
0
        private void registothreadHandler()
        {
            ProtocolSI    protocolSI    = new ProtocolSI(); //instanciar protocolo comunicacao
            NetworkStream networkStream = client.GetStream();

            rsa = new RSACryptoServiceProvider();                          //instanciar metodo cryptografico assimetrico

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); //instanciar metodo cryptografico simetrico

            secretkey = aes.Key;
            IV        = aes.IV;

            Console.WriteLine("Recebida uma Nova Ligacao");

            LogReg logReg = new LogReg();

            bool IsClientLoggedIn = false;

            while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT)
            {
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);

                //registar
                if (protocolSI.GetCmdType() == ProtocolSICmdType.USER_OPTION_1)
                {
                    string usernamepacket = null;

                    byte[] salt      = null;
                    byte[] saltypass = null;

                    usernamepacket = stringdecrypter(protocolSI.GetStringFromData());

                    Console.WriteLine("Attempt to create a new client: " + usernamepacket);

                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    if (protocolSI.GetCmdType() == ProtocolSICmdType.DATA)
                    {
                        saltypass = bytedecrypter(protocolSI.GetData());

                        byte[] comfirmpass = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                        networkStream.Write(comfirmpass, 0, comfirmpass.Length);
                    }

                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    if (protocolSI.GetCmdType() == ProtocolSICmdType.ACK)
                    {
                        salt = bytedecrypter(protocolSI.GetData());

                        byte[] comfirmsalt = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                        networkStream.Write(comfirmsalt, 0, comfirmsalt.Length);
                    }

                    logReg.Register(usernamepacket, saltypass, salt);
                }

                //login
                if (protocolSI.GetCmdType() == ProtocolSICmdType.USER_OPTION_2)
                {
                    string usernamestring = null;
                    string pass           = null;

                    usernamestring = stringdecrypter(protocolSI.GetStringFromData());

                    Console.WriteLine("Tentativa de login de: " + usernamestring);

                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    if (protocolSI.GetCmdType() == ProtocolSICmdType.DATA)
                    {
                        pass = stringdecrypter(protocolSI.GetStringFromData());
                    }

                    IsClientLoggedIn = logReg.VerifyLogin(usernamestring, pass);

                    byte[] comfirmlogin = protocolSI.Make(ProtocolSICmdType.DATA, IsClientLoggedIn.ToString());
                    networkStream.Write(comfirmlogin, 0, comfirmlogin.Length);
                }

                //listaficheiros
                if (protocolSI.GetCmdType() == ProtocolSICmdType.USER_OPTION_3)
                {
                    Console.WriteLine("Pedido de envio de lista de ficheiros recebidos");

                    if (IsClientLoggedIn)
                    {
                        byte[] grantaccess = protocolSI.Make(ProtocolSICmdType.USER_OPTION_9, "true");
                        networkStream.Write(grantaccess, 0, grantaccess.Length);

                        Console.WriteLine("Pedido aceite, a enviar lista");

                        DirectoryInfo
                            dinfo = new DirectoryInfo(
                            @"C:\Users\joaod\Desktop\ProjectoTopSeg\Recursos"); //diretorio com imagens
                        FileInfo[] Files = dinfo.GetFiles(".");                 // get all the files in the directory to the array
                        string     files = "";
                        foreach (FileInfo file in Files)                        //guardar nomes dos ficheiros numa string
                        {
                            files = files + file.Name + "|";
                        }

                        byte[] encriptedfiles = byteencrypter(Encoding.UTF8.GetBytes(files)); //encriptar string
                        byte[] filespacket    = protocolSI.Make(ProtocolSICmdType.DATA, encriptedfiles);
                        networkStream.Write(filespacket, 0, filespacket.Length);              //enviar packet
                    }
                    else
                    {
                        Console.WriteLine("Pedido negado");
                        byte[] grantaccess = protocolSI.Make(ProtocolSICmdType.USER_OPTION_9, "false");
                        networkStream.Write(grantaccess, 0, grantaccess.Length);
                    }
                }

                // receber chave publica do cliente
                if (protocolSI.GetCmdType() == ProtocolSICmdType.PUBLIC_KEY)
                {
                    string Publickeypacket = protocolSI.GetStringFromData(); //recebe pacote de dados com chave publica cliente
                    rsa.FromXmlString(Publickeypacket);                      //importa chave publica

                    //Buscar key e IV
                    byte[] key = aes.Key;
                    byte[] IV  = aes.IV;

                    //encriptar chave simetrica
                    byte[] encryptedkey = rsa.Encrypt(key, true);

                    //enviar chave simetrica
                    byte[] encryptedkeypacket = protocolSI.Make(ProtocolSICmdType.SECRET_KEY, encryptedkey);
                    networkStream.Write(encryptedkeypacket, 0, encryptedkeypacket.Length);

                    //aguardar pela resposta
                    string comfirmationreceivedkey = "idle";
                    while (comfirmationreceivedkey == "idle")
                    {
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                        comfirmationreceivedkey = protocolSI.GetStringFromData();
                    }

                    //encriptar chave simetrica
                    byte[] encrypedIV = rsa.Encrypt(IV, true);

                    //enviar IV
                    byte[] IVpacket = protocolSI.Make(ProtocolSICmdType.IV, encrypedIV);
                    networkStream.Write(IVpacket, 0, IVpacket.Length);

                    //aguardar pela resposta
                    string comfirmationreceivedIV = "idle";
                    while (comfirmationreceivedIV == "idle")
                    {
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                        comfirmationreceivedIV = protocolSI.GetStringFromData();
                    }

                    if (comfirmationreceivedIV == "true" && comfirmationreceivedkey == "true")
                    {
                        Console.WriteLine("Parametros de comunicaçao recebidos pelo utilizador");
                    }
                }

                //receber ficheiros
                if (protocolSI.GetCmdType() == ProtocolSICmdType.USER_OPTION_4)
                {
                    Console.WriteLine("Pedido de envio de ficheiros recebido");

                    if (IsClientLoggedIn)
                    {
                        byte[] grantaccess = protocolSI.Make(ProtocolSICmdType.USER_OPTION_9, "true");
                        networkStream.Write(grantaccess, 0, grantaccess.Length);

                        Console.WriteLine("Pedido de envio de ficheiros concebido");

                        int    bytesread = 0;
                        byte[] signature = null;
                        byte[] datahash  = null;

                        String copyFilePath = "C:\\Users\\joaod\\Desktop\\ProjectoTopSeg\\Recursos\\copyedfile";

                        if (File.Exists(copyFilePath)) //verificar se o ficheiro ja existe
                        {
                            File.Delete(copyFilePath); //se sim eliminar
                        }

                        int    tamanhoficheiro = protocolSI.GetIntFromData();
                        byte[] segment         = new byte[tamanhoficheiro];

                        Console.WriteLine("A receber ficheiro de um cliente");

                        FileStream copyFileStream = new FileStream(copyFilePath, FileMode.Create);//instanciar controlador de leitura Stream

                        bool signaturereceived = false;
                        bool hashreceived      = false;

                        while (signaturereceived == false || hashreceived == false)
                        {
                            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                            if (protocolSI.GetCmdType() == ProtocolSICmdType.DIGITAL_SIGNATURE) // nao envia assinatura
                            {
                                signature = bytedecrypter(protocolSI.GetData());
                                byte[] bytescomfPacket = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                                networkStream.Write(bytescomfPacket, 0, bytescomfPacket.Length);//mandar resposta ao cliente
                                signaturereceived = true;
                            }

                            if (protocolSI.GetCmdType() == ProtocolSICmdType.ASSYM_CIPHER_DATA)
                            {
                                datahash = bytedecrypter(protocolSI.GetData());
                                byte[] bytescomfPacket = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                                networkStream.Write(bytescomfPacket, 0, bytescomfPacket.Length);//mandar resposta ao cliente
                                hashreceived = true;
                            }
                        }

                        //receber pacotes com o ficheiro segmentado
                        while (protocolSI.GetCmdType() != ProtocolSICmdType.EOF)
                        {
                            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);

                            if (protocolSI.GetCmdType() == ProtocolSICmdType.PADDING)
                            {
                                bytesread = Int32.Parse(stringdecrypter(protocolSI.GetStringFromData()));

                                byte[] bytescomfPacket = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                                networkStream.Write(bytescomfPacket, 0, bytescomfPacket.Length);//mandar resposta ao cliente
                            }

                            if (protocolSI.GetCmdType() == ProtocolSICmdType.DATA)
                            {
                                segment = bytedecrypter(protocolSI.GetData());
                                copyFileStream.Write(segment, 0, bytesread); // receber ficheiro

                                byte[] bytescomfPacket = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                                networkStream.Write(bytescomfPacket, 0, bytescomfPacket.Length);//mandar resposta ao cliente

                                Console.WriteLine("A receber Dados: " + segment.Length + "b");
                            }
                        }

                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                        string ext = stringdecrypter(protocolSI.GetStringFromData());

                        byte[] segcomfPacket = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                        networkStream.Write(segcomfPacket, 0, segcomfPacket.Length);//mandar resposta ao cliente
                        Console.WriteLine("Transferencia de ficheiro terminada");
                        copyFileStream.Close();

                        bool integritystatus = verifyintegrity(datahash, File.ReadAllBytes(copyFilePath), signature);

                        string integritycheck = string.Empty;
                        if (integritystatus)
                        {
                            integritycheck = "Ficheiro dentro dos parametros de integridade";
                        }
                        else
                        {
                            integritycheck = "Ficheiro com risco de ter sido modificado";
                        }
                        Console.WriteLine("Integrity Check: " + integritycheck);

                        Random rnd         = new Random(DateTime.Now.Millisecond);
                        int    newfilename = rnd.Next(0, 3000);                                                                          // gere um novo nome para o ficheiro

                        File.Move(copyFilePath, "C:\\Users\\joaod\\Desktop\\ProjectoTopSeg\\Recursos\\" + newfilename.ToString() + ext); //substitui ficheiros
                    }
                    else
                    {
                        Console.WriteLine("Pedido de envio de ficheiros negado");

                        byte[] grantaccess = protocolSI.Make(ProtocolSICmdType.USER_OPTION_9, "false");
                        networkStream.Write(grantaccess, 0, grantaccess.Length);
                    }
                }
            }
            Console.WriteLine("Ligaçao terminada");
        }
Ejemplo n.º 34
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();
        }
        private void buttonlogin_Click(object sender, EventArgs e)
        {
            string     valor = "2";
            string     confirm;
            IPEndPoint endPoint  = new IPEndPoint(IPAddress.Loopback, PORT);
            TcpClient  tcpClient = new TcpClient();

            tcpClient.Connect(endPoint);
            NetworkStream networkStream = tcpClient.GetStream();

            ProtocolSI protocolSI = new ProtocolSI();

            byte[] enviofuncao = protocolSI.Make(ProtocolSICmdType.DATA, "2");
            networkStream.Write(enviofuncao, 0, enviofuncao.Length);
            Thread.Sleep(1000);

            byte[] username = protocolSI.Make(ProtocolSICmdType.DATA, textBoxUsername.Text);
            networkStream.Write(username, 0, username.Length);
            Thread.Sleep(1000);

            byte[] password = protocolSI.Make(ProtocolSICmdType.DATA, TextBoxPassword.Text);
            networkStream.Write(password, 0, password.Length);



            buttonEnviarFicheiro.Enabled = true;
            networkStream.Close();
        }