static void Main(string[] args) { TcpListener tcpl = null; TcpClient tcpc = null; NetworkStream stream = null; try { tcpl = new TcpListener(IPAddress.Any, 9999); tcpl.Start(); Console.Write("Waiting for client... "); tcpc = tcpl.AcceptTcpClient(); Console.WriteLine("ok"); stream = tcpc.GetStream(); ProtocolSI protocol = new ProtocolSI(); ProtocolSICmdType command; byte[] packet; do { stream.Read(protocol.Buffer, 0, protocol.Buffer.Length); command = protocol.GetCmdType(); switch (protocol.GetCmdType()) { case ProtocolSICmdType.NORMAL: Console.WriteLine("inteiro: " + protocol.GetIntFromData().ToString()); break; case ProtocolSICmdType.DATA: Console.WriteLine("string: " + protocol.GetStringFromData()); break; case ProtocolSICmdType.EOT: Console.WriteLine("end"); break; default: Console.WriteLine("not expected"); break; } } while (command != ProtocolSICmdType.EOT); packet = protocol.Make(ProtocolSICmdType.ACK); stream.Write(packet, 0, packet.Length); } catch (Exception e) { Console.WriteLine(e.Message); throw; } finally { Console.WriteLine("disconnected"); if (stream != null) stream.Dispose(); if (tcpc != null) tcpc.Close(); if (tcpl != null) tcpl.Stop(); } }
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"); }
static void Main(string[] args) { Console.WriteLine(" == SERVER == "); Console.Title = "SERVER"; TcpListener listener = null; TcpClient client = null; NetworkStream stream = null; ProtocolSI protocol = null; byte[] packet = null; int bytesRead; try { protocol = new ProtocolSI(); listener = new TcpListener(IPAddress.Any, PORT); listener.Start(); client = listener.AcceptTcpClient(); stream = client.GetStream(); ProtocolSICmdType cmd; do { Console.WriteLine("Waiting for client.."); stream.Read(protocol.Buffer, 0, protocol.Buffer.Length); cmd = protocol.GetCmdType(); switch (cmd) { case ProtocolSICmdType.NORMAL: Console.WriteLine($"Recebido: {protocol.GetIntFromData()}"); break; case ProtocolSICmdType.DATA: Console.WriteLine($"Recebido: {protocol.GetStringFromData()}"); break; case ProtocolSICmdType.EOT: Console.WriteLine("Recebido: EOT"); break; default: Console.WriteLine("Opção inválida."); break; } packet = protocol.Make(ProtocolSICmdType.ACK); // enviar o ACK stream.Write(packet, 0, packet.Length); Console.WriteLine("ack enviado"); } while (cmd != ProtocolSICmdType.EOT); Console.WriteLine("Comunicação Terminada. <tecla para terminar>"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } finally { if (client != null) { client.Dispose(); } if (stream != null) { stream.Dispose(); } if (listener != null) { listener.Stop(); } } Console.ReadKey(); }