Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- //using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using System.Security.Cryptography;
- using Microsoft.Win32;
- using System.IO;
- using System.Threading;
- using System.Collections;
- using System.Drawing;
- namespace ProjectCryptor
- {
- /// <summary>
- /// Логика взаимодействия для MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- #region Window
- public MainWindow()
- {
- InitializeComponent();
- for (int i = 1; i <= 8; i *= 2)
- KeySize.Items.Add(512 * i);
- KeySize.SelectedIndex = 2;
- }
- private void Window_MouseDown(object sender, MouseButtonEventArgs e)
- {
- if (e.ChangedButton != MouseButton.Right)
- DragMove();
- }
- private void ApplicationClose(object sender, RoutedEventArgs e)
- {
- System.Diagnostics.Process.GetCurrentProcess().Kill();
- }
- private void ApplicationHide(object sender, RoutedEventArgs e)
- {
- WindowState = WindowState.Minimized;
- }
- #endregion
- //----------------------------RSA----------------------------
- #region RSA
- private string PublicKey { get; set; }
- private string PrivateKey { get; set; }
- private bool IsKeyGenerated;
- private RSACryptoServiceProvider rsaCryptoServiceProvider;
- private void CreateKeys(object sender, RoutedEventArgs e)
- {
- Thread t = new Thread(delegate ()
- {
- Dispatcher.Invoke(() =>
- {
- CreateKeysButton.Visibility = Visibility.Hidden;
- CreateKeysSpinner.Visibility = Visibility.Visible;
- CreateKeysLabel.Visibility = Visibility.Visible;
- rsaCryptoServiceProvider = new RSACryptoServiceProvider((int)KeySize.SelectedItem);
- });
- PublicKey = rsaCryptoServiceProvider.ToXmlString(false);
- PrivateKey = rsaCryptoServiceProvider.ToXmlString(true);
- Dispatcher.Invoke(() =>
- {
- PrivateKeyTextBox.Text = PrivateKey;
- PublicKeyTextBox.Text = PublicKey;
- IsKeyGenerated = true;
- CreateKeysButton.Visibility = Visibility.Visible;
- CreateKeysSpinner.Visibility = Visibility.Hidden;
- CreateKeysLabel.Visibility = Visibility.Hidden;
- });
- });
- t.SetApartmentState(ApartmentState.STA);
- t.Start();
- }
- private void Encrypt(object sender, RoutedEventArgs e)
- {
- if (!IsKeyGenerated)
- return;
- byte[] plainText = Encoding.Unicode.GetBytes(DecryptTextBox.Text);
- try
- {
- byte[] encrypted = rsaCryptoServiceProvider.Encrypt(plainText, false);
- EncryptTextBox.Text = Convert.ToBase64String(encrypted);
- }
- catch (Exception)
- {
- MessageBox.Show("Ошибка. Слишком большой текст для данного ключа");
- }
- }
- private void Decrypt(object sender, RoutedEventArgs e)
- {
- if (string.IsNullOrEmpty(EncryptTextBox.Text))
- return;
- byte[] x = (Convert.FromBase64String(EncryptTextBox.Text));
- byte[] decrypted = rsaCryptoServiceProvider.Decrypt(x, false);
- DecryptTextBox.Text = Encoding.Unicode.GetString(Convert.FromBase64String(Convert.ToBase64String(decrypted)));
- }
- private void LoadPublicKey_Click(object sender, RoutedEventArgs e)
- {
- PublicKeyTextBox.Text = OpenTxtFile();
- }
- private void SavePublicKey_Click(object sender, RoutedEventArgs e)
- {
- SaveTxtFile(PublicKeyTextBox.Text);
- }
- private void LoadPrivateKey_Click(object sender, RoutedEventArgs e)
- {
- PrivateKeyTextBox.Text = OpenTxtFile();
- }
- private void SavePrivateKey_Click(object sender, RoutedEventArgs e)
- {
- SaveTxtFile(PrivateKeyTextBox.Text);
- }
- private void LoadEncryptText_Click(object sender, RoutedEventArgs e)
- {
- EncryptTextBox.Text = OpenTxtFile();
- }
- private void SaveEncryptText_Click(object sender, RoutedEventArgs e)
- {
- SaveTxtFile(EncryptTextBox.Text);
- }
- private void LoadDecryptText_Click(object sender, RoutedEventArgs e)
- {
- DecryptTextBox.Text = OpenTxtFile();
- }
- private void SaveDecryptText_Click(object sender, RoutedEventArgs e)
- {
- SaveTxtFile(DecryptTextBox.Text);
- }
- private string OpenTxtFile()
- {
- OpenFileDialog LoadTextDialog = new OpenFileDialog
- {
- Filter = "Текстовые файлы(*.txt)|*.txt",
- CheckFileExists = true
- };
- if (LoadTextDialog.ShowDialog() == true)
- {
- return File.ReadAllText(LoadTextDialog.FileName, Encoding.UTF8);
- }
- return "";
- }
- private void SaveTxtFile(string text)
- {
- SaveFileDialog SaveTxtDialog = new SaveFileDialog
- {
- Filter = "Текстовые файлы(*.txt)|*.txt"
- };
- if (SaveTxtDialog.ShowDialog() == true)
- {
- using (StreamWriter sw = new StreamWriter(SaveTxtDialog.OpenFile(), System.Text.Encoding.UTF8))
- {
- sw.Write(text);
- sw.Close();
- }
- }
- }
- #endregion
- //----------------------------LSB----------------------------
- OpenFileDialog LoadImageDialog = new OpenFileDialog
- {
- Filter = "Изображение(*.bmp)|*.bmp",
- CheckFileExists = true
- };
- SaveFileDialog SaveImageDialog = new SaveFileDialog
- {
- Filter = "Изображение(*.bmp)|*.bmp"
- };
- string SourceImagePath, EncryptedImagePath;
- Bitmap SourceImageBitmap, EncryptedImageBitmap;
- private void LoadSourceText_Click(object sender, RoutedEventArgs e)
- {
- SourceText.Text = OpenTxtFile();
- }
- private void LoadSourceImage_Click(object sender, RoutedEventArgs e)
- {
- if (LoadImageDialog.ShowDialog() == true)
- {
- SourceImagePath = LoadImageDialog.FileName;
- SourceImageBitmap = new Bitmap(SourceImagePath);
- SourceImage.Source = BitmapToImageSource(SourceImageBitmap);
- }
- }
- private void LoadEncryptedImage_Click(object sender, RoutedEventArgs e)
- {
- if (LoadImageDialog.ShowDialog() == true)
- {
- EncryptedImagePath = LoadImageDialog.FileName;
- EncryptedImageBitmap = new Bitmap(EncryptedImagePath);
- EncryptedImage.Source = BitmapToImageSource(EncryptedImageBitmap);
- }
- }
- private void SaveSourceText_Click(object sender, RoutedEventArgs e)
- {
- SaveTxtFile(Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(DecryptSourceText.Text)));
- }
- private void SaveEncryptImage_Click(object sender, RoutedEventArgs e)
- {
- if (SaveImageDialog.ShowDialog() == true)
- {
- string sFilePic = SaveImageDialog.FileName;
- if (sFilePic == "")
- return;
- FileStream wFile;
- try
- {
- wFile = new FileStream(sFilePic, FileMode.Create); //открываем поток на запись результатов
- }
- catch (IOException)
- {
- MessageBox.Show("Ошибка открытия файла на запись", "Ошибка");
- return;
- }
- EncryptedImageBitmap.Save(wFile, System.Drawing.Imaging.ImageFormat.Bmp);
- wFile.Close(); //закрываем поток
- }
- }
- //------------------------------------------------------------
- private void EncryptImageButton_Click(object sender, RoutedEventArgs e)
- {
- if (SourceImage.Source == null || SourceText.Text == "")
- return;
- if (SourceText.Text.Count() > 16777215)
- {
- MessageBox.Show("Слишком большой текст", "Ошибка");
- return;
- }
- Bitmap bPic = new Bitmap(SourceImagePath);
- BinaryReader bText = new BinaryReader(
- new MemoryStream(Encoding.UTF8.GetBytes(SourceText.Text ?? "")), Encoding.ASCII);
- List<byte> bList = new List<byte>();
- while (bText.PeekChar() != -1) //считали весь текстовый файл для шифрования в лист байтs
- {
- bList.Add(bText.ReadByte());
- }
- int CountText = bList.Count; // в CountText - количество в байтах текста, который нужно закодировать
- bText.Close();
- //проверяем, поместиться ли исходный текст в картинке
- if (CountText > ((bPic.Width * bPic.Height)) - 4)
- {
- MessageBox.Show("Выбранная картинка мала для размещения выбранного текста", "Информация");
- return;
- }
- //проверяем, может быть картинка уже зашифрована
- if (IsEncryption(bPic))
- {
- MessageBox.Show("Файл уже зашифрован", "Информация");
- return;
- }
- byte[] Symbol = Encoding.GetEncoding(1251).GetBytes("/");
- BitArray ArrBeginSymbol = ByteToBit(Symbol[0]);
- Color curColor = bPic.GetPixel(0, 0);
- BitArray tempArray = ByteToBit(curColor.R);
- tempArray[0] = ArrBeginSymbol[0];
- tempArray[1] = ArrBeginSymbol[1];
- byte nR = BitToByte(tempArray);
- tempArray = ByteToBit(curColor.G);
- tempArray[0] = ArrBeginSymbol[2];
- tempArray[1] = ArrBeginSymbol[3];
- tempArray[2] = ArrBeginSymbol[4];
- byte nG = BitToByte(tempArray);
- tempArray = ByteToBit(curColor.B);
- tempArray[0] = ArrBeginSymbol[5];
- tempArray[1] = ArrBeginSymbol[6];
- tempArray[2] = ArrBeginSymbol[7];
- byte nB = BitToByte(tempArray);
- Color nColor = Color.FromArgb(nR, nG, nB);
- bPic.SetPixel(0, 0, nColor);
- //то есть в первом пикселе будет символ /, который говорит о том, что картика зашифрована
- try
- {
- WriteCountText(CountText, bPic); //записываем количество символов для шифрования
- }
- catch (Exception)
- {
- MessageBox.Show("FFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU");
- return;
- }
- int index = 0;
- bool st = false;
- for (int i = 4; i < bPic.Width; i++)
- {
- for (int j = 0; j < bPic.Height; j++)
- {
- Color pixelColor = bPic.GetPixel(i, j);
- if (index == bList.Count)
- {
- st = true;
- break;
- }
- BitArray colorArray = ByteToBit(pixelColor.R);
- BitArray messageArray = ByteToBit(bList[index]);
- colorArray[0] = messageArray[0]; //меняем
- colorArray[1] = messageArray[1]; // в нашем цвете биты
- byte newR = BitToByte(colorArray);
- colorArray = ByteToBit(pixelColor.G);
- colorArray[0] = messageArray[2];
- colorArray[1] = messageArray[3];
- colorArray[2] = messageArray[4];
- byte newG = BitToByte(colorArray);
- colorArray = ByteToBit(pixelColor.B);
- colorArray[0] = messageArray[5];
- colorArray[1] = messageArray[6];
- colorArray[2] = messageArray[7];
- byte newB = BitToByte(colorArray);
- Color newColor = Color.FromArgb(newR, newG, newB);
- bPic.SetPixel(i, j, newColor);
- index++;
- }
- if (st)
- {
- break;
- }
- }
- EncryptedImageBitmap = bPic;
- EncryptedImage.Source = BitmapToImageSource(EncryptedImageBitmap);
- }
- private void DecryptImageButton_Click(object sender, RoutedEventArgs e)
- {
- if (EncryptedImage.Source == null)
- return;
- Bitmap bPic = EncryptedImageBitmap;
- if (!IsEncryption(bPic))
- {
- MessageBox.Show("В файле нет зашифрованной информации", "Информация");
- return;
- }
- int countSymbol = ReadCountText(bPic); //считали количество зашифрованных символов
- byte[] message = new byte[countSymbol];
- int index = 0;
- bool st = false;
- for (int i = 4; i < bPic.Width; i++)
- {
- for (int j = 0; j < bPic.Height; j++)
- {
- Color pixelColor = bPic.GetPixel(i, j);
- if (index == message.Length)
- {
- st = true;
- break;
- }
- BitArray colorArray = ByteToBit(pixelColor.R);
- BitArray messageArray = ByteToBit(pixelColor.R); ;
- messageArray[0] = colorArray[0];
- messageArray[1] = colorArray[1];
- colorArray = ByteToBit(pixelColor.G);
- messageArray[2] = colorArray[0];
- messageArray[3] = colorArray[1];
- messageArray[4] = colorArray[2];
- colorArray = ByteToBit(pixelColor.B);
- messageArray[5] = colorArray[0];
- messageArray[6] = colorArray[1];
- messageArray[7] = colorArray[2];
- message[index] = BitToByte(messageArray);
- index++;
- }
- if (st)
- {
- break;
- }
- }
- DecryptSourceText.Text = Encoding.GetEncoding(65001/*<-UTF-8*//*1251*/).GetString(message);
- }
- //---------------------------------------------
- /*Проверяет, зашифрован ли файл, возвраещает true, если символ в первом пикслеле равен / иначе false */
- private bool IsEncryption(Bitmap scr)
- {
- byte[] rez = new byte[1];
- Color color = scr.GetPixel(0, 0);
- BitArray colorArray = ByteToBit(color.R); //получаем байт цвета и преобразуем в массив бит
- BitArray messageArray = ByteToBit(color.R); ;//инициализируем результирующий массив бит
- messageArray[0] = colorArray[0];
- messageArray[1] = colorArray[1];
- colorArray = ByteToBit(color.G);//получаем байт цвета и преобразуем в массив бит
- messageArray[2] = colorArray[0];
- messageArray[3] = colorArray[1];
- messageArray[4] = colorArray[2];
- colorArray = ByteToBit(color.B);//получаем байт цвета и преобразуем в массив бит
- messageArray[5] = colorArray[0];
- messageArray[6] = colorArray[1];
- messageArray[7] = colorArray[2];
- rez[0] = BitToByte(messageArray); //получаем байт символа, записанного в 1 пикселе
- return Encoding.GetEncoding(1251).GetString(rez) == "/";
- }
- /*Записыает количество символов для шифрования в первые биты картинки */
- private void WriteCountText(int count, Bitmap src)
- {
- string bits = "";
- for (int i = 23; i >= 0; i--)
- {
- bits += (count >> i) & 0x01;
- }
- for (int i = 0; i < 3; i++)
- {
- Color pColor = src.GetPixel(0, i + 1); //1, 2, 3 пикселы
- BitArray bitsCurColor = ByteToBit(pColor.R); //бит цветов текущего пикселя
- bitsCurColor[0] = bits[0 + i * 8] == '1';
- bitsCurColor[1] = bits[1 + i * 8] == '1';
- byte nR = BitToByte(bitsCurColor); //новый бит цвета пиксея
- bitsCurColor = ByteToBit(pColor.G);//бит бит цветов текущего пикселя
- bitsCurColor[0] = bits[2 + i * 8] == '1';
- bitsCurColor[1] = bits[3 + i * 8] == '1';
- bitsCurColor[2] = bits[4 + i * 8] == '1';
- byte nG = BitToByte(bitsCurColor);//новый цвет пиксея
- bitsCurColor = ByteToBit(pColor.B);//бит бит цветов текущего пикселя
- bitsCurColor[0] = bits[5 + i * 8] == '1';
- bitsCurColor[1] = bits[6 + i * 8] == '1';
- bitsCurColor[2] = bits[7 + i * 8] == '1';
- byte nB = BitToByte(bitsCurColor);//новый цвет пиксея
- Color nColor = Color.FromArgb(nR, nG, nB); //новый цвет из полученных битов
- src.SetPixel(0, i + 1, nColor); //записали полученный цвет в картинку
- }
- }
- /*Читает количество символов для дешифрования из первых бит картинки*/
- private int ReadCountText(Bitmap src)
- {
- string count = "";
- for (int i = 0; i < 3; i++)
- {
- Color color = src.GetPixel(0, i + 1); //цвет 1, 2, 3 пикселей
- BitArray colorArray = ByteToBit(color.R); //биты цвета
- count += colorArray[0] ? "1" : "0";
- count += colorArray[1] ? "1" : "0";
- colorArray = ByteToBit(color.G);
- count += colorArray[0] ? "1" : "0";
- count += colorArray[1] ? "1" : "0";
- count += colorArray[2] ? "1" : "0";
- colorArray = ByteToBit(color.B);
- count += colorArray[0] ? "1" : "0";
- count += colorArray[1] ? "1" : "0";
- count += colorArray[2] ? "1" : "0";
- }
- return Convert.ToInt32(count, 2);
- }
- private BitArray ByteToBit(byte src)
- {
- BitArray bitArray = new BitArray(8);
- bool st = false;
- for (int i = 0; i < 8; i++)
- {
- if ((src >> i & 1) == 1)
- {
- st = true;
- }
- else st = false;
- bitArray[i] = st;
- }
- return bitArray;
- }
- private byte BitToByte(BitArray scr)
- {
- byte num = 0;
- for (int i = 0; i < scr.Count; i++)
- if (scr[i] == true)
- num += (byte)Math.Pow(2, i);
- return num;
- }
- private System.Windows.Media.ImageSource BitmapToImageSource(Bitmap imToConvert)
- {
- Bitmap bmp = new Bitmap(imToConvert);
- MemoryStream ms = new MemoryStream();
- bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
- BitmapImage image = new BitmapImage();
- image.BeginInit();
- ms.Seek(0, SeekOrigin.Begin);
- image.StreamSource = ms;
- image.EndInit();
- System.Windows.Media.ImageSource sc = image;
- return sc;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement