Advertisement
Shokedbrain

csharp lab 2 symmetric

May 5th, 2021
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.68 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Windows.Forms;
  6.  
  7. namespace csharp_crypto_2
  8. {
  9.     public partial class Form1 : Form
  10.     {
  11.         private static readonly RNGCryptoServiceProvider Rand = new RNGCryptoServiceProvider();
  12.  
  13.         public Form1()
  14.         {
  15.             InitializeComponent();
  16.         }
  17.  
  18.         private static int RandomInteger(int min, int max)
  19.         {
  20.             var scale = uint.MaxValue;
  21.             while (scale == uint.MaxValue)
  22.             {
  23.                 var fourBytes = new byte[4];
  24.                 Rand.GetBytes(fourBytes);
  25.                 scale = BitConverter.ToUInt32(fourBytes, 0);
  26.             }
  27.  
  28.             return (int) (min + (max - min) *
  29.                 (scale / (double) uint.MaxValue));
  30.         }
  31.  
  32.         public static byte[] StringToByteArray(string hex) {
  33.             // эквивалетно
  34.             //byte[] bytes = new byte[s.Length/2];
  35.             //for (int i=0; i<s.Length; i+=2)
  36.             //{
  37.             //    bytes[i/2] = Convert.ToByte(s.Substring(i,2), 16);
  38.             //}
  39.             return Enumerable.Range(0, hex.Length)
  40.                 .Where(x => x % 2 == 0)
  41.                 .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
  42.                 .ToArray();
  43.         }
  44.  
  45.         private static byte[] EncryptAES(string input, byte[] Key, byte[] IV)
  46.         {
  47.             if (input == null || input.Length <= 0)
  48.                 throw new ArgumentNullException("cipherText");
  49.             if (Key == null || Key.Length <= 0)
  50.                 throw new ArgumentNullException("Key");
  51.             if (IV == null || IV.Length <= 0)
  52.                 throw new ArgumentNullException("Key");
  53.             byte[] encrypted;
  54.             using (var aes = Aes.Create())
  55.             {
  56.                 aes.Key = Key;
  57.                 aes.IV = IV;
  58.                 var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); // ICryptoTransform
  59.                 using (var msEncrypt = new MemoryStream())
  60.                 using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  61.                 {
  62.                     using (var swEncrypt = new StreamWriter(csEncrypt))
  63.                     {
  64.                             swEncrypt.Write(input);
  65.                     }
  66.                     encrypted = msEncrypt.ToArray();
  67.                 }
  68.                
  69.             }
  70.  
  71.             return encrypted;
  72.         }
  73.  
  74.         private static string DecryptAES(byte[] cipherText, byte[] Key, byte[] IV)
  75.         {
  76.             if (cipherText == null || cipherText.Length <= 0)
  77.                 throw new ArgumentNullException("cipherText");
  78.             if (Key == null || Key.Length <= 0)
  79.                 throw new ArgumentNullException("Key");
  80.             if (IV == null || IV.Length <= 0)
  81.                 throw new ArgumentNullException("Key");
  82.             var output = string.Empty;
  83.             using (var aes = Aes.Create())
  84.             {
  85.                 aes.Key = Key;
  86.                 aes.IV = IV;
  87.                 var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); // ICryptoTransform
  88.                 using (var msDecrypt = new MemoryStream(cipherText))
  89.                 using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
  90.                 using (var srDecrypt = new StreamReader(csDecrypt))
  91.                     output = srDecrypt.ReadToEnd();
  92.                
  93.             }
  94.  
  95.             return output;
  96.         }
  97.  
  98.         public static string RandomHexString(int length)
  99.         {
  100.             var random = new Random();
  101.             const string valid = "ABCDEF0123456789";
  102.             return new string(Enumerable.Repeat(valid, length)
  103.                 .Select(s => s[RandomInteger(0, s.Length)]).ToArray());
  104.         }
  105.  
  106.         private void actionButton_Click(object sender, EventArgs e)
  107.         {
  108.             // обработка входных данных
  109.             // если нет входных данных (они пусты), создаём рандомную строку
  110.             if (keyBox.Text == "") keyBox.Text = RandomHexString(32);
  111.  
  112.             if (initVectorBox.Text == "") initVectorBox.Text = RandomHexString(32);
  113.  
  114.             var aesKey = StringToByteArray(keyBox.Text);
  115.             var aesIV = StringToByteArray(initVectorBox.Text);
  116.             //UnicodeEncoding UE = new UnicodeEncoding();
  117.             //var aesKey = UE.GetBytes(keyBox.Text);
  118.             //var aesIV = UE.GetBytes(initVectorBox.Text);
  119.             // проверка key на стойкость
  120.             var keyLength = aesKey.Length * 8;
  121.             MessageBox.Show(keyLength.ToString(), "");
  122.             MessageBox.Show(keyLength >= 128 ? "Ключ стойкий" : "Ключ не является стойким");
  123.             // открыть файл для шифрования
  124.             var fileContent = string.Empty;
  125.             var filePath = string.Empty;
  126.             using (var dialog = new OpenFileDialog())
  127.             {
  128.                 dialog.Filter = "TXT files (*.txt)|*.txt|All files (*.*)|*.*";
  129.                 dialog.FilterIndex = 2;
  130.                 dialog.RestoreDirectory = true;
  131.                 if (dialog.ShowDialog() == DialogResult.OK)
  132.                 {
  133.                     var fileStream = dialog.OpenFile();
  134.                     filePath = dialog.FileName;
  135.  
  136.                     var outputFile = string.Empty;
  137.                     using (var saveFileDialog = new SaveFileDialog())
  138.                     {
  139.                         saveFileDialog.Filter = "TXT files (*.txt)|*.txt|All files (*.*)|*.*";
  140.                         saveFileDialog.FileName = "Result";
  141.                         if (saveFileDialog.ShowDialog() == DialogResult.OK) outputFile = saveFileDialog.FileName;
  142.                     }
  143.  
  144.                     if (encryptButton.Checked)
  145.                     {
  146.                         using (var reader = new StreamReader(fileStream))
  147.                         {
  148.                             fileContent = reader.ReadToEnd();
  149.                         }
  150.  
  151.                         File.WriteAllBytes(outputFile, EncryptAES(fileContent, aesKey, aesIV));
  152.                     }
  153.  
  154.                     if (decryptButton.Checked)
  155.                     {
  156.                         var test = File.ReadAllBytes(filePath);
  157.                         // расшифрование
  158.                         File.WriteAllText(outputFile, DecryptAES(test, aesKey, aesIV));
  159.                     }
  160.  
  161.                     MessageBox.Show("Файл сохранён: " + outputFile, "ОК", MessageBoxButtons.OK,
  162.                         MessageBoxIcon.Information);
  163.                 }
  164.                 else
  165.                 {
  166.                     MessageBox.Show("Выберите файл для продолжения работы", "Ошибка", MessageBoxButtons.OK,
  167.                         MessageBoxIcon.Error);
  168.                 }
  169.             }
  170.         }
  171.  
  172.         private void Form1_Load(object sender, EventArgs e)
  173.         {
  174.             keyLengthLabel.Text = "";
  175.             IVLengthLabel.Text = "";
  176.             keyBoxLength.Text = "";
  177.             IVBoxLength.Text = "";
  178.         }
  179.  
  180.         private void keyBox_TextChanged(object sender, EventArgs e)
  181.         {
  182.             // char занимает в памяти 2 байта
  183.             keyLengthLabel.Text = (keyBox.Text.Length*8/2) + " бит";
  184.             keyBoxLength.Text = keyBox.Text.Length.ToString();
  185.         }
  186.  
  187.         private void initVectorBox_TextChanged(object sender, EventArgs e)
  188.         {
  189.             IVLengthLabel.Text = (initVectorBox.Text.Length*8/2) + " бит";
  190.             IVBoxLength.Text = initVectorBox.Text.Length.ToString();
  191.         }
  192.     }
  193. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement