Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //REMOVED SENSITIVE DATA.
- //https://rmsoftware.org
- //https://rms0.org/?a=r1
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net.Sockets;
- using System.Security.Cryptography;
- using System.Text;
- namespace RDT_Client
- {
- #region Components
- /// <summary>
- /// Each command in here must be copied exactly in both client and server.
- /// if not, there will be problems.
- /// </summary>
- public enum Command
- {
- /// <summary>
- /// Login to the server
- ///
- /// Client->Server
- /// </summary>
- Login,
- /// <summary>
- /// Logout of the server
- ///
- /// Client->Server
- /// </summary>
- Logout,
- /// <summary>
- /// Sends a message to all clients
- ///
- /// Client->Server
- /// Server->Client
- /// </summary>
- Message,
- /// <summary>
- /// Sends back a list of connected clients
- ///
- /// Client->Server
- /// Server->Client
- /// </summary>
- List,
- /// <summary>
- /// Sends kick to client.
- ///
- /// Server->Client
- /// </summary>
- Kick,
- //Any other commands you want to add can go after this.
- //but they must be in the exact order on both client and server.
- }
- /// <summary>
- /// Used to convert the data into something useful.
- /// </summary>
- public class DataStructure
- {
- public static string EncryptText(string input, string password)
- {
- // Get the bytes of the string
- byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
- byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
- // Hash the password with SHA256
- passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
- byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
- string result = Convert.ToBase64String(bytesEncrypted);
- return result;
- }
- public static string DecryptText(string input, string password)
- {
- // Get the bytes of the string
- byte[] bytesToBeDecrypted = Convert.FromBase64String(input);
- byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
- passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
- byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
- string result = Encoding.UTF8.GetString(bytesDecrypted);
- return result;
- }
- public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
- {
- byte[] encryptedBytes = null;
- // Set your salt here, change it to meet your flavor:
- // The salt bytes must be at least 8 bytes.
- byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
- using (MemoryStream ms = new MemoryStream())
- {
- using (RijndaelManaged AES = new RijndaelManaged())
- {
- AES.KeySize = 256;
- AES.BlockSize = 128;
- var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
- AES.Key = key.GetBytes(AES.KeySize / 8);
- AES.IV = key.GetBytes(AES.BlockSize / 8);
- AES.Mode = CipherMode.CBC;
- using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
- {
- cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
- cs.Close();
- }
- encryptedBytes = ms.ToArray();
- }
- }
- return encryptedBytes;
- }
- public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
- {
- byte[] decryptedBytes = null;
- // Set your salt here, change it to meet your flavor:
- // The salt bytes must be at least 8 bytes.
- byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
- using (MemoryStream ms = new MemoryStream())
- {
- using (RijndaelManaged AES = new RijndaelManaged())
- {
- AES.KeySize = 256;
- AES.BlockSize = 128;
- var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
- AES.Key = key.GetBytes(AES.KeySize / 8);
- AES.IV = key.GetBytes(AES.BlockSize / 8);
- AES.Mode = CipherMode.CBC;
- using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
- {
- cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
- cs.Close();
- }
- decryptedBytes = ms.ToArray();
- }
- }
- return decryptedBytes;
- }
- public string Username { get; private set; }
- public string Message { get; private set; }
- public Command command { get; private set; }
- public static byte[] getBytes(string user, string msg, Command cmd)
- {
- string user_S = user;
- string msg_S = msg;
- if (string.IsNullOrEmpty(user))
- {
- user_S = "anonymous";
- }
- if (string.IsNullOrEmpty(msg))
- {
- msg_S = "No Message";
- }
- //Set user and message as encryption.
- byte[] b_user = Encoding.Default.GetBytes(EncryptText(user_S, "YourPassHere"));
- byte[] b_msg = Encoding.Default.GetBytes(EncryptText(msg_S, "YourPassHere"));
- byte[] usr_len = BitConverter.GetBytes(b_user.Length);
- byte[] msg_len = BitConverter.GetBytes(b_msg.Length);
- byte[] command = BitConverter.GetBytes((int)cmd);
- List<byte> byteArray = new List<byte>();
- byteArray.AddRange(command);
- byteArray.AddRange(usr_len);
- byteArray.AddRange(msg_len);
- byteArray.AddRange(b_user);
- byteArray.AddRange(b_msg);
- return byteArray.ToArray();
- }
- public DataStructure(byte[] fromArray)
- {
- command = (Command)BitConverter.ToInt32(fromArray, 0);
- int usr_len = BitConverter.ToInt32(fromArray, 4);
- int msg_len = BitConverter.ToInt32(fromArray, 8);
- Username = DecryptText(Encoding.Default.GetString(fromArray,12,usr_len), "YourPassHere");
- Message = DecryptText(Encoding.Default.GetString(fromArray,12+usr_len,msg_len), "YourPassHere");
- }
- public DataStructure()
- {
- //default
- }
- }
- #endregion
- public class RDTClient
- {
- #region Event
- public event EventHandler<MessageEventArgs> ClientJoin;
- public event EventHandler<MessageEventArgs> ClientExit;
- public event EventHandler<MessageEventArgs> ChatMessage;
- public event EventHandler<MessageEventArgs> ClientKick;
- public event EventHandler<MessageEventArgs> ServerListReply;
- #endregion
- #region Declare
- /// <summary>
- /// The default Server/client buffer. (Message/Command system)
- /// </summary>
- public byte[] clientSBuffer = new byte[32768];//32kb just for safe measure.
- Socket client;
- /// <summary>
- /// gets the username of this client instance.
- /// </summary>
- public static string user { get; private set; }
- #endregion
- #region Constructor
- /// <summary>
- /// Provides a basic client instance for this program.
- /// </summary>
- /// <param name="host">The address of the server to connect to.</param>
- /// <param name="port">The port number the server is listening on.</param>
- /// <param name="username">Your username for this instance.</param>
- public RDTClient(string host, int port, string username)
- {
- try
- {
- user = username;
- client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- client.BeginConnect(host, port, new AsyncCallback(OnConnect), null);
- }
- catch (Exception)
- {
- throw;
- }
- }
- #endregion
- #region Socket I/O Async method overides
- protected virtual void OnConnect(IAsyncResult ar)
- {
- try
- {
- client.EndConnect(ar);
- byte[] ToSend = DataStructure.getBytes(user, "test", Command.Login);
- client.BeginSend(ToSend,0,ToSend.Length,SocketFlags.None,new AsyncCallback(OnSend),null);
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex.Message);
- ServerDisconnect = true;
- }
- }
- protected virtual void OnSend(IAsyncResult ar)
- {
- try
- {
- client.EndSend(ar);
- client.BeginReceive(clientSBuffer, 0, clientSBuffer.Length, SocketFlags.None, new AsyncCallback(onReceive), null);
- }
- catch(Exception)
- {
- }
- }
- public void SignOut()
- {
- byte[] ToSend = DataStructure.getBytes(user, "Leaving", Command.Logout);
- client.Send(ToSend);
- client.Close();
- ServerDisconnect = true;
- }
- public void SignOut(string Reason)
- {
- byte[] ToSend = DataStructure.getBytes(user, Reason, Command.Logout);
- client.Send(ToSend);
- client.Close();
- ServerDisconnect = true;
- }
- protected virtual void onReceive(IAsyncResult ar)
- {
- try
- {
- //Do stuff with the data accordingly.... meh.
- DataStructure DataReceived = new DataStructure(clientSBuffer);
- client.EndReceive(ar);
- switch (DataReceived.command)
- {
- case Command.Login:
- OnClientJoin(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
- break;
- case Command.Logout:
- OnClientExit(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
- break;
- case Command.Message:
- OnChatMessage(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
- break;
- case Command.List:
- OnServerListReply(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
- break;
- case Command.Kick:
- OnClientKick(new MessageEventArgs(DataReceived.Message, DataReceived.Username));
- break;
- default:
- break;
- }
- //after processing, keep on the lookout for more shit.
- client.BeginReceive(clientSBuffer, 0, clientSBuffer.Length, SocketFlags.None, new AsyncCallback(onReceive), null);
- }
- catch (ObjectDisposedException)
- {
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- #endregion
- #region Invokes
- protected virtual void OnClientJoin(MessageEventArgs e)
- {
- EventHandler<MessageEventArgs> temp = ClientJoin;
- if (temp != null)
- {
- temp(this,e);
- }
- }
- protected virtual void OnClientExit(MessageEventArgs e)
- {
- EventHandler<MessageEventArgs> temp = ClientExit;
- if (temp != null)
- {
- temp(this, e);
- }
- }
- protected virtual void OnChatMessage(MessageEventArgs e)
- {
- EventHandler<MessageEventArgs> temp = ChatMessage;
- if (temp != null)
- {
- temp(this, e);
- }
- }
- protected virtual void OnServerListReply(MessageEventArgs e)
- {
- EventHandler<MessageEventArgs> temp = ServerListReply;
- if (temp != null)
- {
- temp(this, e);
- }
- }
- protected virtual void OnClientKick(MessageEventArgs e)
- {
- EventHandler<MessageEventArgs> temp = ClientKick;
- if (temp != null)
- {
- temp(this, e);
- }
- }
- #endregion
- public bool ServerDisconnect { get; set; }
- public void SendMessage(string username, string message)
- {
- byte[] d = DataStructure.getBytes(user,message,Command.Message);
- client.BeginSend(d, 0, d.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
- }
- }
- public class MessageEventArgs : EventArgs
- {
- /// <summary>
- /// The text message received from the server.
- /// </summary>
- public string Text { get; private set; }
- public string Username { get; private set; }
- public MessageEventArgs(string text,string user)
- {
- Username = user;
- Text = text;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment