Ejemplo n.º 1
0
 void Awake()
 {
     //Inicijalizacija na nulu
     diamondCount = Crypting.EncryptInt(0);
     coinsCount   = Crypting.EncryptInt(0);
     lives        = Crypting.EncryptInt(maxLives);
 }
Ejemplo n.º 2
0
        //Checks if a user with that username exists and if not it writes the new user to the DB and creates a new playlist
        public HttpResponseMessage Post(UserApiModel user)
        {
            var queryData = this.databaseConnection.GetData($"SELECT * FROM user WHERE benutzername = '" + user.userName + "'");

            this.databaseConnection.CloseConnection();

            if (queryData.Count > 0)
            {
                return(this.Request.CreateResponse(HttpStatusCode.InternalServerError));
            }

            try
            {
                var encryptedPassword = Crypting.EncryptPassword(user.password);

                this.databaseConnection.QueryInsert($"INSERT INTO user (`benutzername`, `vorname`, `nachname`, `passwort`) VALUES (\'{user.userName}\', \'{user.firstName}\' , \'{user.lastName}\', \'{encryptedPassword}\')");

                var queryUserId = this.databaseConnection.GetData($"SELECT iduser FROM user WHERE benutzername = '" + user.userName + "'");

                var userId = queryUserId[0].GetValue(0);

                this.databaseConnection.QueryInsert($"INSERT INTO playlist (`User_idUser`) VALUES (\'{userId}\')");
            }
            catch (Exception e)
            {
                return(this.Request.CreateResponse(HttpStatusCode.InternalServerError));
            }

            return(this.Request.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 3
0
        public static bool IsLicenseKey_Exist()
        {
            string lcKey = Crypting.DeCryptData(); if (lcKey == null)

            {
                return(false);
            }

            lcKey = lcKey.Replace("\r\n", "");
            conn.Open();
            string       sql = "SELECT * from LicenseTBO WHERE license_key = @license AND duration_key >= @curdate"; //todo: date check
            MySqlCommand cmd = new MySqlCommand(sql, conn);

            cmd.Parameters.Add("@license", MySqlDbType.String).Value   = lcKey;
            cmd.Parameters.Add("@curdate", MySqlDbType.DateTime).Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            try
            {
                object obj = cmd.ExecuteScalar();
                if (obj == null)
                {
                    conn.Close(); conn.Dispose(); return(false);
                }
                conn.Close();
                conn.Dispose();
                return(true);
            }
            catch
            {
                conn.Close();
                conn.Dispose();
                return(false);
            }
        }
Ejemplo n.º 4
0
 public void InitializeScoresToZero()
 {
     foreach (Score s in scores)
     {
         s.score = Crypting.EncryptInt2(0);
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Old save function
        /// </summary>
        /// <param name="Attempts"></param>
        /// <returns></returns>
        private static async Task <bool> SaveFileAsync <T>(StorageFile file, ObservableCollection <T> DeliveredData, int Attempts = 0) where T : BaseItem
        {
            try
            {
                foreach (var item in DeliveredData.Where(x => x.Secured && !x.Encrypted))
                {
                    item.Name        = Crypting.Encrypt(item.Name);
                    item.Description = Crypting.Encrypt(item.Description);
                    item.Encrypted   = true;
                }

                XmlSerializer Serializ = new XmlSerializer(typeof(ObservableCollection <T>));

                using (Stream XmlStream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(file.Name, CreationCollisionOption.ReplaceExisting))
                {
                    Serializ.Serialize(XmlStream, DeliveredData);
                }

                return(true);
            }

            // When file is unavailable
            catch (Exception e) when((e.Message.Contains("denied") || e.Message.Contains("is in use")) && (Attempts < 10))
            {
                return(await SaveFileAsync(file, DeliveredData, Attempts + 1));
            }

            catch /*(Exception e)*/
            {
                return(false);
            }
        }
Ejemplo n.º 6
0
        private static void OnRead(IAsyncResult ar)
        {
            int receivedBytes = Stream.EndRead(ar);

            TotalBuffer = Concat(TotalBuffer, Buffer, receivedBytes);

            while (TotalBuffer.Length > 8)
            {
                int encryptedLength = BitConverter.ToInt32(TotalBuffer, 0);
                int decryptedLength = BitConverter.ToInt32(TotalBuffer, 4);

                if (TotalBuffer.Length >= 8 + encryptedLength)
                {
                    byte[] PartialBuffer = TotalBuffer.Skip(8).Take(encryptedLength).ToArray();
                    string Decrypted     = Crypting.DecryptStringFromBytes(PartialBuffer);

                    string[] packetData = Regex.Split(Decrypted, "\r\n");
                    HandleData(packetData);
                    TotalBuffer = TotalBuffer.Skip(encryptedLength + 8).Take(TotalBuffer.Length - encryptedLength - 8).ToArray();
                }
                else
                {
                    break;
                }
            }
            Stream.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback(OnRead), null);
        }
Ejemplo n.º 7
0
        public string Login(CredentialsModel data)
        {
            //-------------- here comes username and password check and writing token to database
            // u tokenu moze da stoji i broj koji pokazuje na kom mestu pocinje username
            string password = data.password;
            string username = data.username;

            ApplicationUser user = UserManager.Find(username, password);

            if (user == null)
            {
                return("invalid attempt");
            }



            //--- then token creation
            var userAgent = Request.Headers.GetValues("User-Agent");
            //var referer = Request.Headers.GetValues("Referer");
            var    referer = "Referer";
            string token   = userAgent + "|" + "IGG" + "|" + referer + "|" + user.UserName;// + username;
            // here put smart combination for token

            string tokenEncripted = Crypting.Encrypt(token);


            return(tokenEncripted);
        }
Ejemplo n.º 8
0
 public void InitializeBestScoresToZero()
 {
     for (int i = 0; i < bestScores.Count; i++)
     {
         bestScores[i].score     = Crypting.EncryptInt2(0);
         bestScores[i].scoreName = scores[i].scoreName;
     }
 }
Ejemplo n.º 9
0
 void Update()
 {
     //PRIKAZUJE SE BROJ COINA
     //mozda ovo ne treba da bude u update-u nego da se poziva updateTreasureLabels nakon kupovine
     foreach (UILabel l in coinLabels)
     {
         l.text = Crypting.DecryptInt(coinsCount).ToString();
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Share item via Share menu
        /// </summary>
        /// <param name="obj">Shared item</param>
        public async void ShareItemAsync(T item)
        {
            DataTransferManager daTranManaItem = DataTransferManager.GetForCurrentView();

            daTranManaItem.DataRequested += DaTranManaItem_DataRequested;

            string itemTypeName = item.GetType().Name;

            if (item == null)
            {
                return;
            }

            CurrentItem = item;
            var typeOfItemList = System.Enum.GetValues(typeof(ItemTypeEnum)).Cast <ItemTypeEnum>().ToList();

            var clone = (T)item.Clone();

            if (item.Secured)
            {
                clone.Name        = Crypting.Encrypt(item.Name);
                clone.Description = Crypting.Encrypt(item.Description);
            }

            var sharedData = new ItemStorage <T>
            {
                TypeOfItem = typeOfItemList[typeOfItemList.IndexOf(typeOfItemList.FirstOrDefault(x => x.ToString() == itemTypeName))],
                Items      = new System.Collections.ObjectModel.ObservableCollection <T>()
                {
                    clone
                }
            };

            try
            {
                XmlSerializer Serializ = new XmlSerializer(typeof(ItemStorage <T>));

                using (Stream XmlStream = ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(ShareFileItem, CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult())
                {
                    Serializ.Serialize(XmlStream, sharedData);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            var shareFile = await ApplicationData.Current.LocalFolder.GetFileAsync(ShareFileItem);

            shareFileList = new List <StorageFile>
            {
                shareFile
            };

            DataTransferManager.ShowShareUI();
        }
            public override bool Pass(INodeEndpointProtocolRequest request)
            {
                lock (this.stepLock)
                {
                    switch (this.currentStep)
                    {
                    case Step.WaitingForAuthData:
                    {
                        this.currentStep = Step.WaitingForAuthResult;
                        byte[] authData          = request.Message;
                        byte[] encryptedAuthData = Md5AuthDataAndPassword(authData, this.passwordMD5);
                        this.client.Send(encryptedAuthData);
                    }
                        return(false);

                    case Step.WaitingForAuthResult:
                    {
                        this.currentStep = Step.WaitingForAesKey;
                        if (request.RequestMessage() != "PASS")
                        {
                            this.client.Disconnect();
                        }
                        else
                        {
                            byte[] publicKey, privateKey;
                            Crypting.RsaGenerateKey(out publicKey, out privateKey);

                            this.client.Send(publicKey);
                            this.privateKey = privateKey;
                        }
                    }
                        return(false);

                    case Step.WaitingForAesKey:
                    {
                        this.currentStep = Step.Done;

                        byte[] encryptedMessage = request.Message;
                        byte[] message          = Crypting.RsaDecrypt(encryptedMessage, this.privateKey);
                        this.privateKey = null;

                        int keyLength = StreamProtocol <Stream> .ReadLeadBytes(message);

                        byte[] key = new byte[keyLength];
                        byte[] iv  = new byte[message.Length - sizeof(int) - keyLength];
                        Array.Copy(message, sizeof(int), key, 0, key.Length);
                        Array.Copy(message, sizeof(int) + keyLength, iv, 0, iv.Length);
                        SetKey(key, iv);
                        this.connectionEvent.Set();
                    }
                        return(false);
                    }
                }
                return(true);
            }
 public byte[] Encode(byte[] bytes)
 {
     if (this.key == null)
     {
         return(bytes);
     }
     else
     {
         return(Crypting.AesEncrypt(bytes, this.key, this.iv));
     }
 }
Ejemplo n.º 13
0
        //Читает из реестра, сколько дней прошло с активации
        private int DaysFromActivation(RegistryKey key)
        {
            int errResult = Convert.ToInt32(DateTime.Now.Subtract(Different.MinDate).TotalDays);

            try
            {
                DateTime insDate = DateTime.FromOADate(Crypting.Decrypt(key.GetValue("id").ToString()).ToDouble());
                return(Convert.ToInt32(DateTime.Now.Subtract(insDate).TotalDays));
            }
            catch { return(errResult); }
        }
Ejemplo n.º 14
0
 private void btnRegister_Click(object sender, RoutedEventArgs e)
 {
     if (!DBWorker.SetLicenseKey(tbKey.Text))
     {
         MessageBox.Show("Uncorrect license key");
         return;
     }
     Crypting.CryptDataInFile(tbKey.Text);
     this.Visibility = Visibility.Hidden;
     Application.Current.Windows[0].Visibility = Visibility.Visible;
 }
Ejemplo n.º 15
0
 public void CoinsMinus(int amount)
 {
     if ((GetCoins() - amount) < 0)
     {
         coinsCount = Crypting.EncryptInt(0);
     }
     else
     {
         coinsCount = Crypting.EncryptInt(GetCoins() - amount);
     }
 }
Ejemplo n.º 16
0
 public int GetBestScore(string name)
 {
     for (int i = 0; i < bestScores.Count; i++)
     {
         if (bestScores[i].scoreName.CompareTo(name) == 0)
         {
             return(Crypting.DecryptInt2(bestScores[i].score));
         }
     }
     return(-1);
 }
Ejemplo n.º 17
0
        private void BtnCreateUser_OnClick(object sender, RoutedEventArgs e)
        {
            string connectionString =
                @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SqlRUsers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

            SqlConnection connection = new SqlConnection(connectionString);
            Salting       salting    = new Salting();
            var           salt       = salting.GetSalt();
            Hashing       hashing    = new Hashing();
            var           hash       = hashing.GetHash(salt, txtCreatePassword.Password);

            var encryptedConnectionString = Crypting.Encrypt(txtConnectionString.Text);

            try
            {
                if (connection.State == ConnectionState.Closed && txtConfirmPassword.Password.Equals(txtCreatePassword.Password))
                {
                    connection.Open();
                }
                else
                {
                    MessageBox.Show("Confirm Password does not match Password.");
                }
                String query =
                    "INSERT into Users (UserName,ConnectionString, Password, Salt) VALUES (@Username, @ConnectionString, @Password, @Salt)";
                SqlCommand sqlCmd = new SqlCommand(query, connection);
                sqlCmd.CommandType = CommandType.Text;
                sqlCmd.Parameters.AddWithValue("@Username", txtCreateUsername.Text);
                sqlCmd.Parameters.AddWithValue("@ConnectionString", encryptedConnectionString);
                sqlCmd.Parameters.AddWithValue("@Password", hash);
                sqlCmd.Parameters.AddWithValue("@Salt", salt);


                if (sqlCmd.ExecuteNonQuery() != 0)
                {
                    LoginScreen login = new LoginScreen();
                    login.Show();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Failed creating new user!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 18
0
 public void SetScore(int amount, string name)
 {
     for (int i = 0; i < scores.Count; i++)
     {
         if (scores[i].scoreName.CompareTo(name) == 0)
         {
             scores[i].score = Crypting.EncryptInt2(amount);
             foreach (Text labela in scores[i].scoreLabels)
             {
                 labela.text = amount.ToString();
             }
         }
     }
 }
Ejemplo n.º 19
0
        private void btn_save_Click(object sender, EventArgs e)
        {
            string userName = tb_userName.Text;
            string password = Crypting.EncryptSecret(tb_password.Text);

            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            configuration.AppSettings.Settings["UserName"].Value = userName;
            configuration.AppSettings.Settings["Password"].Value = password;
            configuration.Save(ConfigurationSaveMode.Full, true);
            ConfigurationManager.RefreshSection("appSettings");

            this.Close();
        }
Ejemplo n.º 20
0
        //Check if the password is right
        public HttpResponseMessage Patch(UserApiModel user)
        {
            if (user != null)
            {
                var passwordVerfied = Crypting.VerifyPassword(user.password, user.userName);

                if (passwordVerfied == true)
                {
                    return(this.Request.CreateResponse(HttpStatusCode.OK));
                }
            }

            return(this.Request.CreateResponse(HttpStatusCode.InternalServerError));
        }
Ejemplo n.º 21
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var tokenEncripted = filterContext.HttpContext.Request.Headers["token"];
            var userName       = filterContext.HttpContext.Request.Headers["userName"];
            var rolesList      = AllowedUserTypes.Replace(" ", string.Empty).Split(',').ToList();

            if (rolesList.Contains("GUEST"))
            {
                if (userName == null || userName.Equals(string.Empty))
                {
                    CurentUserName = "******";
                }
                else
                {
                    CurentUserName = userName;
                }
            }
            else
            {
                try
                {
                    string   token         = Crypting.Decrypt(tokenEncripted);
                    string[] tokenArr      = token.Split('|');
                    string   tokenRole     = tokenArr[1];
                    string   tokenUsername = tokenArr[tokenArr.Length - 1];

                    if (!rolesList.Contains(tokenRole))
                    {
                        returnUnauthorized();
                    }

                    if (!tokenUsername.Equals(userName))
                    {
                        returnUnauthenticated();
                    }

                    CurentUserName = userName;
                }
                catch (Exception err)
                {
                    // somebody messed with the token on client

                    returnUnauthenticated();
                }
            }

            // TODO: For greater security ask the database for users role
            // also possible to put token in the database (per user) and bunch other data
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Save data to file
        /// </summary>
        /// <param name="Attempts">Number of attempts</param>
        /// <returns>True, if save was succesful</returns>
        protected async Task <bool> SaveDataAsync(int Attempts = 0)
        {
            try
            {
                foreach (var item in ItemsSource.Where(x => x.Secured && !x.Encrypted))
                {
                    item.Name        = Crypting.Encrypt(item.Name);
                    item.Description = Crypting.Encrypt(item.Description);
                    item.Encrypted   = true;
                }

                var typeOfItemList = System.Enum.GetValues(typeof(ItemTypeEnum)).Cast <ItemTypeEnum>().ToList();

                ItemStorage <T> itemStorage = new ItemStorage <T>()
                {
                    Items      = GetFinalCollection(),
                    TypeOfItem = typeOfItemList[typeOfItemList.IndexOf(typeOfItemList.FirstOrDefault(x => x.ToString() == nameof(T)))]
                };

                XmlSerializer Serializ = new XmlSerializer(typeof(ItemStorage <T>));

                using (Stream XmlStream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(FileName, CreationCollisionOption.ReplaceExisting))
                {
                    Serializ.Serialize(XmlStream, /*DeliveredData*/ itemStorage);
                }

                foreach (var item in ItemsSource.Where(x => x.Secured && x.Encrypted))
                {
                    item.Name        = Crypting.Decrypt(item.Name);
                    item.Description = Crypting.Decrypt(item.Description);
                    item.Encrypted   = false;
                }

                return(true);
            }

            // When file is unavailable
            catch (Exception e) when((e.Message.Contains("denied") || e.Message.Contains("is in use")) && (Attempts < 10))
            {
                return(await SaveDataAsync(Attempts + 1));
            }

            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return(false);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Get all items by async
        /// </summary>
        /// <typeparam name="T">Item type</typeparam>
        /// <returns>Collection of items</returns>
        public virtual async Task <List <T> > GetItemsAsync <T>() where T : BaseItem
        {
            var itemSource = dbAccess.GetAllItems <T>();

            foreach (var item in itemSource)
            {
                if (item.Secured && item.Encrypted)
                {
                    item.Name        = Crypting.Decrypt(item.Name);
                    item.Description = Crypting.Decrypt(item.Description);
                    item.Encrypted   = false;
                }
            }

            return(itemSource);
        }
Ejemplo n.º 24
0
        //Insp -> vlastni typ pripony
        public override void Execute(object parameter)
        {
            if (parameter is ListViewBase itemList)
            {
                if (itemList.Items.Count == 0)
                {
                    return;
                }

                string itemTypeName   = itemList.Items[0].GetType().Name;
                var    typeOfItemList = System.Enum.GetValues(typeof(ItemTypeEnum)).Cast <ItemTypeEnum>().ToList();

                var sharedData = new ItemStorage <T>
                {
                    TypeOfItem = typeOfItemList[typeOfItemList.IndexOf(typeOfItemList.FirstOrDefault(x => x.ToString() == itemTypeName))]
                };

                foreach (var item in new ObservableCollection <T>(itemList.SelectedItems.Cast <T>().Select(x => (T)x.Clone()).ToList()))
                {
                    T itemToShare = item;

                    if (itemToShare.Secured)
                    {
                        itemToShare.Name        = Crypting.Encrypt(itemToShare.Name);
                        itemToShare.Description = Crypting.Encrypt(itemToShare.Description);
                    }

                    sharedData.Items.Add(item);
                }

                try
                {
                    XmlSerializer Serializ = new XmlSerializer(typeof(ItemStorage <T>));

                    using (Stream XmlStream = ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("Share.tdn", CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult())
                    {
                        Serializ.Serialize(XmlStream, sharedData);
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }

                DataTransferManager.ShowShareUI();
            }
        }
Ejemplo n.º 25
0
        //Возвращает номер лицензии указанного приложения или сообщает, что нет лицензии
        public string ANumber(string app)
        {
            int c = ACheck(app, true);

            if (c <= 1)
            {
                return("Нет лицензии");
            }
            RegistryKey UAIKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\UAI");

            try
            {
                return(Crypting.Decrypt(UAIKey.GetValue("un").ToString()));
            }
            catch { return("Нет лицензии"); }
            finally { UAIKey.Close(); }
        }
Ejemplo n.º 26
0
 //Регистрация
 #region
 //Запись в реестр даты установки
 public static void SetDate()
 {
     try
     {
         RegistryKey dateKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\UAI", false);
         if (dateKey == null || dateKey.GetValue("id") == null || (string)dateKey.GetValue("id") == "")
         {
             dateKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\UAI");
             dateKey.SetValue("id", Crypting.Encrypt(DateTime.Now.ToOADate().ToString()), RegistryValueKind.String);
         }
         dateKey.Close();
     }
     catch (Exception e1)
     {
         e1.MessageError();
     }
 }
Ejemplo n.º 27
0
        //Insp -> vlastni typ pripony
        /// <inheritdoc/>
        public override void Execute(object parameter)
        {
            if (parameter is ListViewBase itemList)
            {
                if (itemList.Items.Count == 0)
                {
                    return;
                }

                string itemTypeName = itemList.Items[0].GetType().Name;

                var sharedData = new ItemStorage <T>
                {
                    TypeOfItem = itemTypeName
                };

                foreach (var item in new List <T>(itemList.SelectedItems.Cast <T>().Select(x => (T)x.Clone()).ToList()))
                {
                    T itemToShare = item;

                    if (itemToShare.Secured)
                    {
                        itemToShare.Name        = Crypting.Encrypt(itemToShare.Name);
                        itemToShare.Description = Crypting.Encrypt(itemToShare.Description);
                    }

                    sharedData.Items.Add(item);
                }

                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(ItemStorage <T>));

                    using Stream xmlStream = ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("Share.isuf", CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();
                    serializer.Serialize(xmlStream, sharedData);
                }
                catch (Exception e)
                {
                    LogService.AddLogMessage(e.Message, logLevel: Base.Enum.LogLevel.Debug);
                    throw new Base.Exceptions.Exception("Unhandled exception", e);
                }

                DataTransferManager.ShowShareUI();
            }
        }
Ejemplo n.º 28
0
 public void SetAndSaveBestScores()
 {
     Debug.Log("Checking and setting best scores");
     for (int i = 0; i < scores.Count; i++)
     {
         if (Crypting.DecryptInt2(scores[i].score) > Crypting.DecryptInt2(bestScores[i].score))
         {
             bestScores[i].score = scores[i].score;
             foreach (Text label in bestScores[i].scoreLabels)
             {
                 label.text = (Crypting.DecryptInt2(bestScores[i].score)).ToString();
             }
             AddBestScoreToPlayer(bestScores[i].scoreName, bestScores[i].score);
         }
     }
     //todo: Save na server i lokal
     App.firebase.Save();
 }
Ejemplo n.º 29
0
    public string ToString()
    {
        string print = "Uid: " + uid + "; " +
                       "Name: " + name + "; " +
                       "Email: " + email + "; " +
                       "Fbid: " + fbid + "; " +
                       "Gender: " + gender + "; " +
                       "Ads: " + ads + "; " +
                       "Sound: " + sound + "; " +
                       "TimesPlayed: " + timesPlayed + "; " + "Best scores: ";

        for (int i = 0; i < bestScoreNames.Count; i++)
        {
            print += bestScoreNames[i] + ": " + Crypting.DecryptInt(bestScoreValues[i]) + ";";
        }

        return(print);
    }
Ejemplo n.º 30
0
        private static void Write(string data)
        {
            var dataAsBytes = Encoding.ASCII.GetBytes(data + "\r\n\r\n");

            var dataStringEncrypted = Crypting.EncryptStringToBytes(data + "\r\n\r\n");


            Debug.WriteLine("Non encrypted.. " + Encoding.ASCII.GetString(dataAsBytes));

            Debug.WriteLine("Encrypted " + Encoding.ASCII.GetString(dataStringEncrypted));

            Stream.Write(BitConverter.GetBytes(dataStringEncrypted.Length), 0, 4);
            Stream.Write(BitConverter.GetBytes(dataAsBytes.Length), 0, 4);

            Stream.Write(dataStringEncrypted, 0, dataStringEncrypted.Length);

            Stream.Flush();
        }