public static void addSession(session ns) { sessionsList.Add(ns); }
public static void ReceiveMessage() { while (true) { try { byte[] data = new byte[64]; StringBuilder builder = new StringBuilder(); int bytes = 0; do { bytes = stream.Read(data, 0, data.Length); builder.Append(Encoding.Unicode.GetString(data, 0, bytes)); }while (stream.DataAvailable); string message = builder.ToString(); serverMessage sm = JsonConvert.DeserializeObject <serverMessage>(message); switch (sm.type) { case "messageerror": Console.WriteLine("Ошибка, сообщение невозможно отправить: " + sm.data); break; case "usersonline": string[] usersList = sm.data.Split('|'); Console.WriteLine("Список пользователей онлайн:"); for (int i = 1; i <= usersList.Length; i++) { Console.WriteLine(i.ToString() + ". " + usersList[i - 1]); } break; case "rejectconnection": Console.WriteLine("Невозможно установить соединение: " + sm.data); break; case "connections": string[] onlineConnections = sm.data.Split('|'); if (onlineConnections[0] == "") { Console.WriteLine("Подключения отсутствуют"); break; } Console.WriteLine("Текущие подключения:"); for (int i = 0; i < onlineConnections.Length; i++) { Console.WriteLine(i + ". " + onlineConnections[i]); } break; case "alreadydisconnected": Console.WriteLine("Пользователь " + sm.data + " не подключен"); break; case "removeconnection": Console.WriteLine("Пользователь " + sm.data + " отключен"); break; case "connectionremoved": Console.WriteLine("Пользователь " + sm.data + " отключился"); break; case "acceptconnection": Console.WriteLine("Пользователь " + sm.data + " устанавливает соединение..."); clientMessage cm = new clientMessage() { type = "accept", data = sm.data }; string json = JsonConvert.SerializeObject(cm); Console.WriteLine("JSON : " + json); sendMessage(json); break; case "accept": string[] keys = sm.data.Split('|'); string mySecretKey = keys[1]; string companionPublicKey = keys[2]; string[] mscdataString = mySecretKey.Split(' '); string[] cpkdataString = companionPublicKey.Split(' '); double[] mscdata = new double[mscdataString.Length]; double[] cpkdata = new double[cpkdataString.Length]; for (int i = 0; i < mscdataString.Length; i++) { mscdata[i] = Int32.Parse(mscdataString[i]); cpkdata[i] = Int32.Parse(cpkdataString[i]); } Matrix <double> msc = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(mscdata.Length, 1, mscdata); Matrix <double> cpk = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cpkdata.Length, 1, cpkdata); //Console.WriteLine("MY SEC: " + msc.ToString()); //Console.WriteLine("IT PUB: " + cpk.ToString()); msc = msc.Transpose(); Matrix <double> sKey = msc.Multiply(cpk); sKey = sKey.Modulus(50); commonSecretKey = (int)sKey[0, 0]; //Console.WriteLine("RES: " + Convert.ToString(commonSecretKey)); string Digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; byte[] data123 = BitConverter.GetBytes(commonSecretKey); BigInteger intData = 0; for (int i = 0; i < data123.Length; i++) { intData = intData * 256 + data123[i]; } string result = ""; while (intData > 0) { int remainder = (int)(intData % 58); intData /= 58; result = Digits[remainder] + result; } for (int i = 0; i < data123.Length && data123[i] == 0; i++) { result = '1' + result; } csk = result; Console.WriteLine("СГЕНЕРИРОВАН СЕКРЕТНЫЙ КЛЮЧ: " + csk); Console.WriteLine("Установлена сессия с пользователем " + sm.name); RC4Cipher newCipher = new RC4Cipher(csk, 19); session newSession = new session() { name = sm.name, cipher = newCipher }; addSession(newSession); break; default: string fp = sm.type.Split('|')[0]; string sp = sm.type.Split('|')[1]; session rs = GetSession(sp); if (fp == "message") { Console.WriteLine(sp + "(шифрованное): " + sm.data); string decodemessage = rs.cipher.encode(sm.data); Console.WriteLine(sp + "(дешифрованное): " + decodemessage); } break; } } catch (Exception e) { Console.WriteLine("Подключение прервано! " + e); Console.ReadLine(); Disconnect(); } } }
static void handleMessage() { while (true) { clientMessage cm; string json; string command = Console.ReadLine(); switch (command) { case "help": Console.WriteLine("Список доступных команд:\n1. online - Список пользователей онлайн\n2. connect - установить соединение с " + "пользователем\n4. send - отправка сообщения пользователю\n5. connections - Активные соединения\n6. disconnect - Разорвать " + "соединение с пользователем"); break; case "online": cm = new clientMessage() { type = "usersonline" }; json = JsonConvert.SerializeObject(cm); sendMessage(json); break; case "connect": Console.WriteLine("Введите имя пользователя, к которому хотите подключиться:"); string connectingUser = Console.ReadLine(); if (connectingUser == userName) { Console.WriteLine("Зачем вам коннектиться с самим собой? Вы шо, ебобо?"); break; } cm = new clientMessage() { type = "connect", data = connectingUser }; json = JsonConvert.SerializeObject(cm); sendMessage(json); break; case "send": Console.WriteLine("Введите пользователя, кому хотите отправить сообщение:"); string toUser = Console.ReadLine(); session sendsession = GetSession(toUser); if (sendsession.name == null) { Console.WriteLine("C таким пользователем у вас не установлена сессия. Отправка сообщений невозможна."); break; } Console.WriteLine("Введите сообщение: "); string message = Console.ReadLine(); message = sendsession.cipher.encode(message); Console.WriteLine("Шифрованное сообщение: " + message); cm = new clientMessage() { type = "message|" + toUser, data = message }; json = JsonConvert.SerializeObject(cm); sendMessage(json); break; case "connections": cm = new clientMessage() { type = "connections" }; json = JsonConvert.SerializeObject(cm); sendMessage(json); break; case "disconnect": Console.WriteLine("С каким пользователем хотите разорвать соединение?"); string disconnectUser = Console.ReadLine(); cm = new clientMessage() { type = "disconnect", data = disconnectUser }; json = JsonConvert.SerializeObject(cm); sendMessage(json); break; default: Console.WriteLine("Неизвестная команда, введите 'help' для получения списка доступных команд."); break; } } }