コード例 #1
0
        private void Form1_Load(object sender, EventArgs e)
        {
            ProtocolSI protocolSI = new ProtocolSI(); //instanciar protocolo de comunicaçao

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

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

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

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

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

                //comfirmarrececao
                byte[] IVcomfirmreceived = protocolSI.Make(ProtocolSICmdType.DATA, "true");
                networkStream.Write(IVcomfirmreceived, 0, IVcomfirmreceived.Length);
            }
        }
コード例 #2
0
ファイル: Form_Autenticar.cs プロジェクト: RuiPenetra/spks
        public static byte[] decifrarDadosServidor()
        {
            //RECEBER DADOS
            byte[] dados_recebidos = protocolSI.GetData();

            //DECIFRAR DADOS
            dadosDecifrados = decifrarComChaveSimetrica(dados_recebidos);

            return(dadosDecifrados);
        }
コード例 #3
0
        private void btnVerifySignature_Click(object sender, EventArgs e)
        {
            try {
                netStream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                var signature = symmetricsSI.Decrypt(protocol.GetData());

                bool status = rsaServer.VerifyData(File.ReadAllBytes(FILE), new SHA256CryptoServiceProvider(), signature);
                MessageBox.Show(status ? "Assinatura é válida" : "Assinatura não é válida");
                lblVerify.Visible = true;
            } catch (Exception ex) {
                MessageBox.Show("ERROR: " + ex.Message);
                throw;
            }
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: RuiPenetra/spks
        private byte[] Receber_Hash()
        {
            // receber a hash
            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);

            if (protocolSI.GetCmdType() == ProtocolSICmdType.NORMAL)
            {
                // ler hash
                hash_recebida = protocolSI.GetData();

                // decifra-la com chave simetrica
                byte[] hash_recebida_decifrada = decifrarComChaveSimetrica(hash_recebida);

                Enviar_ACK();

                return(hash_recebida_decifrada);
            }

            return(null);
        }
コード例 #5
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);
            }
        }
コード例 #6
0
        /// <summary>
        /// IMPORTANTE: a cada RECEÇÃO deve seguir-se, obrigatóriamente, um ENVIO de dados
        /// IMPORTANT: each network .Read() must be fallowed by a network .Write()
        /// </summary>
        static void Main(string[] args)
        {
            byte[]        msg;
            IPEndPoint    listenEndPoint;
            TcpListener   server    = null;
            TcpClient     client    = null;
            NetworkStream netStream = null;
            ProtocolSI    protocol  = null;

            try
            {
                Console.WriteLine("SERVER");

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

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


                #endregion

                Console.WriteLine(SEPARATOR);

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

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

                Console.WriteLine(SEPARATOR);

                #region Exchange Data (Unsecure channel)

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

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

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

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

                #endregion

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

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

                    SymmetricsSI symmetric = new SymmetricsSI(aes);

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

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

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

            Console.WriteLine(SEPARATOR);
            Console.Write("End: Press a key...");
            Console.ReadKey();
        }
コード例 #7
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);
        }
コード例 #8
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
            }
コード例 #9
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();
        }
コード例 #10
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");
        }
コード例 #11
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
コード例 #12
0
ファイル: Form1.cs プロジェクト: PSI17JoaoP/Projeto_TS_1617
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUtilizador.Text.Length > 0 && txtPassword.Text.Length > 0)
                {
                    // transforma num array de bytes, recorrendo ao protocol, envia o marcador e o nome de utilizador, o mesmo para pass
                    byte[] usernameLogin     = Encoding.UTF8.GetBytes(txtUtilizador.Text.Trim());
                    byte[] passwordHashLogin = Encoding.UTF8.GetBytes(txtPassword.Text);
                    //saca os bytes do texto.

                    byte[] serverFeedback = null;

                    //utilizar encriptação assimetrica;

                    //Escreve na network stream (forma de comunicarem, imposta pela comunicação, tcp, é onde se trata de enviar dados receber dados.

                    //vai para a parte do program, e faz um read() no lado do servidor.

                    byte[] usernameEncriptado     = protocolSI.Make(ProtocolSICmdType.DATA, servicoCriptoSimetrico.EncryptDados(usernameLogin, usernameLogin.Length));
                    byte[] passwordHashEncriptada = protocolSI.Make(ProtocolSICmdType.DATA, servicoCriptoSimetrico.EncryptDados(passwordHashLogin, passwordHashLogin.Length));

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

                    //faz exatamente a mesma parte de cima e vai servidor. (((Utilizar a Hash)))
                    networkStream.Write(passwordHashEncriptada, 0, passwordHashEncriptada.Length);

                    //fica à escuta para receber a mensagem de sucesso.
                    //ack --> sao acknoledgments, quando recebe alguma coisa tem de dizer que recebeu, é o feedback
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    //vai por a msg no buffer, que veio do lado do servidor.
                    serverFeedback = protocolSI.GetData();
                    //tranforma em string a resposta

                    byte[] serverFeedbackBytes  = servicoCriptoSimetrico.DecryptDados(serverFeedback);
                    string serverFeedbackString = Encoding.UTF8.GetString(serverFeedbackBytes);

                    if (serverFeedbackString == "SUCCESSFUL")
                    {
                        gbMenu.Enabled  = true;
                        gbMenu.Visible  = true;
                        gbLogin.Enabled = false;
                        //ativa os formulários para uso.
                    }

                    else if (serverFeedbackString == "FAILED")
                    {
                        //caso o login não seja bem sucedido, envia uma mensagem de erro.
                        MessageBox.Show("O username e password introduzidos são incorretos", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                else
                {
                    MessageBox.Show("Preencha todos os campos para efeutuar login", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            //caso tenha alguma excepção.
            catch (Exception)
            {
                //throw;
                MessageBox.Show("Erro encontrado. A encerrar", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ShutDown();
                StopConnection();
            }
        }
コード例 #13
0
        public bool Login(string username, string password)
        {
            string credenciais = username + " " + password;

            byte[] msgCifrada = Cifra(credenciais);

            // Envia os dados para o servidor
            Send(msgCifrada, ProtocolSICmdType.USER_OPTION_3);

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

                int    state = -1;
                string msg   = "";

                // Enquanto nao receber um ACK recebe o que o servidor envia
                while (protocolSI.GetCmdType() != ProtocolSICmdType.ACK)
                {
                    if (protocolSI.GetCmdType() == ProtocolSICmdType.USER_OPTION_3)
                    {
                        byte[] receivedData = protocolSI.GetData();

                        // Decifra a mensagem
                        msg = Decifra(receivedData);

                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                    }
                }

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

                if (!ValidacaoDados(msg, hash))
                {
                    Console.WriteLine("Hash não é igual");
                    return(false);
                }

                state = int.Parse(msg);

                switch (state)
                {
                // Faz login
                case 0:
                    return(true);

                // Password errada
                case 1:
                    MessageBox.Show("Password errada");
                    break;

                // Utilizador nao existe ou nome de utilizador errado
                case 2:
                    DialogResult resposta = MessageBox.Show("Deseja criar uma conta nova?", "Conta nao existe", MessageBoxButtons.YesNo);
                    if (resposta == DialogResult.Yes)
                    {
                        // Envia os dados para o servidor
                        byte[] response = protocolSI.Make(ProtocolSICmdType.USER_OPTION_4, msgCifrada);
                        networkStream.Write(response, 0, response.Length);
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(false);
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: PSI17JoaoP/Projeto_TS_1617
        private static void ServerLogin()
        {
            byte[] usernameClientEncriptado = null;
            byte[] passwordHashEncriptada   = null;
            byte[] usernameClientBytes      = null;
            byte[] passwordHashBytes        = null;
            string usernameClient           = null;
            string passwordHash             = null;


            byte[] bytesFeedback    = null;
            string mensagemFeedback = null;

            byte[] mensagemFeedbackBytes = null;

            byte[] secretkey = null;
            byte[] iv        = null;
            byte[] ack       = null;

            ProtocolSICmdType protocolTipoRespostaSecretKey;
            ProtocolSICmdType protocolTipoRespostaIV;

            //----------------
            string key = null;

            byte[] keyBytes = null;
            //----------------

            try
            {
                do
                {
                    //o outro inicia o processo, estabelece a ligação com o cliente do outro lado se houver pedidos, se não houver fica parado, à espera.
                    tcpClient = tcpListener.AcceptTcpClient();
                    //aceita o pedido pendente, e devolve o tcpClient, que é, é informação sobre o cliente que está do outro lado.
                    //escreve a mensagem de sucesso de ligação.
                    Console.WriteLine("Connection Successful!");

                    //networkstream --> canal de comunicação.
                    //o tcpClient,GetStream() -> Vai buscar a networkstream criada pelo cliente.
                    networkStream = tcpClient.GetStream();
                    //diz que já pode mandar mensagens, que está preparado.
                    Console.WriteLine("Waiting for message ...");

                    key = servicoAssinaturas.ObterPublicKey();

                    //string --> vai ao objeto servicoAssinaturas do tipo ServiceCriptoAssimetrica, para obter a public key.

                    keyBytes = protocolSI.Make(ProtocolSICmdType.PUBLIC_KEY, key);
                    //vai fazer um buffer do tipo public key, com a public key recebida anteriormente.
                    networkStream.Write(keyBytes, 0, keyBytes.Length);
                    //vai enviar uma mensagem para o cliente, com o buffer da public key.
                    //o cliente vai receber do seu lado, a public key. linha 99
                    Console.WriteLine("Public Key Shared");

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

                        protocolTipoRespostaSecretKey = protocolSI.GetCmdType();

                        if (protocolTipoRespostaSecretKey == ProtocolSICmdType.SECRET_KEY)
                        {
                            secretkey = servicoAssinaturas.DecriptarDados(protocolSI.GetData());
                            Console.WriteLine("Received Secret Key");

                            ack = protocolSI.Make(ProtocolSICmdType.ACK);
                            networkStream.Write(ack, 0, ack.Length);
                            Console.WriteLine("Acknowlegment (ACK) Sent");

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

                                protocolTipoRespostaIV = protocolSI.GetCmdType();

                                if (protocolTipoRespostaIV == ProtocolSICmdType.IV)
                                {
                                    iv = servicoAssinaturas.DecriptarDados(protocolSI.GetData());
                                    Console.WriteLine("Received IV");

                                    servicoCriptografiaSimetrica = new ServiceCriptoSimetrica(secretkey, iv);
                                }
                            }while (protocolTipoRespostaIV != ProtocolSICmdType.IV);
                        }
                    }while (protocolTipoRespostaSecretKey != ProtocolSICmdType.SECRET_KEY);

                    do
                    {
                        //sempre que existe um write do lado do cliente, o código vai para a parte do servidor e efetua a leitura.
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                        //vai arranjar a string do array de bytes dos dados que ele recebeu do buffer.
                        usernameClientEncriptado = protocolSI.GetData();

                        usernameClientBytes = servicoCriptografiaSimetrica.DecryptDados(usernameClientEncriptado);

                        usernameClient = Encoding.UTF8.GetString(usernameClientBytes);

                        //Envia mensagem cmd,a dizer que o username foi recebido.
                        Console.WriteLine("Client Login Attempt -> " + usernameClient);

                        //Vai a ler a password no buffer do protocol SI.
                        networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                        //vai arranjar um array de bytes com a password, através do buffer recebido.
                        passwordHashEncriptada = protocolSI.GetData();

                        passwordHashBytes = servicoCriptografiaSimetrica.DecryptDados(passwordHashEncriptada);

                        passwordHash = Encoding.UTF8.GetString(passwordHashBytes);

                        /*Console.WriteLine("Client Password Hash Received -> " + passwordHash);*/
                        //Escreve a dizer que recebeu a palavra-passe.


                        //inicia a parte da base de dados. Onde vai verificar o username e a hash da password.
                        //Database
                        connect = new SqlConnection();
                        connect.ConnectionString = Properties.Settings.Default.connectionString;

                        connect.Open();

                        String     sql = "SELECT * FROM Users WHERE Username = @username";
                        SqlCommand cmd = new SqlCommand();
                        cmd.CommandText = sql;

                        //o parâmetro serve para evitar o sql injection.
                        //adiciona o parâmetro ao comando sql
                        //Igual a connection do comando à Connection de cima para saber para onde deverá enviar a query.
                        //vai fazerum reader para leitura dos dados obtidos pela execução da query.*/

                        SqlParameter param = new SqlParameter("@username", usernameClient);
                        cmd.Parameters.Add(param);
                        cmd.Connection = connect;

                        SqlDataReader reader = cmd.ExecuteReader();

                        if (reader.HasRows)
                        {
                            //se o utilizador for válido vai obter as passwords e a hash e tudo, os diversos resultados da query.
                            // devolve o salt que vai ser utilizado para fazer salted hash a password introduzida pelo cliente ao inciar sessão.
                            //gerar a saltedhash, recorrendo a hash devolvida e à password inserida.
                            //fecha a conexão da base de dados.


                            reader.Read();

                            byte[] saltedPasswordHashStored = (byte[])reader["Password"];
                            byte[] saltStored = (byte[])reader["Salt"];
                            byte[] saltedhash = GenerateSaltedHash(Encoding.UTF8.GetBytes(passwordHash), saltStored);

                            connect.Close();


                            //Verifica se a saltedhash gerada é igual a saltedhash registada na base de dados
                            if (saltedhash.SequenceEqual(saltedPasswordHashStored))
                            {
                                //se for igual inicializa o a mensagemfeedback = successful
                                //vai transformar a string num buffer para enviar para a network stream.
                                //enviar a mensagem, o buffer que contem o feedback do login.
                                //ao escrever vai para o cliente, que estava À espera de receber um feedback sobre o login.
                                //o cliente estava parado, agora continua com o server de forma síncrona.
                                //mensagem a dizer o feedback.

                                mensagemFeedback      = "SUCCESSFUL";
                                mensagemFeedbackBytes = Encoding.UTF8.GetBytes(mensagemFeedback);
                                bytesFeedback         = protocolSI.Make(ProtocolSICmdType.DATA, servicoCriptografiaSimetrica.EncryptDados(mensagemFeedbackBytes, mensagemFeedbackBytes.Length));
                                networkStream.Write(bytesFeedback, 0, bytesFeedback.Length);
                                Console.WriteLine("Login Attempt -> " + mensagemFeedback);
                            }
                            else
                            {
                                //se as hash's forem diferentes o feedback fica com erro.
                                //cria um array de bytes, do tipo data, contendo o feedback da mensagem.
                                //O servidor vai enviar através da networkStream(canal de comunicação), o feedback de erro/insucesso na tentativa de login
                                //escreve na consola, que ocorreu um erro na tentativa de login.

                                mensagemFeedback      = "FAILED";
                                mensagemFeedbackBytes = Encoding.UTF8.GetBytes(mensagemFeedback);
                                bytesFeedback         = protocolSI.Make(ProtocolSICmdType.DATA, servicoCriptografiaSimetrica.EncryptDados(mensagemFeedbackBytes, mensagemFeedbackBytes.Length));
                                networkStream.Write(bytesFeedback, 0, bytesFeedback.Length);
                                Console.WriteLine("Login Attempt -> " + mensagemFeedback);
                            }

                            //--------
                        }
                        else
                        {
                            //se as hash's forem diferentes o feedback fica com erro.
                            //cria um array de bytes, do tipo data, contendo o feedback da mensagem.
                            //O servidor vai enviar através da networkStream(canal de comunicação), o feedback de erro/insucesso na tentativa de login
                            //escreve na consola, que ocorreu um erro na tentativa de login.

                            mensagemFeedback      = "FAILED";
                            mensagemFeedbackBytes = Encoding.UTF8.GetBytes(mensagemFeedback);
                            bytesFeedback         = protocolSI.Make(ProtocolSICmdType.DATA, servicoCriptografiaSimetrica.EncryptDados(mensagemFeedbackBytes, mensagemFeedbackBytes.Length));
                            networkStream.Write(bytesFeedback, 0, bytesFeedback.Length);
                            Console.WriteLine("Login Attempt -> " + mensagemFeedback);
                        }
                    }while (mensagemFeedback != "SUCCESSFUL");
                    //faz enquanto não for bem sucedido.
                }while (mensagemFeedback != "SUCCESSFUL");
                //faz enquanto não for bem sucedido.
            }

            //Para o caso de ocorrerem excepções.
            //Chama o procedimento StopServer() e fecha as ligações que estiverem abertas.
            catch (Exception)
            {
                //throw;
                StopServer();
            }
        }
コード例 #15
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();
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: PSI17JoaoP/Projeto_TS_1617
        //------------

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

            protocolSI = new ProtocolSI();

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

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

                    requestClientBytes = servicoCriptografiaSimetrica.DecryptDados(requestClient);

                    requestClienteDecriptada = Encoding.UTF8.GetString(requestClientBytes);

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

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

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

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

                        requestFileBytes = servicoCriptografiaSimetrica.DecryptDados(requestFile);

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

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

                else
                {
                    //se não estiver conectado pára o servidor.
                    StopServer();
                    break;
                }
            }
        }
コード例 #17
0
        static void Main(string[] args)
        {
            protocolSI = new ProtocolSI();
            NetworkStream networkStream = null;
            TcpListener   tcpListener   = null;
            TcpClient     tcpClient     = null;

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

                Console.WriteLine("Starting Server... ");

                tcpListener.Start();

                Console.WriteLine("Waiting for connections...");
                tcpClient = tcpListener.AcceptTcpClient();

                Console.WriteLine("Client Connected..");

                networkStream = tcpClient.GetStream();

                int bytesRead = 0;

                #region Receive String Message



                int bufferSize = tcpClient.ReceiveBufferSize;
                //byte[] buffer = new byte[bufferSize];

                bytesRead = networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                byte[] packet = protocolSI.GetData();

                if (protocolSI.GetCmdType() == = ProtocolSICmdType.DATA)
                {
                }

                Console.WriteLine(Encoding.UTF8.GetString(packet));



                // enviar string a dizer ok
                byte[] ack = Encoding.UTF8.GetBytes("OK");
                networkStream.Write(ack, 0, ack.Length);

                #endregion
            } catch (Exception) {
                throw;
            } finally {
                if (networkStream != null)
                {
                    networkStream.Close();
                }
                if (tcpListener != null)
                {
                    tcpListener.Stop();
                }
                if (tcpClient != null)
                {
                    tcpClient.Close();
                }
            }
            Console.WriteLine("Servidor");
            Console.ReadKey();
        }
コード例 #18
0
ファイル: Form_Autenticar.cs プロジェクト: RuiPenetra/spks
        public Form_Autenticar()
        {
            InitializeComponent();

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

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

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


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

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

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

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

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

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

                //ENVIAR PARA O SERVIDOR

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

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

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

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

                        case ProtocolSICmdType.IV:

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

                        case ProtocolSICmdType.SYM_CIPHER_DATA:

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

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

                            Enviar_ACK();

                            break;

                        case ProtocolSICmdType.NACK:
                            MessageBox.Show("Ocorreu um erro. Por favor reinicie a aplicação! ");
                            break;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Não foi possivel conectar ao servidor. Tente outra vez! ");
                    return;
                }
            }
            catch (SocketException)
            {
                MessageBox.Show("Não foi possivel conectar ao servidor. Tente outra vez! ");
                return;
            }
        }
コード例 #19
0
ファイル: Menu.cs プロジェクト: simaopina/Projeto-TS
        private void btnPedirFicheiro_Click(object sender, EventArgs e)
        {
            byte[] mensagem = protocolSI.Make(ProtocolSICmdType.DATA, "file");
            networkStream.Write(mensagem, 0, mensagem.Length);


            String imagem1 = listViewFicheiros.SelectedItems[0].Text;

            byte[] mensagemFicheiro = protocolSI.Make(ProtocolSICmdType.DATA, imagem1);

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

            int bytesread = 0;

            int buffersize = 1024;

            byte[] packet;

            string copiaFilePath = Path.Combine(Environment.CurrentDirectory, @"Files\");

            networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
            byte[] signature = null;

            if (protocolSI.GetCmdType() == ProtocolSICmdType.DIGITAL_SIGNATURE)
            {
                signature = protocolSI.GetData();
            }



            using (FileStream copiaFileStream = new FileStream(copiaFilePath + imagem1, FileMode.CreateNew, FileAccess.ReadWrite))
            {
                do
                {
                    networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);

                    if (protocolSI.GetCmdType() == ProtocolSICmdType.USER_OPTION_8)
                    {
                        copiaFileStream.Write(protocolSI.GetData(), 0, protocolSI.GetData().Length);

                        //Enviar ack
                        packet = protocolSI.Make(ProtocolSICmdType.ACK);
                        networkStream.Write(packet, 0, packet.Length);
                    }
                } while (protocolSI.GetCmdType() != ProtocolSICmdType.EOF);

                copiaFileStream.Seek(0, SeekOrigin.Begin);
                byte[] fullimage = new byte[copiaFileStream.Length];
                copiaFileStream.Read(fullimage, 0, fullimage.Length);
                bool r;
                using (SHA512 sha = SHA512.Create())
                {
                    r = rsa.VerifyData(fullimage, sha, signature);
                }

                if (r)
                {
                    MessageBox.Show("Mensagem corrompida");
                }
            }


            if (imagem1 != null)
            {
                string copyFilePath = pbxFoto.ImageLocation = Path.Combine(Environment.CurrentDirectory, @"Files\" + imagem1);

                /*packet = protocolSI.Make(ProtocolSICmdType.USER_OPTION_1, imagem1);
                 * networkStream.Write(packet, 0, packet.Length);*/

                MessageBox.Show("copiar");
            }


            // FileStream CopyFileStream = new FileStream(copyFilePath, FileMode.CreateNew);


            //CopyFileStream.Write()


            //// originalFileStream.Close();
            // CopyFileStream.Close();

            MessageBox.Show("Copiado com sucesso!");
        }
コード例 #20
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);*/


            //}
        }
コード例 #21
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();
        }
コード例 #22
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();
            }
        }
コード例 #23
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();
        }