public static string Decrypt(string Data, byte[] Key, byte[] IV) { try { MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(Data)); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). CryptoStream csDecrypt = new CryptoStream(msDecrypt, new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), CryptoStreamMode.Read); // Create buffer to hold the decrypted data. byte[] fromEncrypt = new byte[Data.Length]; // Read the decrypted data out of the crypto stream // and place it into the temporary buffer. csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); //Convert the buffer into a string and return it. string ReturnValue = new ASCIIEncoding().GetString(fromEncrypt); if (ReturnValue.Contains("\0\0\0")) { ReturnValue = ReturnValue.Remove(ReturnValue.IndexOf("\0\0\0")); } return ReturnValue; } catch (CryptographicException e) { Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); return null; } }
private void HandleClientComm(object client) { // Cast Client TcpClient tcpClient = (TcpClient)client; // Add Client string dictionaryKey = Guid.NewGuid().ToString(); if (ClientHandler.Clients.ContainsKey(dictionaryKey)) ClientHandler.Clients.Remove(dictionaryKey); ClientHandler.Clients.Add(dictionaryKey, tcpClient); try { NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[MessageSize]; while (true) { int bytesRead; try { // Blocks until message is sent to server bytesRead = clientStream.Read(message, 0, MessageSize); } catch (Exception exception) { // Socket Error Occurred Console.WriteLine(exception.ToString()); break; } // Client Disconnected if (bytesRead == 0) break; // Message Received string messagesString = new ASCIIEncoding().GetString(message, 0, bytesRead); // Validate Message if (String.IsNullOrEmpty(messagesString) || !messagesString.Contains(EndTerminator)) continue; // Handle Message(s) foreach (string messageString in Regex.Split(messagesString, EndTerminator) .Where(messageString => !String.IsNullOrEmpty(messageString))) { ThreadPool.QueueUserWorkItem(ClientHandler.HandleCommand, new Message(dictionaryKey, messageString)); } } } catch (Exception exception) { Console.WriteLine(exception.ToString()); } finally { try { if (ClientHandler.Clients.ContainsKey(dictionaryKey)) ClientHandler.Clients.Remove(dictionaryKey); if (ClientHandler.PlayerOne.ContainsKey(dictionaryKey)) ClientHandler.PlayerOne.Remove(dictionaryKey); if (ClientHandler.PlayerTwo.ContainsKey(dictionaryKey)) ClientHandler.PlayerTwo.Remove(dictionaryKey); tcpClient.Close(); } catch (Exception exception) { Console.WriteLine(exception.ToString()); } } }