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(); } }
public Chat MakeChat() { NetUtils.Write(stream, Crypto.AES256Encrypt(key, "Chat")); Chat chat = new Chat(stream, key, node); Program.chats.Add(chat); return(chat); }
public Sender(Node node, int receiveTimeOut = 120000) //120 sec { tcpClient = new TcpClient(); tcpClient.ReceiveTimeout = receiveTimeOut; tcpClient.Connect(IPAddress.Parse(node.IP), node.Port); stream = tcpClient.GetStream(); this.node = node; //Establish secure connection byte[] rsaKey = NetUtils.Read(stream); //Generate a key for AES256 new Random().NextBytes(key); NetUtils.Write(stream, Crypto.RSAEncrypt(Encoding.UTF8.GetString(rsaKey), key)); //Register NetUtils.Write(stream, Crypto.AES256Encrypt(key, $"{Program.settings.Name} {Program.settings.Port}")); }
public string Send(string data) { NetUtils.Write(stream, Crypto.AES256Encrypt(key, data)); return(Crypto.AES256Decrypt(key, NetUtils.Read(stream))); }