Example #1
0
        void AcceptClient(TcpClient client)
        {
            string ip = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();

            try
            {
                NetworkStream stream = client.GetStream();

                //Establish secure connection
                byte[] key     = new byte[32];
                var    keysRSA = Crypto.RSACreate();

                NetUtils.Write(stream, Encoding.UTF8.GetBytes(keysRSA.publicKey));
                key = Crypto.RSADecrypt(keysRSA.privateKey, NetUtils.Read(stream));

                //Register node
                string[] requestReg = Crypto.AES256Decrypt(key, NetUtils.Read(stream)).Split(" ");
                Node     node;
                if (Utils.ContainsNode(requestReg[0], ip, int.Parse(requestReg[1])))
                {
                    node = Utils.GetNode(requestReg[0], ip, int.Parse(requestReg[1]));
                }
                else
                {
                    node = new Node()
                    {
                        IP = ip, Name = requestReg[0], Port = int.Parse(requestReg[1])
                    };
                    new Sender(node).Send("Ping"); //if it throws an exception, the connection will close
                    Program.settings.Nodes.Add(node);
                    Utils.SaveSettings();
                }
                Console.WriteLine(ip + " just connected and secure connection was established");

                while (true)
                {
                    try
                    {
                        String msg = Crypto.AES256Decrypt(key, NetUtils.Read(stream));
                        if (msg == "Chat")
                        {
                            Chat chat = new Chat(stream, key, node);
                            Program.chats.Add(chat);
                            break;
                        }
                        else
                        {
                            NetUtils.Write(stream, Crypto.AES256Encrypt(key, ParseRequest(msg, client)));
                        }
                    }
                    catch (Exception) { break; }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Connection with " + ip + " was closed");
                client.Close();
            }
        }
Example #2
0
 public string Send(string data)
 {
     NetUtils.Write(stream, Crypto.AES256Encrypt(key, data));
     return(Crypto.AES256Decrypt(key, NetUtils.Read(stream)));
 }