예제 #1
0
 private void countPart4()
 {
     try
     {
         while (!arrayM_available)
         {
         }
         arrayM_available = false; //LOCK
         //every M[i] mod 3 == 0 --> M[i] = M[i] * M[2]
         for (int i = 0; i < arrayM.Count; i++)
         {
             if (arrayM[i] % 3 == 0)
             {
                 arrayM[i] *= arrayM[2];
             }
         }
         arrayM_available = true; //UNLOCK
         return;
     }
     catch (Exception ex)
     {
         var logLine = DateTime.Now.ToString() + ": " + ex.Message;
         log.Add(logLine);
         File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + ex.Message + Environment.NewLine);
         try
         {
             var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + ex.Message);
             toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
         }
         catch { }
         arrayM_available = true;
         return;
     }
 }
예제 #2
0
        private void refreshTable()
        {
            try
            {
                dataGridView1.Rows.Clear();

                var logs = MSSQL_logging.get_database_logs();

                foreach (var log in logs)
                {
                    dataGridView1.Rows.Add(log.logDateTime, log.labnumber, log.logtext);
                }
            }
            catch
            {
                MessageBox.Show("Не удалось получить информацию из базы данных!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #3
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                saveFileDialog1.FileName         = "SteganoContainer.bmp";
                saveFileDialog1.Filter           = "BMP image file (*.bmp)|*.bmp";
                saveFileDialog1.FilterIndex      = 2;
                saveFileDialog1.RestoreDirectory = true;

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    using (FileStream file = new FileStream(saveFileDialog1.FileName, FileMode.Create))
                    {
                        if (File.Exists("tempImg.bmp"))
                        {
                            byte[] imgContent = File.ReadAllBytes("tempImg.bmp");
                            file.Write(imgContent, 0, imgContent.Length);
                        }
                        else
                        {
                            throw new Exception("Попытка расшифровки без вспомогательного файла стеганоконтейнера!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var logLine = DateTime.Now.ToString() + ": " + ex.Message;
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB2_TZSPD: " + ex.Message + Environment.NewLine);
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB2_TZSPD", "LAB2_TZSPD: " + ex.Message);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
                MessageBox.Show(ex.Message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #4
0
      private void addition_Click(object sender, EventArgs e)
      {
          string str = "";

          try
          {
              int    minlen, maxlen;
              string min   = null,
                     max   = null;
              char symbol1 = ' ';
              char symbol2 = ' ';
              if (name.Text.Length < surname.Text.Length)
              {
                  minlen = name.Text.Length;
                  maxlen = surname.Text.Length;
                  min    = name.Text;
                  max    = surname.Text;
              }
              else
              {
                  maxlen = name.Text.Length;
                  minlen = surname.Text.Length;
                  max    = name.Text;
                  min    = surname.Text;
              }
              tail.Text = "";
              for (int i = minlen; i < maxlen; i++)
              {
                  tail.Text += max[i];
              }
              for (int i = 0; i < minlen; i++)
              {
                  symbol1 = name.Text[i];
                  symbol2 = surname.Text[i];
                  int symbol = symbol1 ^ symbol2;
                  if (symbol > 255)
                  {
                      throw new ArgumentOutOfRangeException("name_surname", "End-char size is out of ASCII range.");
                  }
                  //if (symbol == 3 || symbol == 0)
                  //    throw new SystemCharException("System char exception!", symbol);
                  else
                  {
                      char csymb = (char)symbol;
                      str += csymb.ToString();
                  }
              }
              if (((int)str[0] == 3 || (int)str[0] == 0) && str.Length == 1)
              {
                  throw new SystemCharException("System char exception!", (int)str[0]);
              }

              for (int i = minlen; i < maxlen; i++)
              {
                  str += max[i];
              }
              result.Text = str;


              result_ascii.Text = "";
              foreach (char symb in result.Text)
              {
                  result_ascii.Text += (int)symb + "; ";
              }


              if (name.Text.Any(char.IsDigit) || name.Text.Any(char.IsWhiteSpace))
              {
                  throw new ArgumentException("Name contains unsupportable characters.");
              }
              else if (surname.Text.Any(char.IsDigit) || surname.Text.Any(char.IsWhiteSpace))
              {
                  throw new ArgumentException("Surname contains unsupportable characters.");
              }
          }
          catch (ArgumentOutOfRangeException ex)
          {
              result.Text = "Out of Range!";
              var logLine    = DateTime.Now.ToString() + ": " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text;
              var lineNoTime = ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text;
              File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB1: " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text + Environment.NewLine);
              log.Add(logLine);
              try
              {
                  var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB1", "LAB1:" + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text);
                  toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
              }
              catch { }
          }
          catch (ArgumentException ex)
          {
              result.Text = "Incorrect inp";
              var logLine    = DateTime.Now.ToString() + ": " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text;
              var lineNoTime = ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text;
              File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB1: " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text + Environment.NewLine);
              log.Add(logLine);
              try
              {
                  var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB1", "LAB1:" + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text);
                  toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
              }
              catch { }
          }
          catch (IndexOutOfRangeException ex)
          {
              result.Text = "Index OOR!";
              var logLine    = DateTime.Now.ToString() + ": " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text;
              var lineNoTime = ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text;
              File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB1: " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text + Environment.NewLine);
              log.Add(logLine);
              try
              {
                  var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB1", "LAB1:" + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text);
                  toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
              }
              catch { }
          }
          catch (SystemCharException ex)
          {
              result.Text       = "System char!";
              result_ascii.Text = ex.code.ToString();
              var logLine    = DateTime.Now.ToString() + ": " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text + ",char=" + ex.code;
              var lineNoTime = ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text + ",char=" + ex.code;
              File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB1: " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text + Environment.NewLine);
              log.Add(logLine);
              try
              {
                  var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB1", "LAB1:" + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text);
                  toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
              }
              catch { }
          }
          catch (Exception ex)
          {
              result.Text = ex.Message;
              var logLine    = DateTime.Now.ToString() + ": " + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text;
              var lineNoTime = ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text;
              File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB1: Unhandled Exception; INFO: name=" + name.Text + ",surname=" + surname.Text + Environment.NewLine);
              log.Add(logLine);
              try
              {
                  var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB1", "LAB1:" + ex.Message + "; INFO: name=" + name.Text + ",surname=" + surname.Text);
                  toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
              }
              catch { }
          }
          finally
          {
              Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
              name_ascii.Text    = "";
              surname_ascii.Text = "";
              tail_ascii.Text    = "";
              foreach (char symb in name.Text)
              {
                  name_ascii.Text += (int)symb + "; ";
              }
              foreach (char symb in surname.Text)
              {
                  surname_ascii.Text += (int)symb + "; ";
              }
              foreach (char symb in tail.Text)
              {
                  tail_ascii.Text += (int)symb + "; ";
              }
          }
      }
예제 #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox_message.TextLength > msg_max_len)
            {
                var logLine    = DateTime.Now.ToString() + ": Сообщение слишком длинное для данного контейнера!";
                var lineNoTime = "LAB1_TZSPD: Сообщение слишком длинное для данного контейнера!";
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB1_TZSPD: Сообщение слишком длинное для данного контейнера!" + Environment.NewLine);
                MessageBox.Show("Сообщение слишком длинное для данного контейнера!", "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB1_TZSPD", lineNoTime);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
                return;
            }
            if (textBox_message.TextLength + 256 > msg_max_len && checkBox_sha256.Checked)
            {
                var logLine    = DateTime.Now.ToString() + ": Сообщение С контрольной суммой SHA-256 слишком длинное для данного контейнера!";
                var lineNoTime = "LAB1_TZSPD: Сообщение С контрольной суммой SHA-256 слишком длинное для данного контейнера!";
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB1_TZSPD: Сообщение С контрольной суммой SHA-256 слишком длинное для данного контейнера!" + Environment.NewLine);
                MessageBox.Show("Сообщение С контрольной суммой SHA-256 слишком длинное для данного контейнера!", "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB1_TZSPD", lineNoTime);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
                return;
            }
            if (textBoxContainer.Text.Contains("  "))
            {
                var logLine    = DateTime.Now.ToString() + ": В контейнере двойные или более пробелы! Пожалуйста, нормализуйте контейнер сначала!";
                var lineNoTime = "LAB1_TZSPD: В контейнере двойные или более пробелы! Пожалуйста, нормализуйте контейнер сначала!";
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB1_TZSPD: В контейнере двойные или более пробелы! Пожалуйста, нормализуйте контейнер сначала!" + Environment.NewLine);
                MessageBox.Show("В контейнере двойные или более пробелы! Пожалуйста, нормализуйте контейнер сначала!", "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB1_TZSPD", lineNoTime);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
                return;
            }
            errorProvider1.Clear();
            string hashBits = "";

            if (checkBox_sha256.Checked)
            {
                SHA256        checksumm = SHA256.Create();
                byte[]        bytes     = checksumm.ComputeHash(Encoding.UTF8.GetBytes(textBoxContainer.Text));
                StringBuilder builder   = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                textBox_checkSumm.Text = builder.ToString();
                //checksumm in binary
                for (int i = 0; i < textBox_checkSumm.TextLength; i++)
                {
                    string tempBin = "";
                    for (int j = 0; j < sizeof(byte) * 8; j++)
                    {
                        if (getBit(textBox_checkSumm.Text[i], j))
                        {
                            tempBin += "1";
                        }
                        else
                        {
                            tempBin += "0";
                        }
                    }
                    for (int j = tempBin.Length - 1; j != -1; j--)
                    {
                        hashBits += tempBin[j];
                    }
                }
            }
            string msgBits = "";

            textBox_messageBin.Text = "";
            textBox_result.Text     = "";
            //message in binary
            for (int i = 0; i < textBox_message.TextLength; i++)
            {
                string tempBin = "";
                for (int j = 0; j < sizeof(char) * 8 / byte_size; j++)
                {
                    if (getBit(textBox_message.Text[i], j))
                    {
                        tempBin += "1";
                    }
                    else
                    {
                        tempBin += "0";
                    }
                }
                for (int j = tempBin.Length - 1; j != -1; j--)
                {
                    msgBits += tempBin[j];
                }
            }
            drawBinaryMsg(msgBits); // draw
            //steganography
            if (checkBox_sha256.Checked)
            {
                string temp = msgBits;
                msgBits = hashBits + temp;
            }
            ArrayList spacesListTemp = new ArrayList();

            for (int i = 0; i < textBoxContainer.TextLength; i++)
            {
                if (textBoxContainer.Text[i] == ' ')
                {
                    spacesListTemp.Add(i);
                }
            }
            int       msgPointer = 0;
            ArrayList spacesList = new ArrayList();

            foreach (int spacePos in spacesListTemp)
            {
                if (msgPointer == msgBits.Length)
                {
                    break;
                }
                if (msgBits[msgPointer] == '0')
                {
                    spacesList.Add(spacePos);
                }
                msgPointer++;
            }
            spacesListTemp.Clear();
            int startPos = 0;

            foreach (int space in spacesList)
            {
                textBox_result.Text += textBoxContainer.Text.Substring(startPos, space + 1 - startPos) + " ";
                startPos             = space + 1;
            }
            textBox_result.Text += textBoxContainer.Text.Substring(startPos);
        }
예제 #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBox_prevpwd.Text != MSSQL_logging.userpassword)
                {
                    throw new Exception("Пароль не соответствует текущему");
                }
                if (textBox_newpwd.TextLength < 14)
                {
                    throw new Exception("Минимальная длина пароля - 14 символов");
                }
                if (textBox_newpwd.Text != textBox_newPwdCopy.Text)
                {
                    throw new Exception("Новые пароли не совпадают");
                }

                //checking for bad passwords
                bool bad = false;
                foreach (var pwd in badpwdlist)
                {
                    if (pwd == textBox_newpwd.Text)
                    {
                        bad = true;
                        break;
                    }
                }
                if (bad)
                {
                    throw new Exception("Выбран слабый пароль!");
                }

                //hashing
                string hash = MathOperations.sha256(textBox_newpwd.Text);

                //update password ===============
                string query = "update logins set hash='" + hash + "' where id=" + MSSQL_logging.user_id.ToString();

                var command = new Microsoft.Data.SqlClient.SqlCommand(query, MSSQL_logging.database_connection);

                if (command.Connection.State != System.Data.ConnectionState.Open)
                {
                    command.Connection.Open();
                }

                command.ExecuteNonQuery();

                //delete old pwd =============
                query = "delete from keys where login_id=" + MSSQL_logging.user_id;
                command.CommandText = query;
                command.ExecuteNonQuery();

                //renew key =================
                MSSQL_logging.GetPrivateKeyFromDB();

                var aesInst       = System.Security.Cryptography.Aes.Create();
                var privKeysha256 = MathOperations.sha256_byte(textBox_newpwd.Text);
                var ivmd5         = MathOperations.md5_byte(textBox_newpwd.Text);

                //enc private key with sha256(pwd) and md5(pwd)
                aesInst.Key = privKeysha256;
                aesInst.IV  = ivmd5;

                var    Encrypted_SK            = aesInst.CreateEncryptor().TransformFinalBlock(MSSQL_logging.AesInst.Key, 0, MSSQL_logging.AesInst.Key.Length);
                string Encrypted_SK_String_HEX = "0x";
                foreach (byte part in Encrypted_SK)
                {
                    Encrypted_SK_String_HEX += part.ToString("X2");
                }
                var    Encrypted_IV            = aesInst.CreateEncryptor().TransformFinalBlock(MSSQL_logging.AesInst.IV, 0, MSSQL_logging.AesInst.IV.Length);
                string Encrypted_IV_String_HEX = "0x";
                foreach (byte part in Encrypted_IV)
                {
                    Encrypted_IV_String_HEX += part.ToString("X2");
                }

                query = "insert into keys values (" + MSSQL_logging.user_id.ToString() + ", " + Encrypted_SK_String_HEX + ", " + Encrypted_IV_String_HEX + ")";

                command.CommandText = query;
                command.ExecuteNonQuery();
                command.Connection.Close();

                //renew obj=================
                MSSQL_logging.userpassword = textBox_newpwd.Text;
                MSSQL_logging.GetPrivateKeyFromDB();

                MessageBox.Show("Успешно!", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #7
0
        private void button_calculate_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBox_inputMode.SelectedIndex == 0)
                {
                    foreach (DataGridViewCell cell in dataGridView1.Rows[0].Cells)
                    {
                        if (cell.Value == null)
                        {
                            throw new Exception("Входной массив заполнен неверно!");
                        }
                        arrayP.Add(Int32.Parse(cell.Value.ToString()));
                        arrayM.Add(Int32.Parse(cell.Value.ToString()));
                    }
                }
                if (arrayP.Count == 0 || arrayM.Count == 0)
                {
                    throw new Exception("Необходимо заполнить или сгенерировать исходный массив!");
                }
                //logic
                var timerLinear   = new Stopwatch();
                var timerParallel = new Stopwatch();
                button_calculate.Enabled = false;
                button_calculate.Refresh();
                //count linear
                //save temp
                timerLinear.Start();
                countPart1();
                countPart2();
                countPart3();
                countPart4();
                timerLinear.Stop();
                textBox_time_linear.Text = timerLinear.ElapsedTicks.ToString() + " тиков";
                textBox_time_linear.Refresh();
                //count parallel
                arrayM.Clear();
                arrayM.AddRange(arrayP.ToArray());
                timerParallel.Start();
                dataGridView1.Rows.Add();
                Thread f1 = new Thread(new ThreadStart(countPart1));
                Thread f2 = new Thread(new ThreadStart(countPart2));
                f1.Start();
                f2.Start();
                f1.Join();
                f2.Join();
                Thread f21 = new Thread(new ThreadStart(countPart3));
                Thread f22 = new Thread(new ThreadStart(countPart4));
                f21.Start();
                f21.Join();
                f22.Start();
                f22.Join();
                timerParallel.Stop();
                textBox_time_parallel.Text = timerParallel.ElapsedTicks.ToString() + " тиков";
                textBox_time_parallel.Refresh();

                //cut
                for (int i = 0; i < arrayM.Count; i++)
                {
                    dataGridView1.Rows[1].Cells[i].Value = arrayM[i];
                }
                arrayP.Clear();
                arrayM.Clear();
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
            }
            catch (Exception ex)
            {
                dataGridView1.Rows.Clear();
                dataGridView1.Rows.Add();
                var logLine = DateTime.Now.ToString() + ": " + ex.Message;
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + ex.Message + Environment.NewLine);
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + ex.Message);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
            }
        }
예제 #8
0
        public void InvokeUpdateInfo()
        {
            if (comboBox_inputMode.Text != prevousMode)
            {
                switch (comboBox_inputMode.Text)
                {
                case "Вручную":
                    textBox_randomFrequency.Clear();
                    textBox_randomFrequency.ReadOnly = true;
                    button_generate.Enabled          = false;
                    button_calculate.Enabled         = true;
                    checkBox_startGenTimer.Enabled   = false;
                    dataGridView1.Rows.Clear();
                    dataGridView1.Rows.Add();
                    break;

                case "Случайно":
                    textBox_randomFrequency.Clear();
                    textBox_randomFrequency.ReadOnly = true;
                    button_generate.Enabled          = true;
                    button_calculate.Enabled         = true;
                    checkBox_startGenTimer.Enabled   = false;
                    dataGridView1.Rows.Clear();
                    break;

                case "Случайно с частотой":
                    textBox_randomFrequency.ReadOnly = false;
                    textBox_randomFrequency.Text     = "500";
                    button_generate.Enabled          = false;
                    button_calculate.Enabled         = false;
                    checkBox_startGenTimer.Enabled   = true;
                    dataGridView1.Rows.Clear();
                    break;
                }
                textBox_randomFrequency.Refresh();
                button_generate.Refresh();
                button_calculate.Refresh();
                checkBox_startGenTimer.Refresh();
                prevousMode = comboBox_inputMode.Text;
            }
            if (checkBox_startGenTimer.Checked && !genTimerWasStarted)
            {
                try
                {
                    timer_valid_check();
                    timer_genCount.Interval = int.Parse(textBox_randomFrequency.Text);
                }
                catch (Exception ex)
                {
                    var logLine = DateTime.Now.ToString() + ": " + ex.Message;
                    log.Add(logLine);
                    File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + ex.Message + Environment.NewLine);
                    try
                    {
                        var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + ex.Message);
                        toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                    }
                    catch { }
                    Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
                }
                finally
                {
                    timer_genCount.Start();
                    genTimerWasStarted = true;
                }
            }
            else if (!checkBox_startGenTimer.Checked && genTimerWasStarted)
            {
                timer_genCount.Stop();
                genTimerWasStarted = false;
            }
        }
예제 #9
0
        private void timer_genCount_Tick(object sender, EventArgs e)
        {
            try
            {
                var timerLinear   = new Stopwatch();
                var timerParallel = new Stopwatch();
                //logic
                //defines
                int cells_per_row = Math.Abs(int.Parse(textBox_elementsOfA.Text));
                int gen_min       = int.Parse(textBox_gen_min.Text);
                int gen_max       = int.Parse(textBox_gen_max.Text);
                //0. clear
                dataGridView1.Rows.Clear();
                //1. generate new
                dataGridView1.Rows.Add();
                var rnd = new Random();
                for (int i = 0; i < cells_per_row; i++)
                {
                    var newNumb = rnd.Next(gen_min, gen_max);
                    arrayP.Add(newNumb);
                    arrayM.Add(newNumb);
                    dataGridView1.Rows[0].Cells[i].Value = newNumb;
                }
                //count linear
                timerLinear.Start();
                countPart1();
                countPart2();
                countPart3();
                countPart4();
                timerLinear.Stop();
                textBox_time_linear.Text = timerLinear.ElapsedTicks.ToString() + " тиков";
                textBox_time_linear.Refresh();
                //count parallel
                arrayM.Clear();
                arrayM.AddRange(arrayP.ToArray());
                timerParallel.Start();
                dataGridView1.Rows.Add();
                Thread f1 = new Thread(new ThreadStart(countPart1));
                Thread f2 = new Thread(new ThreadStart(countPart2));
                f1.Start();
                f2.Start();
                f1.Join();
                f2.Join();
                Thread f21 = new Thread(new ThreadStart(countPart3));
                Thread f22 = new Thread(new ThreadStart(countPart4));
                f21.Start();
                f21.Join();
                f22.Start();
                f22.Join();
                timerParallel.Stop();
                textBox_time_parallel.Text = timerParallel.ElapsedTicks.ToString() + " тиков";
                textBox_time_parallel.Refresh();

                //cut
                for (int i = 0; i < arrayM.Count; i++)
                {
                    dataGridView1.Rows[1].Cells[i].Value = arrayM[i];
                }
                arrayP.Clear();
                arrayM.Clear();
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
            }
            catch (Exception ex)
            {
                var logLine = DateTime.Now.ToString() + ": " + ex.Message;
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + ex.Message + Environment.NewLine);
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + ex.Message);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
            }
        }
