rmsoft1

RDTClient.cs

May 9th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.83 KB | None | 0 0
  1. //REMOVED SENSITIVE DATA.
  2. //https://rmsoftware.org
  3. //https://rms0.org/?a=r1
  4.  
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net.Sockets;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12.  
  13. namespace RDT_Client
  14. {
  15.  
  16.     #region Components
  17.     /// <summary>
  18.     /// Each command in here must be copied exactly in both client and server.
  19.     /// if not, there will be problems.
  20.     /// </summary>
  21.     public enum Command
  22.     {
  23.         /// <summary>
  24.         /// Login to the server
  25.         ///
  26.         /// Client->Server
  27.         /// </summary>
  28.         Login,
  29.         /// <summary>
  30.         /// Logout of the server
  31.         ///
  32.         /// Client->Server
  33.         /// </summary>
  34.         Logout,
  35.         /// <summary>
  36.         /// Sends a message to all clients
  37.         ///
  38.         /// Client->Server
  39.         /// Server->Client
  40.         /// </summary>
  41.         Message,
  42.         /// <summary>
  43.         /// Sends back a list of connected clients
  44.         ///
  45.         /// Client->Server
  46.         /// Server->Client
  47.         /// </summary>
  48.         List,
  49.         /// <summary>
  50.         /// Sends kick to client.
  51.         ///
  52.         /// Server->Client
  53.         /// </summary>
  54.         Kick,
  55.  
  56.         //Any other commands you want to add can go after this.
  57.         //but they must be in the exact order on both client and server.
  58.     }
  59.  
  60.     /// <summary>
  61.     /// Used to convert the data into something useful.
  62.     /// </summary>
  63.     public class DataStructure
  64.     {
  65.         public static string EncryptText(string input, string password)
  66.         {
  67.             // Get the bytes of the string
  68.             byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
  69.             byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
  70.  
  71.             // Hash the password with SHA256
  72.             passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
  73.  
  74.             byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
  75.  
  76.             string result = Convert.ToBase64String(bytesEncrypted);
  77.  
  78.             return result;
  79.         }
  80.  
  81.         public static string DecryptText(string input, string password)
  82.         {
  83.             // Get the bytes of the string
  84.             byte[] bytesToBeDecrypted = Convert.FromBase64String(input);
  85.             byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
  86.             passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
  87.  
  88.             byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
  89.  
  90.             string result = Encoding.UTF8.GetString(bytesDecrypted);
  91.  
  92.             return result;
  93.         }
  94.  
  95.         public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
  96.         {
  97.             byte[] encryptedBytes = null;
  98.  
  99.             // Set your salt here, change it to meet your flavor:
  100.             // The salt bytes must be at least 8 bytes.
  101.             byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
  102.  
  103.             using (MemoryStream ms = new MemoryStream())
  104.             {
  105.                 using (RijndaelManaged AES = new RijndaelManaged())
  106.                 {
  107.                     AES.KeySize = 256;
  108.                     AES.BlockSize = 128;
  109.  
  110.                     var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
  111.                     AES.Key = key.GetBytes(AES.KeySize / 8);
  112.                     AES.IV = key.GetBytes(AES.BlockSize / 8);
  113.  
  114.                     AES.Mode = CipherMode.CBC;
  115.  
  116.                     using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
  117.                     {
  118.                         cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
  119.                         cs.Close();
  120.                     }
  121.                     encryptedBytes = ms.ToArray();
  122.                 }
  123.             }
  124.  
  125.             return encryptedBytes;
  126.         }
  127.  
  128.         public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
  129.         {
  130.             byte[] decryptedBytes = null;
  131.  
  132.             // Set your salt here, change it to meet your flavor:
  133.             // The salt bytes must be at least 8 bytes.
  134.             byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
  135.  
  136.             using (MemoryStream ms = new MemoryStream())
  137.             {
  138.                 using (RijndaelManaged AES = new RijndaelManaged())
  139.                 {
  140.                     AES.KeySize = 256;
  141.                     AES.BlockSize = 128;
  142.  
  143.                     var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
  144.                     AES.Key = key.GetBytes(AES.KeySize / 8);
  145.                     AES.IV = key.GetBytes(AES.BlockSize / 8);
  146.  
  147.                     AES.Mode = CipherMode.CBC;
  148.  
  149.                     using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
  150.                     {
  151.                         cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
  152.                         cs.Close();
  153.                     }
  154.                     decryptedBytes = ms.ToArray();
  155.                 }
  156.             }
  157.  
  158.             return decryptedBytes;
  159.         }
  160.  
  161.         public string Username { get; private set; }
  162.         public string Message { get; private set; }
  163.         public Command command { get; private set; }
  164.  
  165.         public static byte[] getBytes(string user, string msg, Command cmd)
  166.         {
  167.             string user_S = user;
  168.             string msg_S = msg;
  169.             if (string.IsNullOrEmpty(user))
  170.             {
  171.                 user_S = "anonymous";
  172.             }
  173.             if (string.IsNullOrEmpty(msg))
  174.             {
  175.                 msg_S = "No Message";
  176.             }
  177.             //Set user and message as encryption.
  178.             byte[] b_user = Encoding.Default.GetBytes(EncryptText(user_S, "YourPassHere"));
  179.             byte[] b_msg = Encoding.Default.GetBytes(EncryptText(msg_S, "YourPassHere"));
  180.             byte[] usr_len = BitConverter.GetBytes(b_user.Length);
  181.             byte[] msg_len = BitConverter.GetBytes(b_msg.Length);
  182.             byte[] command = BitConverter.GetBytes((int)cmd);
  183.  
  184.             List<byte> byteArray = new List<byte>();
  185.             byteArray.AddRange(command);
  186.             byteArray.AddRange(usr_len);
  187.             byteArray.AddRange(msg_len);
  188.             byteArray.AddRange(b_user);
  189.             byteArray.AddRange(b_msg);
  190.             return byteArray.ToArray();
  191.  
  192.         }
  193.  
  194.  
  195.         public DataStructure(byte[] fromArray)
  196.         {
  197.             command = (Command)BitConverter.ToInt32(fromArray, 0);
  198.             int usr_len = BitConverter.ToInt32(fromArray, 4);
  199.             int msg_len = BitConverter.ToInt32(fromArray, 8);
  200.             Username = DecryptText(Encoding.Default.GetString(fromArray,12,usr_len), "YourPassHere");
  201.             Message = DecryptText(Encoding.Default.GetString(fromArray,12+usr_len,msg_len), "YourPassHere");
  202.         }
  203.  
  204.         public DataStructure()
  205.         {
  206.             //default
  207.         }
  208.     }
  209.     #endregion
  210.  
  211.     public class RDTClient
  212.     {
  213.  
  214.         #region Event
  215.         public event EventHandler<MessageEventArgs> ClientJoin;
  216.         public event EventHandler<MessageEventArgs> ClientExit;
  217.         public event EventHandler<MessageEventArgs> ChatMessage;
  218.         public event EventHandler<MessageEventArgs> ClientKick;
  219.         public event EventHandler<MessageEventArgs> ServerListReply;
  220.         #endregion
  221.  
  222.         #region Declare
  223.         /// <summary>
  224.         /// The default Server/client buffer. (Message/Command system)
  225.         /// </summary>
  226.         public byte[] clientSBuffer = new byte[32768];//32kb just for safe measure.
  227.         Socket client;
  228.         /// <summary>
  229.         /// gets the username of this client instance.
  230.         /// </summary>
  231.         public static string user { get; private set; }
  232.         #endregion
  233.  
  234.         #region Constructor
  235.         /// <summary>
  236.         /// Provides a basic client instance for this program.
  237.         /// </summary>
  238.         /// <param name="host">The address of the server to connect to.</param>
  239.         /// <param name="port">The port number the server is listening on.</param>
  240.         /// <param name="username">Your username for this instance.</param>
  241.         public RDTClient(string host, int port, string username)
  242.         {
  243.             try
  244.             {
  245.                 user = username;
  246.                 client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  247.                 client.BeginConnect(host, port, new AsyncCallback(OnConnect), null);
  248.                
  249.             }
  250.             catch (Exception)
  251.             {
  252.                
  253.                 throw;
  254.             }
  255.         }
  256.         #endregion
  257.  
  258.         #region Socket I/O Async method overides
  259.         protected virtual void OnConnect(IAsyncResult ar)
  260.         {
  261.             try
  262.             {
  263.                 client.EndConnect(ar);
  264.                 byte[] ToSend = DataStructure.getBytes(user, "test", Command.Login);
  265.                 client.BeginSend(ToSend,0,ToSend.Length,SocketFlags.None,new AsyncCallback(OnSend),null);
  266.                
  267.                
  268.             }
  269.             catch(Exception ex)
  270.             {
  271.                 Console.WriteLine(ex.Message);
  272.                 ServerDisconnect = true;
  273.             }
  274.         }
  275.  
  276.         protected virtual void OnSend(IAsyncResult ar)
  277.         {
  278.             try
  279.             {
  280.                 client.EndSend(ar);
  281.                 client.BeginReceive(clientSBuffer, 0, clientSBuffer.Length, SocketFlags.None, new AsyncCallback(onReceive), null);
  282.             }
  283.             catch(Exception)
  284.             {
  285.                
  286.             }
  287.            
  288.         }
  289.  
  290.         public void SignOut()
  291.         {
  292.             byte[] ToSend = DataStructure.getBytes(user, "Leaving", Command.Logout);
  293.             client.Send(ToSend);
  294.             client.Close();
  295.             ServerDisconnect = true;
  296.            
  297.         }
  298.         public void SignOut(string Reason)
  299.         {
  300.             byte[] ToSend = DataStructure.getBytes(user, Reason, Command.Logout);
  301.             client.Send(ToSend);
  302.             client.Close();
  303.             ServerDisconnect = true;
  304.  
  305.         }
  306.         protected virtual void onReceive(IAsyncResult ar)
  307.         {
  308.             try
  309.             {
  310.                 //Do stuff with the data accordingly.... meh.
  311.                 DataStructure DataReceived = new DataStructure(clientSBuffer);
  312.                 client.EndReceive(ar);
  313.  
  314.                 switch (DataReceived.command)
  315.                 {
  316.                     case Command.Login:
  317.                         OnClientJoin(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
  318.                         break;
  319.                     case Command.Logout:
  320.                         OnClientExit(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
  321.                         break;
  322.                     case Command.Message:
  323.                         OnChatMessage(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
  324.                         break;
  325.                     case Command.List:
  326.                         OnServerListReply(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
  327.                         break;
  328.                     case Command.Kick:
  329.                         OnClientKick(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
  330.                         break;
  331.                     default:
  332.                         break;
  333.                 }
  334.                 //after processing, keep on the lookout for more shit.
  335.                 client.BeginReceive(clientSBuffer, 0, clientSBuffer.Length, SocketFlags.None, new AsyncCallback(onReceive), null);
  336.                
  337.             }
  338.             catch (ObjectDisposedException)
  339.             {
  340.  
  341.             }
  342.             catch (Exception ex)
  343.             {
  344.                 Console.WriteLine(ex.Message);
  345.              
  346.             }
  347.         }
  348.         #endregion
  349.  
  350.         #region Invokes
  351.         protected virtual void OnClientJoin(MessageEventArgs e)
  352.         {
  353.             EventHandler<MessageEventArgs> temp = ClientJoin;
  354.             if (temp != null)
  355.             {
  356.                 temp(this,e);
  357.             }
  358.         }
  359.         protected virtual void OnClientExit(MessageEventArgs e)
  360.         {
  361.             EventHandler<MessageEventArgs> temp = ClientExit;
  362.             if (temp != null)
  363.             {
  364.                 temp(this, e);
  365.             }
  366.         }
  367.         protected virtual void OnChatMessage(MessageEventArgs e)
  368.         {
  369.             EventHandler<MessageEventArgs> temp = ChatMessage;
  370.             if (temp != null)
  371.             {
  372.                 temp(this, e);
  373.             }
  374.         }
  375.         protected virtual void OnServerListReply(MessageEventArgs e)
  376.         {
  377.             EventHandler<MessageEventArgs> temp = ServerListReply;
  378.             if (temp != null)
  379.             {
  380.                 temp(this, e);
  381.             }
  382.         }
  383.         protected virtual void OnClientKick(MessageEventArgs e)
  384.         {
  385.             EventHandler<MessageEventArgs> temp = ClientKick;
  386.             if (temp != null)
  387.             {
  388.                 temp(this, e);
  389.             }
  390.         }
  391.         #endregion
  392.         public bool ServerDisconnect { get; set; }
  393.  
  394.         public void SendMessage(string username, string message)
  395.         {
  396.             byte[] d = DataStructure.getBytes(user,message,Command.Message);
  397.             client.BeginSend(d, 0, d.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
  398.         }
  399.     }
  400.  
  401.     public class MessageEventArgs : EventArgs
  402.     {
  403.         /// <summary>
  404.         /// The text message received from the server.
  405.         /// </summary>
  406.         public string Text { get; private set; }
  407.  
  408.         public string Username { get; private set; }
  409.         public MessageEventArgs(string text,string user)
  410.         {
  411.             Username = user;
  412.             Text = text;
  413.         }
  414.     }
  415. }
Advertisement
Add Comment
Please, Sign In to add comment