Advertisement
PhotoShaman

VOOu

Nov 24th, 2017
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 21.27 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. //using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using System.Security.Cryptography;
  16. using Microsoft.Win32;
  17. using System.IO;
  18. using System.Threading;
  19. using System.Collections;
  20. using System.Drawing;
  21.  
  22. namespace ProjectCryptor
  23. {
  24.     /// <summary>
  25.     /// Логика взаимодействия для MainWindow.xaml
  26.     /// </summary>
  27.     public partial class MainWindow : Window
  28.     {
  29.         #region Window
  30.         public MainWindow()
  31.         {
  32.             InitializeComponent();
  33.             for (int i = 1; i <= 8; i *= 2)
  34.                 KeySize.Items.Add(512 * i);
  35.             KeySize.SelectedIndex = 2;
  36.         }
  37.  
  38.         private void Window_MouseDown(object sender, MouseButtonEventArgs e)
  39.         {
  40.             if (e.ChangedButton != MouseButton.Right)
  41.                 DragMove();
  42.         }
  43.  
  44.         private void ApplicationClose(object sender, RoutedEventArgs e)
  45.         {
  46.             System.Diagnostics.Process.GetCurrentProcess().Kill();
  47.         }
  48.  
  49.         private void ApplicationHide(object sender, RoutedEventArgs e)
  50.         {
  51.             WindowState = WindowState.Minimized;
  52.         }
  53.         #endregion
  54.  
  55.         //----------------------------RSA----------------------------
  56.         #region RSA
  57.         private string PublicKey { get; set; }
  58.         private string PrivateKey { get; set; }
  59.  
  60.         private bool IsKeyGenerated;
  61.  
  62.         private RSACryptoServiceProvider rsaCryptoServiceProvider;
  63.  
  64.         private void CreateKeys(object sender, RoutedEventArgs e)
  65.         {
  66.             Thread t = new Thread(delegate ()
  67.             {
  68.                 Dispatcher.Invoke(() =>
  69.                 {
  70.                     CreateKeysButton.Visibility = Visibility.Hidden;
  71.                     CreateKeysSpinner.Visibility = Visibility.Visible;
  72.                     CreateKeysLabel.Visibility = Visibility.Visible;
  73.                     rsaCryptoServiceProvider = new RSACryptoServiceProvider((int)KeySize.SelectedItem);
  74.                 });
  75.                 PublicKey = rsaCryptoServiceProvider.ToXmlString(false);
  76.                 PrivateKey = rsaCryptoServiceProvider.ToXmlString(true);
  77.                 Dispatcher.Invoke(() =>
  78.                 {
  79.                     PrivateKeyTextBox.Text = PrivateKey;
  80.                     PublicKeyTextBox.Text = PublicKey;
  81.                     IsKeyGenerated = true;
  82.                     CreateKeysButton.Visibility = Visibility.Visible;
  83.                     CreateKeysSpinner.Visibility = Visibility.Hidden;
  84.                     CreateKeysLabel.Visibility = Visibility.Hidden;
  85.                 });
  86.             });
  87.             t.SetApartmentState(ApartmentState.STA);
  88.             t.Start();
  89.         }
  90.  
  91.         private void Encrypt(object sender, RoutedEventArgs e)
  92.         {
  93.             if (!IsKeyGenerated)
  94.                 return;
  95.  
  96.             byte[] plainText = Encoding.Unicode.GetBytes(DecryptTextBox.Text);
  97.             try
  98.             {
  99.                 byte[] encrypted = rsaCryptoServiceProvider.Encrypt(plainText, false);
  100.                 EncryptTextBox.Text = Convert.ToBase64String(encrypted);
  101.             }
  102.             catch (Exception)
  103.             {
  104.                 MessageBox.Show("Ошибка. Слишком большой текст для данного ключа");
  105.             }
  106.         }
  107.  
  108.         private void Decrypt(object sender, RoutedEventArgs e)
  109.         {
  110.             if (string.IsNullOrEmpty(EncryptTextBox.Text))
  111.                 return;
  112.  
  113.             byte[] x = (Convert.FromBase64String(EncryptTextBox.Text));
  114.  
  115.             byte[] decrypted = rsaCryptoServiceProvider.Decrypt(x, false);
  116.             DecryptTextBox.Text = Encoding.Unicode.GetString(Convert.FromBase64String(Convert.ToBase64String(decrypted)));
  117.         }
  118.  
  119.         private void LoadPublicKey_Click(object sender, RoutedEventArgs e)
  120.         {
  121.             PublicKeyTextBox.Text = OpenTxtFile();
  122.         }
  123.         private void SavePublicKey_Click(object sender, RoutedEventArgs e)
  124.         {
  125.             SaveTxtFile(PublicKeyTextBox.Text);
  126.         }
  127.         private void LoadPrivateKey_Click(object sender, RoutedEventArgs e)
  128.         {
  129.             PrivateKeyTextBox.Text = OpenTxtFile();
  130.         }
  131.         private void SavePrivateKey_Click(object sender, RoutedEventArgs e)
  132.         {
  133.             SaveTxtFile(PrivateKeyTextBox.Text);
  134.         }
  135.         private void LoadEncryptText_Click(object sender, RoutedEventArgs e)
  136.         {
  137.             EncryptTextBox.Text = OpenTxtFile();
  138.         }
  139.         private void SaveEncryptText_Click(object sender, RoutedEventArgs e)
  140.         {
  141.             SaveTxtFile(EncryptTextBox.Text);
  142.         }
  143.         private void LoadDecryptText_Click(object sender, RoutedEventArgs e)
  144.         {
  145.             DecryptTextBox.Text = OpenTxtFile();
  146.         }
  147.         private void SaveDecryptText_Click(object sender, RoutedEventArgs e)
  148.         {
  149.             SaveTxtFile(DecryptTextBox.Text);
  150.         }
  151.  
  152.         private string OpenTxtFile()
  153.         {
  154.             OpenFileDialog LoadTextDialog = new OpenFileDialog
  155.             {
  156.                 Filter = "Текстовые файлы(*.txt)|*.txt",
  157.                 CheckFileExists = true
  158.             };
  159.             if (LoadTextDialog.ShowDialog() == true)
  160.             {
  161.                 return File.ReadAllText(LoadTextDialog.FileName, Encoding.UTF8);
  162.             }
  163.             return "";
  164.         }
  165.  
  166.         private void SaveTxtFile(string text)
  167.         {
  168.             SaveFileDialog SaveTxtDialog = new SaveFileDialog
  169.             {
  170.                 Filter = "Текстовые файлы(*.txt)|*.txt"
  171.             };
  172.             if (SaveTxtDialog.ShowDialog() == true)
  173.             {
  174.                 using (StreamWriter sw = new StreamWriter(SaveTxtDialog.OpenFile(), System.Text.Encoding.UTF8))
  175.                 {
  176.                     sw.Write(text);
  177.                     sw.Close();
  178.                 }
  179.             }
  180.         }
  181.         #endregion
  182.  
  183.         //----------------------------LSB----------------------------
  184.  
  185.         OpenFileDialog LoadImageDialog = new OpenFileDialog
  186.         {
  187.             Filter = "Изображение(*.bmp)|*.bmp",
  188.             CheckFileExists = true
  189.         };
  190.  
  191.         SaveFileDialog SaveImageDialog = new SaveFileDialog
  192.         {
  193.             Filter = "Изображение(*.bmp)|*.bmp"
  194.         };
  195.  
  196.         string SourceImagePath, EncryptedImagePath;
  197.         Bitmap SourceImageBitmap, EncryptedImageBitmap;
  198.  
  199.         private void LoadSourceText_Click(object sender, RoutedEventArgs e)
  200.         {
  201.             SourceText.Text = OpenTxtFile();
  202.         }
  203.  
  204.         private void LoadSourceImage_Click(object sender, RoutedEventArgs e)
  205.         {
  206.             if (LoadImageDialog.ShowDialog() == true)
  207.             {
  208.                 SourceImagePath = LoadImageDialog.FileName;
  209.                 SourceImageBitmap = new Bitmap(SourceImagePath);
  210.                 SourceImage.Source = BitmapToImageSource(SourceImageBitmap);
  211.             }
  212.         }
  213.  
  214.         private void LoadEncryptedImage_Click(object sender, RoutedEventArgs e)
  215.         {
  216.             if (LoadImageDialog.ShowDialog() == true)
  217.             {
  218.                 EncryptedImagePath = LoadImageDialog.FileName;
  219.                 EncryptedImageBitmap = new Bitmap(EncryptedImagePath);
  220.                 EncryptedImage.Source = BitmapToImageSource(EncryptedImageBitmap);
  221.             }
  222.         }
  223.  
  224.         private void SaveSourceText_Click(object sender, RoutedEventArgs e)
  225.         {
  226.             SaveTxtFile(Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(DecryptSourceText.Text)));
  227.         }
  228.  
  229.         private void SaveEncryptImage_Click(object sender, RoutedEventArgs e)
  230.         {
  231.             if (SaveImageDialog.ShowDialog() == true)
  232.             {
  233.                 string sFilePic = SaveImageDialog.FileName;
  234.                 if (sFilePic == "")
  235.                     return;
  236.  
  237.                 FileStream wFile;
  238.                 try
  239.                 {
  240.                     wFile = new FileStream(sFilePic, FileMode.Create); //открываем поток на запись результатов
  241.                 }
  242.                 catch (IOException)
  243.                 {
  244.                     MessageBox.Show("Ошибка открытия файла на запись", "Ошибка");
  245.                     return;
  246.                 }
  247.  
  248.                 EncryptedImageBitmap.Save(wFile, System.Drawing.Imaging.ImageFormat.Bmp);
  249.                 wFile.Close(); //закрываем поток
  250.             }
  251.         }
  252.  
  253.         //------------------------------------------------------------
  254.  
  255.         private void EncryptImageButton_Click(object sender, RoutedEventArgs e)
  256.         {
  257.             if (SourceImage.Source == null || SourceText.Text == "")
  258.                 return;
  259.             if (SourceText.Text.Count() > 16777215)
  260.             {
  261.                 MessageBox.Show("Слишком большой текст", "Ошибка");
  262.                 return;
  263.             }
  264.             Bitmap bPic = new Bitmap(SourceImagePath);
  265.  
  266.             BinaryReader bText = new BinaryReader(
  267.                 new MemoryStream(Encoding.UTF8.GetBytes(SourceText.Text ?? "")), Encoding.ASCII);
  268.  
  269.             List<byte> bList = new List<byte>();
  270.             while (bText.PeekChar() != -1) //считали весь текстовый файл для шифрования в лист байтs
  271.             {
  272.                 bList.Add(bText.ReadByte());
  273.             }
  274.             int CountText = bList.Count; // в CountText - количество в байтах текста, который нужно закодировать
  275.             bText.Close();
  276.  
  277.             //проверяем, поместиться ли исходный текст в картинке
  278.             if (CountText > ((bPic.Width * bPic.Height)) - 4)
  279.             {
  280.                 MessageBox.Show("Выбранная картинка мала для размещения выбранного текста", "Информация");
  281.                 return;
  282.             }
  283.  
  284.             //проверяем, может быть картинка уже зашифрована
  285.             if (IsEncryption(bPic))
  286.             {
  287.                 MessageBox.Show("Файл уже зашифрован", "Информация");
  288.                 return;
  289.             }
  290.  
  291.             byte[] Symbol = Encoding.GetEncoding(1251).GetBytes("/");
  292.             BitArray ArrBeginSymbol = ByteToBit(Symbol[0]);
  293.             Color curColor = bPic.GetPixel(0, 0);
  294.             BitArray tempArray = ByteToBit(curColor.R);
  295.             tempArray[0] = ArrBeginSymbol[0];
  296.             tempArray[1] = ArrBeginSymbol[1];
  297.             byte nR = BitToByte(tempArray);
  298.  
  299.             tempArray = ByteToBit(curColor.G);
  300.             tempArray[0] = ArrBeginSymbol[2];
  301.             tempArray[1] = ArrBeginSymbol[3];
  302.             tempArray[2] = ArrBeginSymbol[4];
  303.             byte nG = BitToByte(tempArray);
  304.  
  305.             tempArray = ByteToBit(curColor.B);
  306.             tempArray[0] = ArrBeginSymbol[5];
  307.             tempArray[1] = ArrBeginSymbol[6];
  308.             tempArray[2] = ArrBeginSymbol[7];
  309.             byte nB = BitToByte(tempArray);
  310.  
  311.             Color nColor = Color.FromArgb(nR, nG, nB);
  312.             bPic.SetPixel(0, 0, nColor);
  313.             //то есть в первом пикселе будет символ /, который говорит о том, что картика зашифрована
  314.             try
  315.             {
  316.                 WriteCountText(CountText, bPic); //записываем количество символов для шифрования
  317.             }
  318.             catch (Exception)
  319.             {
  320.                 MessageBox.Show("FFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU");
  321.                 return;
  322.             }
  323.             int index = 0;
  324.             bool st = false;
  325.             for (int i = 4; i < bPic.Width; i++)
  326.             {
  327.                 for (int j = 0; j < bPic.Height; j++)
  328.                 {
  329.                     Color pixelColor = bPic.GetPixel(i, j);
  330.                     if (index == bList.Count)
  331.                     {
  332.                         st = true;
  333.                         break;
  334.                     }
  335.                     BitArray colorArray = ByteToBit(pixelColor.R);
  336.                     BitArray messageArray = ByteToBit(bList[index]);
  337.                     colorArray[0] = messageArray[0]; //меняем
  338.                     colorArray[1] = messageArray[1]; // в нашем цвете биты
  339.                     byte newR = BitToByte(colorArray);
  340.  
  341.                     colorArray = ByteToBit(pixelColor.G);
  342.                     colorArray[0] = messageArray[2];
  343.                     colorArray[1] = messageArray[3];
  344.                     colorArray[2] = messageArray[4];
  345.                     byte newG = BitToByte(colorArray);
  346.  
  347.                     colorArray = ByteToBit(pixelColor.B);
  348.                     colorArray[0] = messageArray[5];
  349.                     colorArray[1] = messageArray[6];
  350.                     colorArray[2] = messageArray[7];
  351.                     byte newB = BitToByte(colorArray);
  352.  
  353.                     Color newColor = Color.FromArgb(newR, newG, newB);
  354.                     bPic.SetPixel(i, j, newColor);
  355.                     index++;
  356.                 }
  357.                 if (st)
  358.                 {
  359.                     break;
  360.                 }
  361.             }
  362.             EncryptedImageBitmap = bPic;
  363.             EncryptedImage.Source = BitmapToImageSource(EncryptedImageBitmap);
  364.         }
  365.  
  366.         private void DecryptImageButton_Click(object sender, RoutedEventArgs e)
  367.         {
  368.             if (EncryptedImage.Source == null)
  369.                 return;
  370.             Bitmap bPic = EncryptedImageBitmap;
  371.             if (!IsEncryption(bPic))
  372.             {
  373.                 MessageBox.Show("В файле нет зашифрованной информации", "Информация");
  374.                 return;
  375.             }
  376.  
  377.             int countSymbol = ReadCountText(bPic); //считали количество зашифрованных символов
  378.             byte[] message = new byte[countSymbol];
  379.             int index = 0;
  380.             bool st = false;
  381.             for (int i = 4; i < bPic.Width; i++)
  382.             {
  383.                 for (int j = 0; j < bPic.Height; j++)
  384.                 {
  385.                     Color pixelColor = bPic.GetPixel(i, j);
  386.                     if (index == message.Length)
  387.                     {
  388.                         st = true;
  389.                         break;
  390.                     }
  391.                     BitArray colorArray = ByteToBit(pixelColor.R);
  392.                     BitArray messageArray = ByteToBit(pixelColor.R); ;
  393.                     messageArray[0] = colorArray[0];
  394.                     messageArray[1] = colorArray[1];
  395.  
  396.                     colorArray = ByteToBit(pixelColor.G);
  397.                     messageArray[2] = colorArray[0];
  398.                     messageArray[3] = colorArray[1];
  399.                     messageArray[4] = colorArray[2];
  400.  
  401.                     colorArray = ByteToBit(pixelColor.B);
  402.                     messageArray[5] = colorArray[0];
  403.                     messageArray[6] = colorArray[1];
  404.                     messageArray[7] = colorArray[2];
  405.                     message[index] = BitToByte(messageArray);
  406.                     index++;
  407.                 }
  408.                 if (st)
  409.                 {
  410.                     break;
  411.                 }
  412.             }
  413.             DecryptSourceText.Text = Encoding.GetEncoding(65001/*<-UTF-8*//*1251*/).GetString(message);
  414.         }
  415.  
  416.         //---------------------------------------------
  417.  
  418.         /*Проверяет, зашифрован ли файл, возвраещает true, если символ в первом пикслеле равен / иначе false */
  419.         private bool IsEncryption(Bitmap scr)
  420.         {
  421.             byte[] rez = new byte[1];
  422.             Color color = scr.GetPixel(0, 0);
  423.             BitArray colorArray = ByteToBit(color.R); //получаем байт цвета и преобразуем в массив бит
  424.             BitArray messageArray = ByteToBit(color.R); ;//инициализируем результирующий массив бит
  425.             messageArray[0] = colorArray[0];
  426.             messageArray[1] = colorArray[1];
  427.  
  428.             colorArray = ByteToBit(color.G);//получаем байт цвета и преобразуем в массив бит
  429.             messageArray[2] = colorArray[0];
  430.             messageArray[3] = colorArray[1];
  431.             messageArray[4] = colorArray[2];
  432.  
  433.             colorArray = ByteToBit(color.B);//получаем байт цвета и преобразуем в массив бит
  434.             messageArray[5] = colorArray[0];
  435.             messageArray[6] = colorArray[1];
  436.             messageArray[7] = colorArray[2];
  437.             rez[0] = BitToByte(messageArray); //получаем байт символа, записанного в 1 пикселе
  438.             return Encoding.GetEncoding(1251).GetString(rez) == "/";
  439.         }
  440.  
  441.         /*Записыает количество символов для шифрования в первые биты картинки */
  442.         private void WriteCountText(int count, Bitmap src)
  443.         {
  444.             string bits = "";
  445.             for (int i = 23; i >= 0; i--)
  446.             {
  447.                 bits += (count >> i) & 0x01;
  448.             }
  449.             for (int i = 0; i < 3; i++)
  450.             {
  451.                 Color pColor = src.GetPixel(0, i + 1); //1, 2, 3 пикселы
  452.                 BitArray bitsCurColor = ByteToBit(pColor.R); //бит цветов текущего пикселя
  453.                 bitsCurColor[0] = bits[0 + i * 8] == '1';
  454.                 bitsCurColor[1] = bits[1 + i * 8] == '1';
  455.                 byte nR = BitToByte(bitsCurColor); //новый бит цвета пиксея
  456.  
  457.                 bitsCurColor = ByteToBit(pColor.G);//бит бит цветов текущего пикселя
  458.                 bitsCurColor[0] = bits[2 + i * 8] == '1';
  459.                 bitsCurColor[1] = bits[3 + i * 8] == '1';
  460.                 bitsCurColor[2] = bits[4 + i * 8] == '1';
  461.                 byte nG = BitToByte(bitsCurColor);//новый цвет пиксея
  462.  
  463.                 bitsCurColor = ByteToBit(pColor.B);//бит бит цветов текущего пикселя
  464.                 bitsCurColor[0] = bits[5 + i * 8] == '1';
  465.                 bitsCurColor[1] = bits[6 + i * 8] == '1';
  466.                 bitsCurColor[2] = bits[7 + i * 8] == '1';
  467.                 byte nB = BitToByte(bitsCurColor);//новый цвет пиксея
  468.  
  469.                 Color nColor = Color.FromArgb(nR, nG, nB); //новый цвет из полученных битов
  470.                 src.SetPixel(0, i + 1, nColor); //записали полученный цвет в картинку
  471.             }
  472.         }
  473.  
  474.         /*Читает количество символов для дешифрования из первых бит картинки*/
  475.         private int ReadCountText(Bitmap src)
  476.         {
  477.             string count = "";
  478.             for (int i = 0; i < 3; i++)
  479.             {
  480.                 Color color = src.GetPixel(0, i + 1); //цвет 1, 2, 3 пикселей
  481.                 BitArray colorArray = ByteToBit(color.R); //биты цвета
  482.                 count += colorArray[0] ? "1" : "0";
  483.                 count += colorArray[1] ? "1" : "0";
  484.  
  485.                 colorArray = ByteToBit(color.G);
  486.                 count += colorArray[0] ? "1" : "0";
  487.                 count += colorArray[1] ? "1" : "0";
  488.                 count += colorArray[2] ? "1" : "0";
  489.  
  490.                 colorArray = ByteToBit(color.B);
  491.                 count += colorArray[0] ? "1" : "0";
  492.                 count += colorArray[1] ? "1" : "0";
  493.                 count += colorArray[2] ? "1" : "0";
  494.             }
  495.             return Convert.ToInt32(count, 2);
  496.         }
  497.  
  498.  
  499.         private BitArray ByteToBit(byte src)
  500.         {
  501.             BitArray bitArray = new BitArray(8);
  502.             bool st = false;
  503.             for (int i = 0; i < 8; i++)
  504.             {
  505.                 if ((src >> i & 1) == 1)
  506.                 {
  507.                     st = true;
  508.                 }
  509.                 else st = false;
  510.                 bitArray[i] = st;
  511.             }
  512.             return bitArray;
  513.         }
  514.  
  515.         private byte BitToByte(BitArray scr)
  516.         {
  517.             byte num = 0;
  518.             for (int i = 0; i < scr.Count; i++)
  519.                 if (scr[i] == true)
  520.                     num += (byte)Math.Pow(2, i);
  521.             return num;
  522.         }
  523.  
  524.         private System.Windows.Media.ImageSource BitmapToImageSource(Bitmap imToConvert)
  525.         {
  526.             Bitmap bmp = new Bitmap(imToConvert);
  527.             MemoryStream ms = new MemoryStream();
  528.             bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
  529.  
  530.             BitmapImage image = new BitmapImage();
  531.             image.BeginInit();
  532.             ms.Seek(0, SeekOrigin.Begin);
  533.             image.StreamSource = ms;
  534.             image.EndInit();
  535.  
  536.             System.Windows.Media.ImageSource sc = image;
  537.  
  538.             return sc;
  539.         }
  540.     }
  541. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement