コード例 #1
0
        private void Enviar_Click(object sender, EventArgs e)
        {
            string msg = "";

            byte[] userData = protocolSI.Make(ProtocolSICmdType.DATA, textBoxMensagem.Text);

            networkStream.Write(userData, 0, userData.Length);

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

                if (protocolSI.GetCmdType() == ProtocolSICmdType.ACK)
                {
                    break;
                }
                else if (protocolSI.GetCmdType() == ProtocolSICmdType.DATA)
                {
                    msg = msg + protocolSI.GetStringFromData();
                }
            }

            listBoxChat.Items.Insert(0, $"Cliente: {textBoxMensagem.Text}");
            textBoxMensagem.Clear();
            textBoxMensagem.Enabled = true;

            if (!String.IsNullOrWhiteSpace(msg))
            {
                listBoxChat.Items.Insert(0, $"Server: {msg}");
            }
        }
コード例 #2
0
            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();
            }
コード例 #3
0
ファイル: Server.cs プロジェクト: jodufra/aulas_si
        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();
            }
        }
コード例 #4
0
        private void tbLogin_Click(object sender, EventArgs e)
        {
            //Prepara o envio dos dados de login
            string login = tbUsuario.Text;
            string senha = tbSenha.Text;

            byte[] pctLogin = protocolSI.Make(ProtocolSICmdType.USER_OPTION_1, protocolSecurity.cifrarMensagem(login));
            byte[] pctSenha = protocolSI.Make(ProtocolSICmdType.SECRET_KEY, protocolSecurity.cifrarMensagem(senha));

            //Envia o login
            networkStream.Write(pctLogin, 0, pctLogin.Length);
            esperaACK();

            //Envia a senha
            networkStream.Write(pctSenha, 0, pctSenha.Length);
            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            while (protocolSI.GetCmdType() != ProtocolSICmdType.ACK)
            {
                if (protocolSI.GetCmdType() == ProtocolSICmdType.USER_OPTION_3)
                {
                    MessageBox.Show("Senha incorreta!");
                    enviaACK();
                    return;
                }
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            }
            lastMsg = protocolSecurity.decifrarMensagem(protocolSI.GetStringFromData());
            string[] msg = lastMsg.Split('/');;
            tbJogadores.Text = msg[0];
            tbPontos.Text    = msg[1];

            btConectar.Enabled = true;
            tbSala.Enabled     = true;
            btSair.Enabled     = true;

            tbUsuario.Enabled = false;
            tbSenha.Enabled   = false;
            btEntrar.Enabled  = false;
            enviaACK();
        }
コード例 #5
0
ファイル: Login.cs プロジェクト: simaopina/Projeto-TS
        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;
            }
        }
コード例 #6
0
        private void btnExchangeAssymmetricKeys_Click(object sender, EventArgs e)
        {
            try {
                // enviar a chave publica
                var msg = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaClient.ToXmlString(false));
                netStream.Write(msg, 0, msg.Length);

                // receber a chave publica do servidor
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                rsaServer.FromXmlString(protocol.GetStringFromData());

                lblExchangeAssymetricKeys.Visible = true;
            } catch (Exception ex) {
                MessageBox.Show("ERROR: " + ex.Message);
                throw;
            }
        }
コード例 #7
0
ファイル: Login.cs プロジェクト: JoaodssPSI/TopSeg
        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);
                }
            }
        }
コード例 #8
0
ファイル: Login.cs プロジェクト: simaopina/Projeto-TS
        private void btnLogin_Click(object sender, EventArgs e)
        {
            byte[] login = protocolSI.Make(ProtocolSICmdType.USER_OPTION_5, encrypt_symmetric(Encoding.UTF8.GetBytes(txtUsername.Text)));
            networkStream.Write(login, 0, login.Length);

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



            login = protocolSI.Make(ProtocolSICmdType.USER_OPTION_5, encrypt_symmetric(Encoding.UTF8.GetBytes(txtPassword.Text)));
            networkStream.Write(login, 0, login.Length);

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


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


            if (resposta == "True")
            {
                this.BeginInvoke((Action) delegate
                {
                    NovoMenu();
                });
            }
            else
            {
                MessageBox.Show("Invalid User");
            }
        }
コード例 #9
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);
            }
        }
コード例 #10
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();
        }
コード例 #11
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();
        }
コード例 #12
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);
        }
コード例 #13
0
        private void btnSendFiles_Click(object sender, EventArgs e)
        {
            ProtocolSI protocolSI = new ProtocolSI(); //instanciar protocolo de comunicaçao

            //verificar login
            // Selecionar imagem para enviar
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Title = "Select a File";

            string originalfilepath = string.Empty;

            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                originalfilepath = openFileDialog1.FileName;
            }
            else
            {
                return; //mensagem de erro/ ficheiro nao suportado
            }

            string ext = stringencrypter(Path.GetExtension(openFileDialog1.FileName));

            //definir variaveis
            int bufferSize = 100;

            byte[] buffer = new byte[bufferSize];

            int bytesRead = 0;

            //estabelecer ligacao aqui, enviar pedido de acesso, se autorizado o server recebe o tamanho do ficheiro nesta packet
            byte[] bufferSizePacket = protocolSI.Make(ProtocolSICmdType.USER_OPTION_4, bufferSize);
            networkStream.Write(bufferSizePacket, 0, bufferSizePacket.Length);

            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            if (protocolSI.GetStringFromData() == "true")
            {
                //receber resposta aqui
                byte[]     file = File.ReadAllBytes(originalfilepath);
                FileStream originalFileStream = new FileStream(originalfilepath, FileMode.Open); //instanciar controlador de escrita Stream

                //meter aqui progress bar para ficar bem bonito
                progressBar1.Minimum = 0;
                progressBar1.Maximum = (int)originalFileStream.Length;
                progressBar1.Step    = bufferSize;

                byte[] datahash          = generatedatahash(file);
                byte[] encrypteddatahash = byteencrypter(datahash);
                byte[] signature         = byteencrypter(signData(file));

                byte[] signaturepacket = protocolSI.Make(ProtocolSICmdType.DIGITAL_SIGNATURE, signature);
                networkStream.Write(signaturepacket, 0, signaturepacket.Length);

                bool cancontinue = false;
                while (cancontinue == false)
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    if (protocolSI.GetStringFromData() == "true")
                    {
                        cancontinue = true;
                    }
                }

                byte[] datahashpacket = protocolSI.Make(ProtocolSICmdType.ASSYM_CIPHER_DATA, encrypteddatahash);
                networkStream.Write(datahashpacket, 0, datahashpacket.Length);

                cancontinue = false;
                while (cancontinue == false)
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    if (protocolSI.GetStringFromData() == "true")
                    {
                        cancontinue = true;
                    }
                }

                //copiar e enviar bytesread
                while ((bytesRead = originalFileStream.Read(buffer, 0, bufferSize)) > 0) // segmentar ficheiro
                {
                    //mandar bytes lidos
                    byte[] encriptedbytes  = Encoding.UTF8.GetBytes(stringencrypter(bytesRead.ToString()));
                    byte[] readbytesPacket = protocolSI.Make(ProtocolSICmdType.PADDING, encriptedbytes);
                    networkStream.Write(readbytesPacket, 0, readbytesPacket.Length);

                    //esperar por resposta de servidor ate enviar outro

                    cancontinue = false;
                    while (cancontinue == false)
                    {
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                        if (protocolSI.GetStringFromData() == "true")
                        {
                            cancontinue = true;
                        }
                    }

                    //mandar segmento
                    byte[] encriptedsegment = byteencrypter(buffer);
                    byte[] segmentPacket    = protocolSI.Make(ProtocolSICmdType.DATA, encriptedsegment);
                    networkStream.Write(segmentPacket, 0, segmentPacket.Length);

                    cancontinue = false;
                    while (cancontinue == false)
                    {
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                        if (protocolSI.GetStringFromData() == "true")
                        {
                            cancontinue = true;
                        }
                    }
                    progressBar1.PerformStep();
                }

                //terminar transferencia
                byte[] finishingpacket = protocolSI.Make(ProtocolSICmdType.EOF);
                networkStream.Write(finishingpacket, 0, finishingpacket.Length);

                originalFileStream.Close();

                //send file extension
                byte[] exttPacket = protocolSI.Make(ProtocolSICmdType.DATA, ext);
                networkStream.Write(exttPacket, 0, exttPacket.Length);

                DialogResult result = MessageBox.Show("Ficheiro enviado com sucesso", "Send Files",
                                                      MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (result == DialogResult.OK)
                {
                    progressBar1.Value = 0;
                }
            }
            else
            {
                MessageBox.Show("Acess not granted", "Send Files",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: JoaodssPSI/TopSeg
        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");
        }
コード例 #15
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
コード例 #16
0
        /// <summary>
        /// IMPORTANTE: a cada RECEÇÃO deve seguir-se, obrigatóriamente, um ENVIO de dados
        /// IMPORTANT: each network .Read() must be fallowed by a network .Write()
        /// </summary>
        static void Main(string[] args)
        {
            byte[]        msg;
            IPEndPoint    listenEndPoint;
            TcpListener   server    = null;
            TcpClient     client    = null;
            NetworkStream netStream = null;
            ProtocolSI    protocol  = null;
            TripleDESCryptoServiceProvider tripleDES = null;
            SymmetricsSI symmetricsSI = null;

            RSACryptoServiceProvider rsaClient = null;
            RSACryptoServiceProvider rsaServer = null;

            try {
                Console.WriteLine("SERVER");

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

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

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

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

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

                Console.WriteLine(SEPARATOR);

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

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

                Console.WriteLine(SEPARATOR);

                #region Exchange Public Key


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


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

                #endregion

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

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

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

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

                Console.WriteLine(SEPARATOR);

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

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

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key... ");
            Console.ReadKey();
        }
コード例 #17
0
ファイル: CreateUser.cs プロジェクト: JoaodssPSI/TopSeg
        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);
                }
            }
        }
コード例 #18
0
        //my main
        static void Main(string[] args)
        {
            // Vars
            int    Saltgador = 8;
            string ola       = "ola";
            string end       = "end";
            string var;

            byte[] salt = new byte[Saltgador];



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

            listener.Start();
            Console.WriteLine("Server Ready");

            //while (true)

            //aceita cliente

            do
            {
                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine("Client connected");
                NetworkStream networkStream = client.GetStream();
                ProtocolSI    protocolSI    = new ProtocolSI();
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                var = Convert.ToString(protocolSI.GetStringFromData());

                Thread.Sleep(1000);

                switch (var)
                {
                case ("1"):

                    string username;
                    string password;

                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    username = protocolSI.GetStringFromData();
                    Console.WriteLine("Obetendo username com sucesso!");
                    Thread.Sleep(1000);

                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    password = protocolSI.GetStringFromData();
                    networkStream.Close();
                    client.Close();
                    Console.WriteLine("Otendo password com sucesso!");
                    Thread.Sleep(1000);

                    salt = GenerateSalt(Saltgador);
                    byte[] SaltedHash = GenerateSaltedHash(Encoding.UTF8.GetBytes(password), salt);
                    Register(username, SaltedHash, salt);
                    Console.WriteLine("Tudo Feito com sucesso!");


                    break;

                case ("2"):
                    string usernamelogin;
                    string passwordlogin;
                    bool   confirm;

                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    usernamelogin = protocolSI.GetStringFromData();
                    Console.WriteLine("Obetendo username com sucesso!");
                    Thread.Sleep(1000);

                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    passwordlogin = protocolSI.GetStringFromData();

                    Console.WriteLine("Otendo password com sucesso!");
                    Thread.Sleep(1000);

                    confirm = VerifyLogin(usernamelogin, passwordlogin);
                    Console.WriteLine("Fazendo Login!");

                    networkStream.Close();
                    client.Close();



                    break;

                case ("3"):

                    enviarFicheiro();

                    break;

                default:
                    Console.WriteLine("Nenhuma funçao atribuida nesse valor!");
                    break;
                }
            }while(var != "10");
        }
コード例 #19
0
        static void Main(string[] args)
        {
            byte[]                   msg;
            IPEndPoint               serverEndPoint;
            TcpClient                client       = null;
            NetworkStream            netStream    = null;
            ProtocolSI               protocol     = null;
            AesCryptoServiceProvider aes          = null;
            SymmetricsSI             symmetricsSI = null;
            RSACryptoServiceProvider rsaClient    = null;
            RSACryptoServiceProvider rsaServer    = null;

            try {
                Console.WriteLine("CLIENT");

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

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


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

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

                Console.WriteLine(SEPARATOR);

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

                Console.WriteLine(SEPARATOR);

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

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

                Console.WriteLine(SEPARATOR);

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

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


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

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

                #endregion

                Console.WriteLine(SEPARATOR);

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

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



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

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

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

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

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key...");
            Console.ReadKey();
        }
コード例 #20
0
ファイル: Form1.cs プロジェクト: PSI17JoaoP/Projeto_TS_1617
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //é equivalente à inicialização de objetos e preparação do cliente.
                tcpClient = new TcpClient();
                endPoint  = new IPEndPoint(IPAddress.Loopback, port);

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

                protocolSI = new ProtocolSI();

                servicoCriptoSimetrico = new ServiceCriptoSimetrica();

                string publickey = null;
                byte[] secretkey = null;
                byte[] iv        = null;

                ProtocolSICmdType protocolTipoResposta;

                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                //lê para o buffer a key, enviada anteriormente pelo servidor.

                if (protocolSI.GetCmdType() == ProtocolSICmdType.PUBLIC_KEY)
                {
                    //serve para determinar e verificar se o buffer é do tipo public key, se for executa.
                    publickey = protocolSI.GetStringFromData();
                    //obtêm a string do buffer, este sendo um array de bytes.
                    //Receção e envio da public key, do cliente para o servidor e receber do servidor
                    Debug.Print("Received Public Key");

                    servicoAssinaturas = new ServiceCriptoAssimetrica(publickey);
                    //Vai instanciar um servico de criptografia assimetrica, com a public key do servidor.
                    //O construtor desta classe necessita da public key, por isso é que só foi inicializado agora.

                    secretkey = servicoCriptoSimetrico.ObterSecretKey();
                    byte[] secretkeyEncriptada = protocolSI.Make(ProtocolSICmdType.SECRET_KEY, servicoAssinaturas.EncriptarDados(secretkey));
                    networkStream.Write(secretkeyEncriptada, 0, secretkeyEncriptada.Length);
                    Debug.Print("Secret Key Sent");

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

                        protocolTipoResposta = protocolSI.GetCmdType();

                        if (protocolTipoResposta == ProtocolSICmdType.ACK)
                        {
                            iv = servicoCriptoSimetrico.ObterIV();
                            byte[] ivEncriptado = protocolSI.Make(ProtocolSICmdType.IV, servicoAssinaturas.EncriptarDados(iv));
                            networkStream.Write(ivEncriptado, 0, ivEncriptado.Length);
                            Debug.Print("IV Sent");
                        }
                    }while (protocolTipoResposta != ProtocolSICmdType.ACK);

                    //encriptar a chave secreta com a publica  envia la ao mesmo tempo
                    //como o do outro lado.
                }
                else
                {
                    //caso não seja do tipo public key envia uma mensagem de erro.
                    MessageBox.Show("Erro ao receber a chave pública", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            catch (Exception)
            {
                MessageBox.Show("Erro encontrado. A encerrar", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ShutDown();
                StopConnection();
            }
        }
コード例 #21
0
        private void buttonLoginRegister_Click(object sender, EventArgs e)
        {
            string msg = "";                                                                                          // Cria a variável que recebe a resposta do Servidor

            if (!String.IsNullOrWhiteSpace(textBoxUsername.Text) || !String.IsNullOrWhiteSpace(textBoxPassword.Text)) // Verifica se os campos de Username e Password estão preenchidos
            {
                byte[] option1 = protocolSI.Make(ProtocolSICmdType.USER_OPTION_1, textBoxUsername.Text);              // Cria a mensagem que envia o Username do utilizador

                networkStream.Write(option1, 0, option1.Length);                                                      // Envia a mensagem através da Stream

                while (protocolSI.GetCmdType() == ProtocolSICmdType.ACK)                                              // Espera pela confirmação (Acknowledge) do Servidor
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                }

                /* Verifica se é para realizar Login ou Registo */

                if (isLogin == true)                                                                         // Caso seja Login
                {
                    byte[] option3 = protocolSI.Make(ProtocolSICmdType.USER_OPTION_3, textBoxPassword.Text); // Cria a mensagem que envia a Password do utilizador

                    networkStream.Write(option3, 0, option3.Length);                                         // Envia a mensagem através da Stream

                    while (true)
                    {
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length); // Lê o buffer

                        if (protocolSI.GetCmdType() == ProtocolSICmdType.ACK)               // Se for ACK (Acknowledge) sai fora do ciclo While
                        {
                            break;
                        }
                        else if (protocolSI.GetCmdType() == ProtocolSICmdType.DATA) // Se for DATA apanha a resposta do Servidor
                        {
                            msg += protocolSI.GetStringFromData();
                        }
                    }
                }
                else // Caso seja Registo
                {
                    byte[] option2 = protocolSI.Make(ProtocolSICmdType.USER_OPTION_2, textBoxPassword.Text); // Cria a mensagem que envia a Password do utilizador

                    networkStream.Write(option2, 0, option2.Length); // Envia a mensagem através da Stream

                    while (true)
                    {
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length); // Lê o buffer

                        if (protocolSI.GetCmdType() == ProtocolSICmdType.ACK)               // Se for ACK (Acknowledge) sai fora do ciclo While
                        {
                            break;
                        }
                        else if (protocolSI.GetCmdType() == ProtocolSICmdType.DATA) // Se for DATA apanha a resposta do Servidor
                        {
                            msg += protocolSI.GetStringFromData();
                        }
                    }
                }

                if (!String.IsNullOrWhiteSpace(msg))        // Verifica se a resposta do Servidor é vazia ou null
                {
                    MessageBox.Show(msg, "Login/Registo."); // Apresenta a resposta ao utilizador
                }

                formCliente = new FormCliente(networkStream, protocolSI, tcpClient); // Instancia o Form do CLiente (janela de Chat) com as informações de conexão
                this.Hide();                                                         // Esconde a janela de Login (não dá para fechar a janela pois fecharia também a janela de Chat)
                formCliente.ShowDialog();                                            // Abre a janela de Chat
            }
            else
            {
                MessageBox.Show("Tem de preencher os campos todos.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
コード例 #22
0
        private void threadHandler() //Trata as mensagens que chegam e que são enviadas
        {
            networkStream = this.tcpClient.GetStream();
            protocolSI    = new ProtocolSI();
            Boolean trocaPosicao = false;

            while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT) //Enquanto a thread não receber ordens para terminar
            {
                networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                ProtocolSICmdType cmd = protocolSI.GetCmdType();
                string            msg;
                byte[]            msgByte;
                switch (protocolSI.GetCmdType())
                {
                case ProtocolSICmdType.PUBLIC_KEY:
                    security.setPublicKey(protocolSI.GetStringFromData());
                    Console.WriteLine("Recebi uma chave pública");
                    enviaACK();

                    simetricKey = protocolSI.Make(ProtocolSICmdType.SYM_CIPHER_DATA, security.getSimetricKey());
                    networkStream.Write(simetricKey, 0, simetricKey.Length);
                    esperaACK();

                    IV = protocolSI.Make(ProtocolSICmdType.IV, security.getIV());
                    networkStream.Write(IV, 0, IV.Length);
                    esperaACK();
                    break;

                case ProtocolSICmdType.USER_OPTION_1: //Adquire o nome do jogador
                    connection.WaitOne();             //Caso no qual é feito um broadcast e a thread "errada" recebe o ACK e, portanto
                    connection.ReleaseMutex();        //espera até que a thread "correta" receba o ACK para poder voltar a esperar nova mensagem
                    nomeJogador = security.DecifrarTexto(protocolSI.GetStringFromData());
                    Console.WriteLine("Jogador {0} - {1}, conectou-se", clientID, nomeJogador);
                    enviaACK();
                    break;

                case ProtocolSICmdType.USER_OPTION_2:     //Atualiza os jogadores presentes na sala
                    string salaDesejada = security.DecifrarTexto(protocolSI.GetStringFromData());
                    byte[] newJogador;

                    foreach (room sala in rooms)     //Percorre a lista de salas verificando se a sala na qual o cliente deseja conectar-se já existe
                    {
                        if (sala.getName() == salaDesejada)
                        {
                            if (!sala.isFull())     //Verifica se a sala não está cheia
                            {
                                sala.addClientToRoom(this);
                                this.room = sala;
                                break;
                            }
                            else
                            {
                                goto SalaCheia;
                            }
                        }
                    }

                    if (room == null)     //Cria a sala caso a mesma não exista
                    {
                        room = new room(salaDesejada);
                        rooms.Add(room);
                        room.addClientToRoom(this);
                        msg = System.DateTime.Now.ToString();
                        room.writeLog(msg);
                    }

                    Console.WriteLine("{0} entrou na sala {1}", nomeJogador, salaDesejada);
                    enviaACK();

                    if (room.getClientList().Count == 1)     //Se aquele jogador é o único na sala
                    {
                        //Coloca o jogador como o jogador 1
                        room.setJogador(nomeJogador);
                        msg        = String.Format("1/{0}/", nomeJogador);
                        newJogador = protocolSI.Make(ProtocolSICmdType.USER_OPTION_1, security.CifrarTexto(msg));
                        networkStream.Write(newJogador, 0, newJogador.Length);
                        esperaACK();
                    }
                    else if (room.getClientList().Count == 2)      //Se é o 2º jogador a entrar na sala
                    {
                        int posNovoJogador;
                        room.setJogador(nomeJogador);
                        foreach (ClientHandler client in room.getClientList())
                        {
                            if (client.clientID != clientID)
                            {
                                posNovoJogador = room.getNomeJogador(2) == nomeJogador ? 2 : 1;     //Descobre qual será a posição do novo jogador
                                msg            = String.Format("{0}/{1}/{2}", posNovoJogador, nomeJogador, jogadores);
                                newJogador     = protocolSI.Make(ProtocolSICmdType.USER_OPTION_1, client.security.CifrarTexto(msg));

                                broadcast(msg, ProtocolSICmdType.USER_OPTION_1, nomeJogador);

                                //Coloca-se na posição que resta
                                networkStream.Write(newJogador, 0, newJogador.Length);
                                esperaACK();
                            }
                            else     //Envia o nome do jogador que já está na sala para o novo jogador
                            {
                                int posJogadorPresente = room.getNomeJogador(1) != nomeJogador ? 1 : 2;
                                msg     = String.Format("{0}/{1}/{2}", posJogadorPresente, room.getNomeJogador(posJogadorPresente), true == room.isMultiplePlayers() ? "true" : "false");
                                msgByte = protocolSI.Make(ProtocolSICmdType.USER_OPTION_1, security.CifrarTexto(msg));
                                networkStream.Write(msgByte, 0, msgByte.Length);
                                esperaACK();
                            }
                        }
                        //Broadcast que informa que há 2 jogadores na sala e, portanto o jogo pode iniciar
                        broadcast(" ", ProtocolSICmdType.USER_OPTION_3);
                    }
                    else     //Se a sala já tem 2 jogadores
                    {
                        //Coloca os próximos jogadores na fila
                        room.setJogador(nomeJogador);
                        msg = String.Format("3/{0}/{1}/{2}/{3}/{4}/{5}/{6}", room.getNomeJogador(1), room.getNomeJogador(2), room.getPontos(room.getNomeJogador(1)),
                                            room.getPontos(room.getNomeJogador(2)), room.getPontos("empates"), jogadores, room.getProximoJogadores());
                        newJogador = protocolSI.Make(ProtocolSICmdType.USER_OPTION_1, security.CifrarTexto(msg));
                        networkStream.Write(newJogador, 0, newJogador.Length);
                        msg = String.Format("4/{0}/{1}", jogadores, room.getProximoJogadores());
                        broadcast(msg, ProtocolSICmdType.USER_OPTION_1);
                        esperaACK();
                    }
                    break;
SalaCheia:
                    msgByte = protocolSI.Make(ProtocolSICmdType.USER_OPTION_3);
                    networkStream.Write(msgByte, 0, msgByte.Length);
                    esperaACK();
                    break;

                case ProtocolSICmdType.DATA:     //Transmite o que o jogador disse para o chat
                    msg = $"{System.DateTime.Now.ToString("HH:mm:ss")} - {nomeJogador} : {security.DecifrarTexto(protocolSI.GetStringFromData())}";
                    Console.WriteLine(msg);
                    broadcast(msg, ProtocolSICmdType.DATA); //Broadcast da mensagem para todos os jogadores
                    room.writeLog(msg);                     //Escreve para o arquivo de texto as mensagens do chat
                    break;

                case ProtocolSICmdType.USER_OPTION_3:     //Trata da jogada executada utilizando assinaturas digitais
                                                          //Recebe o movimento cifrado
                    string move = security.DecifrarTexto(protocolSI.GetStringFromData());
                    //Espera pelo hash assinado do movimento cifrado com a chave privada
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    while (protocolSI.GetCmdType() != ProtocolSICmdType.USER_OPTION_4)
                    {
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    }
                    string moveSign = security.DecifrarTexto(protocolSI.GetStringFromData());
                    //Verifica a autenticidade do movimento
                    if (security.verifySignData(move, moveSign))
                    {
                        string[] coordenadas  = move.Split('/');
                        int      line         = int.Parse(coordenadas[0]);
                        int      col          = int.Parse(coordenadas[1]);
                        string   symbolPlayer = room.getNomeJogador(1) == this.nomeJogador ? "X" : "O";
                        switch (room.move(line, col, this.nomeJogador))
                        {
                        case -1:         //Movimento é inválido
                            msg = "Movimento inválido, tente novamente!";
                            byte[] invalid = protocolSI.Make(ProtocolSICmdType.USER_OPTION_4, security.CifrarTexto(msg));
                            networkStream.Write(invalid, 0, invalid.Length);
                            break;

                        case 0:         //Movimento válido
                            broadcast(String.Format("{0}{1}/{2}", line, col, symbolPlayer), ProtocolSICmdType.USER_OPTION_5);
                            break;

                        case 1:         //Jogo termina com um ganhador
                            broadcast(String.Format("{0}{1}/{2}", line, col, symbolPlayer), ProtocolSICmdType.USER_OPTION_5);
                            Thread.Sleep(100);
                            broadcast(String.Format("{0}/ganhou!", nomeJogador), ProtocolSICmdType.USER_OPTION_6);
                            Thread.Sleep(100);
                            if (trocaPosicao)
                            {
                                trocaDePosicao(room.isMultiplePlayers() == true ? true : false);
                                trocaPosicao = false;
                            }
                            break;

                        case 2:        //Jogo termina em empate
                            broadcast(String.Format("{0}{1}/{2}", line, col, symbolPlayer), ProtocolSICmdType.USER_OPTION_5);
                            Thread.Sleep(100);
                            broadcast(String.Format("/Empate!", nomeJogador), ProtocolSICmdType.USER_OPTION_6);
                            Thread.Sleep(100);
                            if (trocaPosicao)
                            {
                                trocaDePosicao(room.isMultiplePlayers() == true ? true : false);
                                trocaPosicao = false;
                            }
                            break;

                        case 3:         //Jogador incorreto tentou fazer o movimento
                            msg = "Espere a sua vez!";
                            byte[] jogadorIncorreto = protocolSI.Make(ProtocolSICmdType.USER_OPTION_4, security.CifrarTexto(msg));
                            networkStream.Write(jogadorIncorreto, 0, jogadorIncorreto.Length);
                            break;

                        default:
                            Console.WriteLine("Algo de errado aconteceu ao executar room.move");
                            break;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Mensagem enviada inválida");
                        msg = "Ocorreu algum erro, tente novamente!";
                        byte[] invalid = protocolSI.Make(ProtocolSICmdType.USER_OPTION_7, security.CifrarTexto(msg));
                        networkStream.Write(invalid, 0, invalid.Length);
                    }
                    break;

                case ProtocolSICmdType.USER_OPTION_5:     //Jogador solicitou troca de posição
                    trocaPosicao = true;
                    if (!room.jogo.jogoComecou())
                    {
                        trocaDePosicao();
                    }
                    break;

                case ProtocolSICmdType.USER_OPTION_6:     //Jogador solicitou permitir vários jogadores
                    room.multiplePlayers();
                    msg = "Múltiplos jogadores habilitado";
                    broadcast(msg, ProtocolSICmdType.USER_OPTION_8);
                    break;

                case ProtocolSICmdType.SECRET_KEY:     //Recebe a senha do usuário
                    Console.WriteLine("Recebi a senha");
                    string senha = security.DecifrarTexto(protocolSI.GetStringFromData());
                    if (security.VerifyLogin(this.nomeJogador, senha))
                    {     //Autentica o jogador
                        Console.WriteLine("{0} autenticado com sucesso", this.nomeJogador);
                        msg = String.Format("{0}/{1}", nomeJogador, security.GetPoints(nomeJogador));
                        byte[] ack = protocolSI.Make(ProtocolSICmdType.ACK, security.CifrarTexto(msg));
                        networkStream.Write(ack, 0, ack.Length);
                        jogadores = jogadores + nomeJogador + ',' + security.GetPoints(nomeJogador) + ';';
                    }
                    else
                    {
                        Console.WriteLine("{0} senha incorreta", this.nomeJogador);
                        byte[] msgConnection = protocolSI.Make(ProtocolSICmdType.USER_OPTION_3);
                        networkStream.Write(msgConnection, 0, msgConnection.Length);
                        esperaACK();
                    }
                    break;

                case ProtocolSICmdType.EOT:     //Finaliza a sessão do jogador
                    Console.WriteLine("Ending Thread from {0}", nomeJogador);
                    if (room != null)
                    {
                        security.setPoints(nomeJogador, room.getPontos(nomeJogador) + security.GetPoints(nomeJogador));
                        if (room.getClientList().Count >= 2)
                        {
                            msg = String.Format("Jogador {0} deixou a sala/{1}", nomeJogador, nomeJogador);
                            broadcast(msg, ProtocolSICmdType.USER_OPTION_9, nomeJogador);
                        }
                    }
                    room.novoJogo();
                    break;

                case ProtocolSICmdType.ACK:     //Caso no qual é feito um broadcast e a thread "errada" recebe o ACK e, portanto
                    connection.WaitOne();       //espera até que a thread "correta" receba o ACK para poder voltar a esperar nova mensagem
                    connection.ReleaseMutex();
                    break;

                default:
                    break;
                }
            }
            networkStream.Close();
            this.tcpClient.Close();
            if (room != null)
            {
                this.room.removeClientOfRoom(this);
                this.room = null;
            }
        }
コード例 #23
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());
        }
コード例 #24
0
        /// <summary>
        /// IMPORTANTE: a cada RECEÇÃO deve seguir-se, obrigatóriamente, um ENVIO de dados
        /// IMPORTANT: each network .Read() must be fallowed by a network .Write()
        /// </summary>
        static void Main(string[] args)
        {
            byte[]        msg;
            IPEndPoint    serverEndPoint;
            TcpClient     client    = null;
            NetworkStream netStream = null;
            ProtocolSI    protocol  = null;
            TripleDESCryptoServiceProvider tripleDES = null;
            SymmetricsSI symmetricsSI = null;

            RSACryptoServiceProvider rsaClient = null;
            RSACryptoServiceProvider rsaServer = null;

            try {
                Console.WriteLine("CLIENT");

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

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

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

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

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

                Console.WriteLine(SEPARATOR);

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

                Console.WriteLine(SEPARATOR);

                #region Exchange Public Key

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

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

                #endregion


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

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

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

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

                Console.WriteLine(SEPARATOR);

                #region Exchange Data  (Secure channel)
                // Send data...
                byte[] clearData     = Encoding.UTF8.GetBytes("hello world!!!");
                byte[] encryptedData = symmetricsSI.Encrypt(clearData);
                Console.Write("Sending  data... ");
                msg = protocol.Make(ProtocolSICmdType.DATA, encryptedData);
                netStream.Write(msg, 0, msg.Length);
                Console.WriteLine("ok.");
                Console.WriteLine("Data to encrypt.... (STR): {0}", ProtocolSI.ToString(clearData));
                Console.WriteLine("Data to encrypt.... (HEX): {0}", ProtocolSI.ToHexString(clearData));
                Console.WriteLine("Encrypted data sent (HEX): {0}", ProtocolSI.ToHexString(encryptedData));

                // Receive answer from server
                Console.Write("waiting for ACK... ");
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                Console.WriteLine("ok.");
                #endregion
            } catch (Exception ex) {
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Exception: {0}", ex.ToString());
            } finally {
                if (tripleDES != null)
                {
                    tripleDES.Dispose();
                }
                // Close connections
                if (netStream != null)
                {
                    netStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                }
                Console.WriteLine(SEPARATOR);
                Console.WriteLine("Connection with server was closed.");
            }

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key...");
            Console.ReadKey();
        }
コード例 #25
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();
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: simaopina/Projeto-TS
        //----------------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);*/


            //}
        }
コード例 #27
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
            }
コード例 #28
0
ファイル: Program.cs プロジェクト: Albert-Snake/ProjectoTS
        //Estabelecer comunicação e obter mensagens do cliente
        private void threadHandler()
        {
            NetworkStream networkStream = this.client.GetStream();
            ProtocolSI    protocolSI    = new ProtocolSI();

            while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT)
            {
                //Ler dados do cliente
                try
                {
                    int bytesRead = networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                }
                catch (Exception ex)
                {
                }

                //Criar resposta para o cliente
                byte[] ack;

                switch (protocolSI.GetCmdType())
                {
                case ProtocolSICmdType.DATA:
                    Console.WriteLine(protocolSI.GetStringFromData());

                    string     caminho = @"C:\Projecto de TS Completo\Server\conversa.txt";
                    FileStream fs      = new FileStream(caminho, FileMode.Append, FileAccess.Write);
                    // criar o buffer binário de escrita
                    BinaryWriter bw = new BinaryWriter(fs);
                    // Guardar os dados no ficheiro
                    bw.Write(protocolSI.GetStringFromData());
                    // Fechar o ficheiro e o stream
                    bw.Close();
                    fs.Close();

                    //Criar resposta paara o cliente com o protocolSI
                    ack = protocolSI.Make(ProtocolSICmdType.ACK);

                    //Enviar a mensagem para o cliente
                    try
                    {
                        networkStream.Write(ack, 0, ack.Length);
                        break;
                    }
                    catch (Exception ex)
                    {
                        break;
                    }

                case ProtocolSICmdType.EOT:
                    Console.WriteLine("Deixou o Chat");

                    //Criar resposta paara o cliente com o protocolSI
                    ack = protocolSI.Make(ProtocolSICmdType.ACK);

                    //Enviar a mensagem para o cliente
                    networkStream.Write(ack, 0, ack.Length);
                    break;
                }
            }
            //Fechar as ligações
            networkStream.Close();
            client.Close();
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: RuiPenetra/spks
        private void threadHandler()
        {
            // OBTEM O STREAM DE COMUNICAÇÃO COM O CLIENTE
            networkStream = this.client.GetStream();

            // INICIA O PROTOCOLO SI
            protocolSI = new ProtocolSI();

            // para a hash para validação de dados (integridade)
            sha512 = SHA512.Create();

            byte[]       ack;
            string       ficheiro_sala = "";
            StreamWriter streamWriter;

            // directoria do projeto (Servidor/)
            string directoriaProjeto = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName;

            // ENQUANTO NÃO RECEBE UMA MSG DO TIPO EOT
            while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT)
            {
                // RECEBE AS MENSAGENS DO CLIENTE
                int bytesRead = networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);

                // VERIFICA O TIPO DE MENSAGEM RECEBIDO
                switch (protocolSI.GetCmdType())
                {
                //enviar chaves
                case ProtocolSICmdType.USER_OPTION_1:


                    //guardar chave do cliente
                    this.chavePublicaCliente = protocolSI.GetStringFromData();

                    Enviar_ACK();

                    //criar chave simetrica
                    aes = new AesCryptoServiceProvider();

                    //guardar chave e vetor da chave simetrica
                    this.key = aes.Key;
                    this.IV  = aes.IV;

                    // cifrar com a chave publica do cliente
                    string keycifrada = cifrarComChavePublica(this.key, this.chavePublicaCliente);
                    string ivcifrado  = cifrarComChavePublica(this.IV, this.chavePublicaCliente);

                    // enviar chave simetrica para o cliente
                    //chave
                    byte[] enviarKey = protocolSI.Make(ProtocolSICmdType.SECRET_KEY, Convert.FromBase64String(keycifrada));
                    networkStream.Write(enviarKey, 0, enviarKey.Length);


                    // se o cliente respondeu ACK, continua a enviar coisas
                    if (Receber_ACK())
                    {
                        //enviar vetor
                        byte[] enviarIV = protocolSI.Make(ProtocolSICmdType.IV, Convert.FromBase64String(ivcifrado));
                        networkStream.Write(enviarIV, 0, enviarIV.Length);

                        if (Receber_ACK())
                        {
                            //cifrar a chave publica com a chave simetrica
                            byte[] chavePublica        = Encoding.UTF8.GetBytes(chavepublicaServidor);
                            byte[] chavePublicaCifrada = cifrarComChaveSimetrica(chavePublica);

                            //enviar para o cliente
                            byte[] enviarChavePublicaCifrada = protocolSI.Make(ProtocolSICmdType.SYM_CIPHER_DATA, chavePublicaCifrada);
                            networkStream.Write(enviarChavePublicaCifrada, 0, enviarChavePublicaCifrada.Length);

                            if (!Receber_ACK())
                            {
                                Enviar_NACK();     // algo correu mal
                            }
                        }
                        else
                        {
                            Enviar_NACK();     // algo correu mal
                        }
                    }
                    else
                    {
                        Enviar_NACK();     // algo correu mal
                    }

                    break;

                // login
                case ProtocolSICmdType.USER_OPTION_2:

                    dados_recebidos = protocolSI.GetData();

                    byte[] dados_login_bytes = decifrarComChaveSimetrica(dados_recebidos);

                    string dados_login = emString(dados_login_bytes);

                    // separar dados
                    string[] split_dados_login = Regex.Split(dados_login, "_Ø_");     // username_Ø_password

                    string user = split_dados_login[0];
                    string pass = split_dados_login[1];

                    Enviar_ACK();

                    // recebe a hash, decifra-a e envia ACK
                    hash_recebida = Receber_Hash();

                    // integridade
                    if (Integridade_Valida(hash_recebida, dados_login_bytes))
                    {
                        // caso login com sucesso, manda o OK e guarda o username
                        if (VerifyLogin(user, pass))
                        {
                            this.nickname = user;
                            Enviar_ACK();
                        }
                        else
                        {
                            Enviar_NACK();
                        }
                    }
                    else
                    {
                        Enviar_NACK();
                    }

                    break;

                // registo
                case ProtocolSICmdType.USER_OPTION_3:

                    dados_recebidos = protocolSI.GetData();

                    byte[] dados_bytes = decifrarComChaveSimetrica(dados_recebidos);

                    string dados = emString(dados_bytes);


                    Enviar_ACK();

                    // separar dados
                    string[] split_dados = Regex.Split(dados, "_Ø_");     // username_Ø_password

                    //guarda a password e passa para bytes
                    string username = split_dados[0];
                    byte[] password = Encoding.UTF8.GetBytes(split_dados[1]);

                    //gera o salt e "salga" a password
                    byte[] salt         = GenerateSalt(SALTSIZE);
                    byte[] passwordSalt = GenerateSaltedHash(password, salt);

                    // recebe a hash, decifra-a e envia ACK
                    hash_recebida = Receber_Hash();


                    if (Integridade_Valida(hash_recebida, dados_bytes))
                    {
                        // caso registe com sucesso, manda o OK
                        if (Register(username, passwordSalt, salt))
                        {
                            Console.WriteLine("Novo registo de utilizador: " + username);
                            Enviar_ACK();
                        }
                        else
                        {
                            Enviar_NACK();
                        }
                    }
                    else
                    {
                        Enviar_NACK();
                    }
                    break;

                // sala
                case ProtocolSICmdType.USER_OPTION_4:

                    //receber dados
                    dados_recebidos = protocolSI.GetData();

                    //decifrar dados

                    byte[] nome_sala_bytes = decifrarComChaveSimetrica(dados_recebidos);

                    string nome_sala = emString(nome_sala_bytes);


                    //enviar ack
                    Enviar_ACK();

                    //receber hash, decifrar e enviar ack
                    hash_recebida = Receber_Hash();


                    if (Integridade_Valida(hash_recebida, nome_sala_bytes))
                    {
                        // remove caracteres especiais do nome da sala
                        // e constroi o caminho da directoria
                        ficheiro_sala = directoriaProjeto + "/Salas/" + CleanInput(nome_sala) + ".txt";

                        IdSala = getIdSala(listSalas, nome_sala);

                        //verificar se a sala ja existe
                        if (File.Exists(ficheiro_sala) && IdSala > -1)
                        {
                            //Verifica se esta disponivel
                            if (listSalas[IdSala].numeroClientes >= 2)     //Caso nao esteja disponivel
                            {
                                //dizer que nao ta ok
                                Enviar_NACK();

                                Console.WriteLine("Cliente: " + nickname + " tentou entrar na sala " + nome_sala + " ");
                                Console.WriteLine("<O cliente {0} desconectou-se!>", clientID);

                                // FECHA AS COMUNICAÇOES COM O CLIENTE
                                networkStream.Close();
                                client.Close();

                                return;
                            }
                            else
                            {
                                //Adiciona o cliente
                                ClassePrincipalServidor.AdicionarCliente(IdSala);
                                if (listSalas[IdSala].nickname1 == null)
                                {
                                    listSalas[IdSala].nickname1 = nickname;
                                }
                                else
                                {
                                    listSalas[IdSala].nickname2 = nickname;
                                }
                                // colocar a sinalização de que ha msgs novas para o novo cliente ler
                                ClassePrincipalServidor.ExistemMensagensNovas(IdSala);

                                // avisar sala de que entrou

                                streamWriter = new StreamWriter(ficheiro_sala, true);     // append true
                                streamWriter.WriteLine(nickname + " entrou. ");
                                streamWriter.Dispose();
                            }

                            Enviar_ACK();
                            if (listSalas[IdSala].Atac == null)
                            {
                                listSalas[IdSala].Atac = nickname;
                                enviarCliente("Ataque");
                            }
                            else
                            {
                                listSalas[IdSala].Defensor = nickname;
                                enviarCliente("Defesa");
                            }
                        }
                        else
                        {
                            //Criar sala(ficheiro);
                            // guarda o nome da sala no cliente
                            Sala Sala = new Sala(nome_sala);

                            streamWriter = new StreamWriter(ficheiro_sala, false);     // append false

                            streamWriter.WriteLine("Chat Iniciado");

                            // avisar sala de que entrou
                            streamWriter.WriteLine(nickname + " entrou. ");
                            streamWriter.Dispose();



                            // cria nova sala na lista geral
                            ClassePrincipalServidor.AdicionarSala(Sala);

                            // atualiza a lista local
                            this.listSalas = ClassePrincipalServidor.ListaDeSalas();

                            IdSala = listSalas.LastIndexOf(Sala);



                            Enviar_ACK();

                            listSalas[IdSala].nickname1 = nickname;
                            listSalas[IdSala].Atac      = nickname;
                            enviarCliente("Ataque");


                            Console.WriteLine("Sala criada: " + Sala.nome + " ");
                            Console.WriteLine("Total de salas: " + listSalas.Count() + " ");
                        }
                        break;
                    }
                    else
                    {
                        Enviar_NACK();
                    }
                    break;


                //resposta ao pedido de dados do cliente
                case ProtocolSICmdType.USER_OPTION_5:

                    //receber dados
                    dados_recebidos = protocolSI.GetData();

                    //passar para bytes
                    byte[] dados_Bytes = decifrarComChaveSimetrica(dados_recebidos);

                    //decifrar dados
                    int lenghtClienteTem = Int32.Parse(emString(dados_Bytes));

                    //enviar ack
                    Enviar_ACK();

                    //receber hash e  enviar ack
                    hash_recebida = Receber_Hash();


                    //  verificar a integridade
                    if (Integridade_Valida(hash_recebida, dados_Bytes))
                    {
                        Enviar_ACK();

                        // vai buscar o ficheiro da sala para ler
                        ficheiro_sala = directoriaProjeto + "/Salas/" + CleanInput(listSalas[IdSala].nome) + ".txt";

                        string response = File.ReadAllText(ficheiro_sala);

                        response = response.Substring(lenghtClienteTem);

                        // LIMPA A VARIAVEL AUXILIAR
                        string stringChunk = "";

                        // TAMANHO PARA LER DE CADA VEZ (USAR COMO MÁX 64 CARACTERES)
                        int chunkSize = 60;

                        // VAI BUSCAR O TAMANHO DA RESPOSTA
                        int stringLength = response.Length;

                        // variavel para o pacote
                        byte[] packet;


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

                        Console.WriteLine("  -> " + stringLength);

                        // PERCORRE A RESPOSTA E VAI DIVIDINDO EM PEDAÇOS PEQUENOS (CHUNKS)
                        for (int i = 0; i < response.Length; i = i + chunkSize)
                        {
                            // CASE SEJA O ÚLTIMO CHUNK
                            if (chunkSize > stringLength)
                            {
                                // ENVIA TUDO O QUE FALTA
                                stringChunk = response.Substring(i);
                            }

                            // CASO SEJA UM CHUNK NORMAL
                            else
                            {
                                // DECREMENTA O TOTAL DE CARACTERES JÁ LIDOS
                                stringLength = stringLength - chunkSize;

                                // OBTEM ESSE CHUNK
                                stringChunk = response.Substring(i, chunkSize);
                            }

                            //cifrar e enviar
                            byte[] chunckCifrado = cifrarComChaveSimetrica(Encoding.UTF8.GetBytes(stringChunk));

                            // CRIA A MENSAGEM DO TIPO DATA UTILIZANDO O PROTOCOLO SI
                            packet = protocolSI.Make(ProtocolSICmdType.DATA, chunckCifrado);

                            // ENVIA A RESPOSTA PARA O CLIENTE (WRITE)
                            networkStream.Write(packet, 0, packet.Length);
                        }

                        Console.WriteLine("  -> " + nickname + " atualizou os dados");

                        // CRIA O EOF PARA ENVIAR PARA O CLIENTE
                        byte[] eof = protocolSI.Make(ProtocolSICmdType.EOF);

                        // ENVIA A RESPOSTA PARA O CLIENTE (WRITE)
                        networkStream.Write(eof, 0, eof.Length);

                        Console.WriteLine("  -> " + nickname + " EOF ");


                        // Receber ACK, se o cliente recebeu tudo, continua
                        if (Receber_ACK())
                        {
                            // enviar hash de tudo
                            byte[] hashing = CriarHash_Assinar_Cifrar(Encoding.UTF8.GetBytes(response));

                            // CRIA A MENSAGEM DO TIPO NORMAL (para enviar a hash) UTILIZANDO O PROTOCOLO SI
                            packet = protocolSI.Make(ProtocolSICmdType.NORMAL, hashing);

                            //escreve na stream
                            networkStream.Write(packet, 0, packet.Length);

                            if (!Receber_ACK())     // nao recebeu hash
                            {
                                Console.WriteLine("  -> " + nickname + "não recebeu hash ");
                            }
                        }
                    }
                    else
                    {
                        Enviar_NACK();
                    }

                    break;

                // saber se existem novas msgs
                case ProtocolSICmdType.USER_OPTION_6:

                    if (ClassePrincipalServidor.VerificarMensagensNovas(IdSala) > 0)
                    {
                        // CRIA O ACK PARA ENVIAR PARA O CLIENTE para ele verificar as novas msgs
                        Enviar_ACK();
                        Console.WriteLine("  -> " + nickname + " precisa de novos dados");
                    }
                    else
                    {
                        Enviar_NACK();     // nao necessita de atualizar
                    }
                    break;

                case ProtocolSICmdType.USER_OPTION_7:
                    //receber dados
                    dados_recebidos = protocolSI.GetData();
                    byte[] msg = decifrarComChaveSimetrica(dados_recebidos);
                    string pos = emString(msg);

                    //enviar ack
                    Enviar_ACK();

                    //receber hash e  enviar ack
                    hash_recebida = Receber_Hash();


                    //  verificar a integridade
                    if (Integridade_Valida(hash_recebida, msg))
                    {
                        if (nickname == listSalas[IdSala].Atac)
                        {
                            listSalas[IdSala].PosAtac = pos;
                            Console.Write("Estou a atacar na pos:" + pos);
                        }
                        else
                        {
                            listSalas[IdSala].PosDefensor = pos;
                            Console.Write("Estou a defender na pos:" + pos);
                        }
                    }
                    else
                    {
                        Enviar_NACK();
                    }
                    break;

                case ProtocolSICmdType.USER_OPTION_8:

                    if (listSalas[IdSala].PosAtac == null || listSalas[IdSala].PosDefensor == null)
                    {
                        Enviar_NACK();
                        break;
                    }

                    Enviar_ACK();

                    if (listSalas[IdSala].PosAtac == listSalas[IdSala].PosDefensor)
                    {
                        if (nickname == listSalas[IdSala].Atac)
                        {
                            enviarCliente(NAOACERTOU);
                            listSalas[IdSala].msg++;
                        }
                        else
                        {
                            enviarCliente(DEFENDEU);
                            listSalas[IdSala].msg++;
                            listSalas[IdSala].adicionarPontos(nickname);
                        }
                    }
                    else
                    {
                        if (nickname == listSalas[IdSala].Atac)
                        {
                            enviarCliente(MARCOU);
                            listSalas[IdSala].msg++;
                            listSalas[IdSala].adicionarPontos(nickname);
                        }
                        else
                        {
                            enviarCliente(NAOACERTOU);
                            listSalas[IdSala].msg++;
                        }
                    }

                    if (listSalas[IdSala].msg == 2)
                    {
                        listSalas[IdSala].msg         = 0;
                        listSalas[IdSala].PosAtac     = null;
                        listSalas[IdSala].PosDefensor = null;
                        listSalas[IdSala].trocarFuncoes();
                        listSalas[IdSala].QuantosJogaram++;
                        if (listSalas[IdSala].QuantosJogaram == 5)
                        {
                            listSalas[IdSala].QuantosJogaram = 0;
                            listSalas[IdSala].PontosJogador1 = 0;
                            listSalas[IdSala].PontosJogador2 = 0;
                        }
                    }

                    break;


                // SE FOR DO TIPO DATA É UMA MENSAGEM PARA MOSTRAR
                case ProtocolSICmdType.DATA:

                    //receber dados
                    dados_recebidos = protocolSI.GetData();

                    //decifrar dados
                    byte[] mensagemBytes = decifrarComChaveSimetrica(dados_recebidos);

                    // passar para string
                    string mensagem = emString(mensagemBytes);

                    //enviar ack
                    Enviar_ACK();

                    //receber hash e  enviar hack
                    hash_recebida = Receber_Hash();


                    // integridade
                    if (Integridade_Valida(hash_recebida, mensagemBytes))
                    {
                        // mensagens normais
                        //Console.WriteLine("  (" + nickname + "): " + protocolSI.GetStringFromData());
                        streamWriter = new StreamWriter(ficheiro_sala, true);     // append true
                        streamWriter.WriteLine(nickname + " disse: " + mensagem);
                        streamWriter.Dispose();

                        // colocar a sinalização de que ha msgs novas
                        ClassePrincipalServidor.ExistemMensagensNovas(IdSala);

                        Enviar_ACK();
                    }
                    else
                    {
                        Enviar_NACK();
                    }

                    break;

                // SE FOR DO TIPO EOT É PARA FECHAR A COMUNICAÇÃO
                case ProtocolSICmdType.EOT:
                    Console.WriteLine("<O cliente {0} desconectou-se!>", clientID);

                    // avisar sala
                    if (!ficheiro_sala.Equals(""))
                    {
                        streamWriter = new StreamWriter(ficheiro_sala, true);     // append true
                        streamWriter.WriteLine(nickname + " desligou-se. ");
                        streamWriter.Dispose();
                        // colocar a sinalização de que ha msgs novas
                        ClassePrincipalServidor.ExistemMensagensNovas(IdSala);

                        // remover utilizador da sala
                        ClassePrincipalServidor.RemoverCliente(IdSala);

                        // atualiza a lista local
                        this.listSalas[IdSala].numeroClientes--;
                    }

                    Enviar_ACK();

                    break;
                }
            }

            // FECHA AS COMUNICAÇOES COM O CLIENTE
            networkStream.Dispose();
            client.Dispose();
        }
コード例 #30
0
ファイル: Client.cs プロジェクト: jodufra/aulas_si
        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();
            }
        }
コード例 #31
0
ファイル: Server.cs プロジェクト: jodufra/aulas_si
        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();
            }
        }