예제 #10
0
 private void timer_valid_check()
 {
     //validation check
     if (textBox_elementsOfA.TextLength == 0)
     {
         string message = "Размер массива должен быть указан!";
         var    logLine = DateTime.Now.ToString() + ": " + message;
         log.Add(logLine);
         File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + message + Environment.NewLine);
         try
         {
             var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + message);
             toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
         }
         catch { }
         Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
         checkBox_startGenTimer.Checked = false;
         checkBox_startGenTimer.Refresh();
         textBox_elementsOfA.Text = "20";
         textBox_elementsOfA.Refresh();
         MessageBox.Show(message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     if (textBox_gen_max.TextLength == 0)
     {
         string message = "Максимум генерации должен быть указан!";
         var    logLine = DateTime.Now.ToString() + ": " + message;
         log.Add(logLine);
         File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + message + Environment.NewLine);
         try
         {
             var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + message);
             toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
         }
         catch { }
         Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
         checkBox_startGenTimer.Checked = false;
         checkBox_startGenTimer.Refresh();
         textBox_gen_max.Text = "100";
         textBox_gen_max.Refresh();
         MessageBox.Show(message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     if (textBox_gen_min.TextLength == 0)
     {
         string message = "Минимум генерации должен быть указан!";
         var    logLine = DateTime.Now.ToString() + ": " + message;
         log.Add(logLine);
         File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + message + Environment.NewLine);
         try
         {
             var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + message);
             toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
         }
         catch { }
         Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
         checkBox_startGenTimer.Checked = false;
         checkBox_startGenTimer.Refresh();
         textBox_gen_min.Text = "-100";
         textBox_gen_min.Refresh();
         MessageBox.Show(message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     if (textBox_randomFrequency.TextLength == 0)
     {
         string message = "Частота должна быть указана!";
         var    logLine = DateTime.Now.ToString() + ": " + message;
         log.Add(logLine);
         File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + message + Environment.NewLine);
         try
         {
             var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + message);
             toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
         }
         catch { }
         Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
         checkBox_startGenTimer.Checked = false;
         checkBox_startGenTimer.Refresh();
         textBox_randomFrequency.Text = "500";
         textBox_randomFrequency.Refresh();
         MessageBox.Show(message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
 }
예제 #11
0
 private void button_generate_Click(object sender, EventArgs e)
 {
     try
     {
         //validation check
         if (textBox_elementsOfA.TextLength == 0)
         {
             string message = "Размер массива должен быть указан!";
             MessageBox.Show(message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
             var logLine = DateTime.Now.ToString() + ": " + message;
             log.Add(logLine);
             File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + message + Environment.NewLine);
             try
             {
                 var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + message);
                 toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
             }
             catch { }
             Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
             return;
         }
         if (textBox_gen_max.TextLength == 0)
         {
             string message = "Максимум генерации должен быть указан!";
             MessageBox.Show(message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
             var logLine = DateTime.Now.ToString() + ": " + message;
             log.Add(logLine);
             File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + message + Environment.NewLine);
             try
             {
                 var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + message);
                 toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
             }
             catch { }
             Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
             return;
         }
         if (textBox_gen_min.TextLength == 0)
         {
             string message = "Минимум генерации должен быть указан!";
             MessageBox.Show(message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
             var logLine = DateTime.Now.ToString() + ": " + message;
             log.Add(logLine);
             File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + message + Environment.NewLine);
             try
             {
                 var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + message);
                 toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
             }
             catch { }
             Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
             return;
         }
         //logic
         button_calculate.Enabled = true;
         button_calculate.Refresh();
         //defines
         int cells_per_row = Math.Abs(int.Parse(textBox_elementsOfA.Text));
         int gen_min       = int.Parse(textBox_gen_min.Text);
         int gen_max       = int.Parse(textBox_gen_max.Text);
         //0. clear
         dataGridView1.Rows.Clear();
         arrayP.Clear();
         arrayM.Clear();
         //1. generate new
         dataGridView1.Rows.Add();
         var rnd = new Random();
         for (int i = 0; i < cells_per_row; i++)
         {
             var newNumb = rnd.Next(gen_min, gen_max);
             arrayP.Add(newNumb);
             arrayM.Add(newNumb);
             dataGridView1.Rows[0].Cells[i].Value = newNumb;
         }
     }
     catch (Exception ex)
     {
         var logLine = DateTime.Now.ToString() + ": " + ex.Message;
         log.Add(logLine);
         File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB3: " + ex.Message + Environment.NewLine);
         try
         {
             var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB3", "LAB3: " + ex.Message);
             toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
         }
         catch { }
         Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
     }
 }
예제 #12
0
        private void InvokeUpdateInfo()
        {
            //checks
            bool f_ok = true;

            if (!IsDigitsOnly(numb_a.Text))
            {
                errorProvider1.SetError(numb_a, "Field must be number!");
                var logLine    = DateTime.Now.ToString() + ": В поле A не число.";
                var lineNoTime = "LAB2: В поле A не число.";
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB2: В поле A не число.");
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB2", lineNoTime);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                f_ok = false;
            }
            if (!IsDigitsOnly(numb_b.Text))
            {
                errorProvider1.SetError(numb_b, "Field must be number!");
                var logLine    = DateTime.Now.ToString() + ": В поле B не число.";
                var lineNoTime = "LAB2: В поле B не число.";
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB2: В поле B не число.");
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB2", lineNoTime);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                f_ok = false;
            }
            if (!IsDigitsOnly(numb_n.Text))
            {
                errorProvider1.SetError(numb_n, "Field must be number!");
                var logLine    = DateTime.Now.ToString() + ": В поле N не число.";
                var lineNoTime = "LAB2: В поле N не число.";
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB2: В поле N не число.");
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB2", lineNoTime);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                f_ok = false;
            }
            if (!f_ok)
            {
                label5.Text         = "?";
                label7.Text         = "?";
                label9.Text         = "?";
                textBox_area.Text   = "Error";
                textBox_digits.Text = "Error";
                textBox3.Text       = "Error";
                textBox4.Text       = "Error";
                textBox5.Text       = "Error";
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
                return;
            }
            errorProvider1.Clear();

            //
            if (numb_a.TextLength != 0)
            {
                label5.Text = numb_a.Text;
                label7.Text = numb_a.Text;
            }
            if (numb_b.TextLength != 0)
            {
                label9.Text = numb_b.Text;
            }
            if (numb_a.TextLength != 0 && numb_b.TextLength != 0 && numb_n.TextLength != 0)
            {
                //1
                int digits = 0;
                for (int i = 0; i < numb_n.TextLength; i++)
                {
                    if (int.Parse(numb_n.Text[i].ToString()) > int.Parse(numb_a.Text))
                    {
                        digits++;
                    }
                }
                textBox_digits.Text = digits.ToString();
                //2
                if (int.Parse(numb_a.Text) < int.Parse(numb_n.Text) && int.Parse(numb_n.Text) < int.Parse(numb_b.Text))
                {
                    textBox_area.Text = "Да";
                }
                else
                {
                    textBox_area.Text = "Нет";
                }
                //3
                if (int.Parse(numb_n.Text) % 3 == 0)
                {
                    textBox3.Text = "Да";
                }
                else
                {
                    textBox3.Text = "Нет";
                }
                if (int.Parse(numb_n.Text) % 4 == 0)
                {
                    textBox4.Text = "Да";
                }
                else
                {
                    textBox4.Text = "Нет";
                }
                if (int.Parse(numb_n.Text) % 5 == 0)
                {
                    textBox5.Text = "Да";
                }
                else
                {
                    textBox5.Text = "Нет";
                }
            }
        }
예제 #13
0
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                progress_steg.Visible = true;
                progress_steg.Refresh();
                label_progress.Visible = true;
                label_progress.Refresh();
                textBox_message.Text = "";
                if (!File.Exists("tempImg.bmp"))
                {
                    throw new Exception("Попытка расшифровки без загрузки стеганоконтейнера!");
                }
                container_bytes.Clear();
                using (FileStream file = File.OpenRead("tempImg.bmp"))
                {
                    BinaryReader binaryReader = new BinaryReader(file);
                    binaryReader.BaseStream.Position = 0;
                    byte[] tempBytes = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);
                    container_bytes.AddRange(tempBytes);
                }
                //reading headers
                //Header-offset
                int header_offset = (int)readHexReverse(container_bytes, 0x0D, 4);
                //ImageSize (pixels)
                int img_pixels = (int)readHexReverse(container_bytes, 0x25, 4);
                img_pixels /= 3;
                //ImageSize (pixels - msgLen)
                int maxLen = (int)readHexReverse(container_bytes, 0x25, 4); //bytes
                maxLen /= 3;                                                //pixels
                maxLen -= 2;                                                //header 2 chars
                maxLen  = (int)Math.Floor((double)(maxLen / 16));           //chars in 2b
                //Image width
                int img_width = (int)readHexReverse(container_bytes, 0x15, 4);
                //Image height
                int img_height = (int)readHexReverse(container_bytes, 0x19, 4);
                //Bit per pixel
                int bit_per_pixel   = (int)readHexReverse(container_bytes, 0x1D, 2);
                int bytes_per_pixel = bit_per_pixel / 8;
                //Compression
                int img_compression = (int)readHexReverse(container_bytes, 0x21, 4);
                if (img_compression != 0)
                {
                    throw new Exception("Метод компрессии BMP не поддерживается!");
                }
                //padding calc
                int delta            = img_width % 4;
                int padding_per_line = Convert.ToBoolean(delta) ? 4 - delta : 0;
                //decoding
                //read msglen
                string msgBits = "";
                for (int i = header_offset + 2; i < header_offset + 2 + (bytes_per_pixel * 16); i += bytes_per_pixel)
                {
                    if (getBit((byte)container_bytes[i], 0))
                    {
                        msgBits += "1";
                    }
                    else
                    {
                        msgBits += "0";
                    }
                }
                msgBits = Reverse(msgBits);
                int msgLen = binStringToInt(msgBits);

                int  msgBitsRead = 0;
                int  rank        = -1;
                bool doneMsg     = false;
                msgBits = "";

                while (msgBitsRead < (msgLen * 8) + 16)
                {
                    rank++;
                    int memoryPointer = header_offset + 2;
                    for (int i = 0; (i < img_height) && !doneMsg; i++)    //height
                    {
                        for (int j = 0; (j < img_width) && !doneMsg; j++) //scans
                        {
                            if (getBit((byte)container_bytes[memoryPointer], rank))
                            {
                                msgBits += "1";
                            }
                            else
                            {
                                msgBits += "0";
                            }
                            msgBitsRead++;
                            memoryPointer += bytes_per_pixel;
                            if (msgBitsRead >= (msgLen * 8) + 16)
                            {
                                doneMsg = true;
                                break;
                            }
                        }
                    }
                }
                msgBits = msgBits.Substring(16);

                /*for (int i = header_offset + 2 + (bytes_per_pixel * 16); i < header_offset + 2 + (bytes_per_pixel * 16) + (bytes_per_pixel * 8 * msgLen); i+= bytes_per_pixel)
                 * {
                 *  if (getBit((byte)container_bytes[i], 0))
                 *              msgBits += "1";
                 *          else
                 *              msgBits += "0";
                 * }*/
                string tempChar = "";
                for (int i = 0; i < msgBits.Length; i++)
                {
                    tempChar += msgBits[i];
                    if ((i + 1) % (sizeof(char) * 8) == 0 && (i != 0))
                    {
                        char Symb = (char)binStringToInt(tempChar);
                        textBox_message.Text += Symb;
                        tempChar              = "";
                    }
                }
                progress_steg.Visible = true;
                progress_steg.Refresh();
                label_progress.Visible = true;
                label_progress.Refresh();
            }
            catch (Exception ex)
            {
                var logLine = DateTime.Now.ToString() + ": " + ex.Message;
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB2_TZSPD: " + ex.Message + Environment.NewLine);
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB2_TZSPD", "LAB2_TZSPD: " + ex.Message);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
                MessageBox.Show(ex.Message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #14
0
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                /*container_bytes.Clear();
                 * if (Container.Image != null)
                 * {
                 *  using (MemoryStream bits = new MemoryStream())
                 *  {
                 *      using (Bitmap bmp = new Bitmap(Container.Image.Width, Container.Image.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                 *      {
                 *          using (Graphics g = Graphics.FromImage(bmp))
                 *          {
                 *              g.DrawImage(Container.Image, new Point(0, 0));
                 *          }
                 *          bmp.Save(bits, System.Drawing.Imaging.ImageFormat.Bmp);
                 *      }
                 *      //Container.Image.Save(bits, ImageFormat.Bmp);
                 *      using (BinaryReader binaryReader = new BinaryReader(bits))
                 *      {
                 *          byte[] tempBytes = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);
                 *          container_bytes.AddRange(tempBytes);
                 *      }
                 *  }
                 * }*/

                if (int.Parse(textBox_maxMsgLen.Text) < textBox_message.TextLength)
                {
                    MessageBox.Show("Размер сообщения слишком велик, будут задействованы более старшие биты.", "Info.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                progress_steg.Visible = true;
                progress_steg.Refresh();
                label_progress.Visible = true;
                label_progress.Refresh();
                label_task.Visible = true;
                label_task.Refresh();
                if (SteganoContainer.Image != null)
                {
                    SteganoContainer.Image.Dispose();
                }

                string msgBits     = "";
                int    msgLenBytes = 0;
                //message in binary
                label_task.Text = "Подготовка";
                label_task.Refresh();
                for (int i = 0; i < textBox_message.TextLength; i++)
                {
                    int progress = 100 * i / textBox_message.TextLength;
                    progress_steg.Value = progress;
                    label_progress.Text = progress.ToString() + " %";
                    string tempBin = "";
                    for (int j = 0; j < sizeof(char) * 8; j++)
                    {
                        if (getBit(textBox_message.Text[i], j))
                        {
                            tempBin += "1";
                        }
                        else
                        {
                            tempBin += "0";
                        }
                    }
                    for (int j = tempBin.Length - 1; j != -1; j--)
                    {
                        msgBits += tempBin[j];
                    }
                }
                msgLenBytes = msgBits.Length / 8;
                string msgLenBytesBits = "";
                //msgLen in binary
                for (int i = 0; i < 16; i++)
                {
                    if (getBit(msgLenBytes, i))
                    {
                        msgLenBytesBits += "1";
                    }
                    else
                    {
                        msgLenBytesBits += "0";
                    }
                }
                //reading headers
                //Header-offset
                int header_offset = (int)readHexReverse(container_bytes, 0x0D, 4);
                //ImageSize (pixels)
                int img_pixels = (int)readHexReverse(container_bytes, 0x25, 4);
                img_pixels /= 3;
                //Image width
                int img_width = (int)readHexReverse(container_bytes, 0x15, 4);
                //Image height
                int img_height = (int)readHexReverse(container_bytes, 0x19, 4);
                //Bit per pixel
                int bit_per_pixel   = (int)readHexReverse(container_bytes, 0x1D, 2);
                int bytes_per_pixel = bit_per_pixel / 8;
                //Compression
                int img_compression = (int)readHexReverse(container_bytes, 0x21, 4);
                if (img_compression != 0)
                {
                    throw new Exception("Метод компрессии BMP не поддерживается!");
                }
                //padding calc
                int delta            = img_width % 4;
                int padding_per_line = Convert.ToBoolean(delta) ? 4 - delta : 0;
                //hiding
                label_task.Text = "В процессе";
                label_task.Refresh();
                string combinedMsg    = msgLenBytesBits + msgBits;
                int    messagePointer = 0;
                int    rank           = -1;
                bool   doneMsg        = false;
                while (messagePointer < combinedMsg.Length)
                {
                    rank++;
                    int pixelMemoryPointer = header_offset + 2;           //To set to LSB
                    for (int i = 0; (i < img_height) && !doneMsg; i++)    //height
                    {
                        for (int j = 0; (j < img_width) && !doneMsg; j++) //scans
                        {
                            int progress = (100 * messagePointer / msgBits.Length);
                            if (progress <= 100)
                            {
                                progress_steg.Value = progress;
                            }
                            progress_steg.Refresh();
                            label_progress.Text = (progress > 100?100:progress).ToString() + " %";
                            label_progress.Refresh();
                            //3 bytes per pixel
                            if (combinedMsg[messagePointer] == '1' && !getBit((byte)container_bytes[pixelMemoryPointer], rank))
                            {
                                //increment
                                byte temp = (byte)container_bytes[pixelMemoryPointer];
                                temp++;
                                container_bytes.RemoveAt(pixelMemoryPointer);
                                container_bytes.Insert(pixelMemoryPointer, temp);
                            }
                            else if (combinedMsg[messagePointer] == '0' && getBit((byte)container_bytes[pixelMemoryPointer], rank))
                            {
                                //decrement
                                byte temp = (byte)container_bytes[pixelMemoryPointer];
                                temp--;
                                container_bytes.RemoveAt(pixelMemoryPointer);
                                container_bytes.Insert(pixelMemoryPointer, temp);
                            }
                            messagePointer++;
                            if (messagePointer >= combinedMsg.Length)
                            {
                                doneMsg = true;
                            }
                            pixelMemoryPointer += bytes_per_pixel;
                        }
                        pixelMemoryPointer += padding_per_line;
                    }
                }
                using (FileStream tempImg = File.Create("tempImg.bmp"))
                {
                    foreach (byte b in container_bytes)
                    {
                        tempImg.WriteByte(b);
                    }
                }
                Image img;
                using (var bmpTemp = new Bitmap("tempImg.bmp"))
                {
                    img = new Bitmap(bmpTemp);
                }
                SteganoContainer.Image = img;
                progress_steg.Visible  = true;
                progress_steg.Refresh();
                label_progress.Visible = true;
                label_progress.Refresh();
                label_task.Visible = false;
                label_task.Refresh();
            }
            catch (Exception ex)
            {
                var logLine = DateTime.Now.ToString() + ": " + ex.Message;
                log.Add(logLine);
                File.AppendAllText(Directory.GetCurrentDirectory() + "\\global_log.log", DateTime.Now.ToString() + ": LAB2_TZSPD: " + ex.Message + Environment.NewLine);
                try
                {
                    var time_ms = MSSQL_logging.log_error_onTimer(DateTime.Now, "LAB2_TZSPD", "LAB2_TZSPD: " + ex.Message);
                    toolStripStatusLabel1.Text = "Логирование выполнено за " + time_ms + "мс";
                }
                catch { }
                Invoke(new UpdateLogBoxDelegate(InvokeUpdateLogBox));
                MessageBox.Show(ex.Message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string host = textBox_host.Text;
                string port = textBox_port.Text;
                //resolving host string
                string hostString = "tcp:" + host;
                if (port != "Default" && port != "")
                {
                    hostString += ", " + port;
                }


                string getLoginsLogin = "******";
                string getLoginsPassw = "ceb3478&Bc23b2&";

                Microsoft.Data.SqlClient.SqlConnectionStringBuilder extractLoginsConnBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder();

                extractLoginsConnBuilder.DataSource             = hostString;
                extractLoginsConnBuilder.ConnectTimeout         = 10;
                extractLoginsConnBuilder.UserID                 = getLoginsLogin;
                extractLoginsConnBuilder.Password               = getLoginsPassw;
                extractLoginsConnBuilder.Authentication         = Microsoft.Data.SqlClient.SqlAuthenticationMethod.SqlPassword;
                extractLoginsConnBuilder.IntegratedSecurity     = false;
                extractLoginsConnBuilder.TrustServerCertificate = true;

                string        queryString   = "select * from logins";
                StringBuilder errorMessages = new StringBuilder();

                int user_id = 0;

                using (Microsoft.Data.SqlClient.SqlConnection connection1 = new Microsoft.Data.SqlClient.SqlConnection(extractLoginsConnBuilder.ConnectionString))
                {
                    Microsoft.Data.SqlClient.SqlCommand command1 = new Microsoft.Data.SqlClient.SqlCommand(queryString, connection1);
                    try
                    {
                        command1.Connection.Open();
                        command1.ExecuteNonQuery();

                        var reader = command1.ExecuteReader();
                        if (!reader.HasRows)
                        {
                            throw new Exception("Provided login not found or password is incorrect");
                        }

                        string login    = textBox_login.Text;
                        string password = textBox_password.Text;
                        string hash     = MathOperations.sha256(password);

                        bool login_in = false;
                        while (reader.Read())
                        {
                            if (reader.GetString(1) == login && reader.GetString(2) == hash)
                            {
                                user_id  = reader.GetInt32(0);
                                login_in = true;
                            }
                        }
                        reader.Close();

                        command1.Connection.Close();
                        if (!login_in)
                        {
                            throw new Exception("Provided login not found or password is incorrect");
                        }
                    }
                    catch (Microsoft.Data.SqlClient.SqlException ex)
                    {
                        for (int i = 0; i < ex.Errors.Count; i++)
                        {
                            errorMessages.Append("Index #" + i + "\n" +
                                                 "Message: " + ex.Errors[i].Message + "\n" +
                                                 "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                                                 "Source: " + ex.Errors[i].Source + "\n" +
                                                 "Procedure: " + ex.Errors[i].Procedure + "\n");
                        }
                        throw new Exception(errorMessages.ToString());
                    }
                }

                string basicLogin = "******";
                string basicPassw = "n3i7A7834bo&T21h@tbn";

                extractLoginsConnBuilder.UserID   = basicLogin;
                extractLoginsConnBuilder.Password = basicPassw;

                queryString = "select * from keys";

                Microsoft.Data.SqlClient.SqlConnection connection = new Microsoft.Data.SqlClient.SqlConnection(extractLoginsConnBuilder.ConnectionString);
                Microsoft.Data.SqlClient.SqlCommand    command    = new Microsoft.Data.SqlClient.SqlCommand(queryString, connection);
                try
                {
                    command.Connection.Open();
                    command.ExecuteNonQuery();

                    //check if user has key
                    var  reader  = command.ExecuteReader();
                    bool has_key = false;

                    while (reader.Read())
                    {
                        if (reader.GetInt32(0) == user_id)
                        {
                            has_key = true;
                        }
                    }
                    reader.Close();

                    if (!has_key)
                    {
                        MessageBox.Show("Ключ не найден. Сейчас будет сгенерирован новый ключ и добавлен в базу данных.", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        var aesInst       = System.Security.Cryptography.Aes.Create();
                        var privkey       = aesInst.Key;
                        var iv            = aesInst.IV;
                        var privKeysha256 = MathOperations.sha256_byte(textBox_password.Text);
                        var ivmd5         = MathOperations.md5_byte(textBox_password.Text);

                        //enc private key with sha256(pwd) and md5(pwd)
                        aesInst.Key = privKeysha256;
                        aesInst.IV  = ivmd5;

                        var    Encrypted_SK            = aesInst.CreateEncryptor().TransformFinalBlock(privkey, 0, privkey.Length);
                        string Encrypted_SK_String_HEX = "0x";
                        foreach (byte part in Encrypted_SK)
                        {
                            Encrypted_SK_String_HEX += part.ToString("X2");
                        }
                        var    Encrypted_IV            = aesInst.CreateEncryptor().TransformFinalBlock(iv, 0, iv.Length);
                        string Encrypted_IV_String_HEX = "0x";
                        foreach (byte part in Encrypted_IV)
                        {
                            Encrypted_IV_String_HEX += part.ToString("X2");
                        }

                        queryString = "insert into keys values (" + user_id.ToString() + ", " + Encrypted_SK_String_HEX + ", " + Encrypted_IV_String_HEX + ")";
                        Microsoft.Data.SqlClient.SqlCommand command_newkey = new Microsoft.Data.SqlClient.SqlCommand(queryString, connection);
                        //command.Connection.Open();
                        command_newkey.ExecuteNonQuery();
                        command_newkey.Connection.Close();
                    }
                    //save session data
                    MSSQL_logging.user_id             = user_id;
                    MSSQL_logging.userpassword        = textBox_password.Text;
                    MSSQL_logging.database_connection = connection;
                    MSSQL_logging.GetPrivateKeyFromDB();

                    command.Connection.Close();

                    //open start panel
                    this.Hide();
                    var form_start = new Form_start();
                    form_start.Closed += (s, args) => this.Close();
                    form_start.Show();
                }
                catch (Microsoft.Data.SqlClient.SqlException ex)
                {
                    for (int i = 0; i < ex.Errors.Count; i++)
                    {
                        errorMessages.Append("Index #" + i + "\n" +
                                             "Message: " + ex.Errors[i].Message + "\n" +
                                             "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                                             "Source: " + ex.Errors[i].Source + "\n" +
                                             "Procedure: " + ex.Errors[i].Procedure + "\n");
                    }
                    throw new Exception(errorMessages.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }