Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Windows.Forms;
- namespace csharp_crypto_2
- {
- public partial class Form1 : Form
- {
- private static readonly RNGCryptoServiceProvider Rand = new RNGCryptoServiceProvider();
- public Form1()
- {
- InitializeComponent();
- }
- private static int RandomInteger(int min, int max)
- {
- var scale = uint.MaxValue;
- while (scale == uint.MaxValue)
- {
- var fourBytes = new byte[4];
- Rand.GetBytes(fourBytes);
- scale = BitConverter.ToUInt32(fourBytes, 0);
- }
- return (int) (min + (max - min) *
- (scale / (double) uint.MaxValue));
- }
- public static byte[] StringToByteArray(string hex) {
- // эквивалетно
- //byte[] bytes = new byte[s.Length/2];
- //for (int i=0; i<s.Length; i+=2)
- //{
- // bytes[i/2] = Convert.ToByte(s.Substring(i,2), 16);
- //}
- return Enumerable.Range(0, hex.Length)
- .Where(x => x % 2 == 0)
- .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
- .ToArray();
- }
- private static byte[] EncryptAES(string input, byte[] Key, byte[] IV)
- {
- if (input == null || input.Length <= 0)
- throw new ArgumentNullException("cipherText");
- if (Key == null || Key.Length <= 0)
- throw new ArgumentNullException("Key");
- if (IV == null || IV.Length <= 0)
- throw new ArgumentNullException("Key");
- byte[] encrypted;
- using (var aes = Aes.Create())
- {
- aes.Key = Key;
- aes.IV = IV;
- var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); // ICryptoTransform
- using (var msEncrypt = new MemoryStream())
- using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
- {
- using (var swEncrypt = new StreamWriter(csEncrypt))
- {
- swEncrypt.Write(input);
- }
- encrypted = msEncrypt.ToArray();
- }
- }
- return encrypted;
- }
- private static string DecryptAES(byte[] cipherText, byte[] Key, byte[] IV)
- {
- if (cipherText == null || cipherText.Length <= 0)
- throw new ArgumentNullException("cipherText");
- if (Key == null || Key.Length <= 0)
- throw new ArgumentNullException("Key");
- if (IV == null || IV.Length <= 0)
- throw new ArgumentNullException("Key");
- var output = string.Empty;
- using (var aes = Aes.Create())
- {
- aes.Key = Key;
- aes.IV = IV;
- var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); // ICryptoTransform
- using (var msDecrypt = new MemoryStream(cipherText))
- using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
- using (var srDecrypt = new StreamReader(csDecrypt))
- output = srDecrypt.ReadToEnd();
- }
- return output;
- }
- public static string RandomHexString(int length)
- {
- var random = new Random();
- const string valid = "ABCDEF0123456789";
- return new string(Enumerable.Repeat(valid, length)
- .Select(s => s[RandomInteger(0, s.Length)]).ToArray());
- }
- private void actionButton_Click(object sender, EventArgs e)
- {
- // обработка входных данных
- // если нет входных данных (они пусты), создаём рандомную строку
- if (keyBox.Text == "") keyBox.Text = RandomHexString(32);
- if (initVectorBox.Text == "") initVectorBox.Text = RandomHexString(32);
- var aesKey = StringToByteArray(keyBox.Text);
- var aesIV = StringToByteArray(initVectorBox.Text);
- //UnicodeEncoding UE = new UnicodeEncoding();
- //var aesKey = UE.GetBytes(keyBox.Text);
- //var aesIV = UE.GetBytes(initVectorBox.Text);
- // проверка key на стойкость
- var keyLength = aesKey.Length * 8;
- MessageBox.Show(keyLength.ToString(), "");
- MessageBox.Show(keyLength >= 128 ? "Ключ стойкий" : "Ключ не является стойким");
- // открыть файл для шифрования
- var fileContent = string.Empty;
- var filePath = string.Empty;
- using (var dialog = new OpenFileDialog())
- {
- dialog.Filter = "TXT files (*.txt)|*.txt|All files (*.*)|*.*";
- dialog.FilterIndex = 2;
- dialog.RestoreDirectory = true;
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- var fileStream = dialog.OpenFile();
- filePath = dialog.FileName;
- var outputFile = string.Empty;
- using (var saveFileDialog = new SaveFileDialog())
- {
- saveFileDialog.Filter = "TXT files (*.txt)|*.txt|All files (*.*)|*.*";
- saveFileDialog.FileName = "Result";
- if (saveFileDialog.ShowDialog() == DialogResult.OK) outputFile = saveFileDialog.FileName;
- }
- if (encryptButton.Checked)
- {
- using (var reader = new StreamReader(fileStream))
- {
- fileContent = reader.ReadToEnd();
- }
- File.WriteAllBytes(outputFile, EncryptAES(fileContent, aesKey, aesIV));
- }
- if (decryptButton.Checked)
- {
- var test = File.ReadAllBytes(filePath);
- // расшифрование
- File.WriteAllText(outputFile, DecryptAES(test, aesKey, aesIV));
- }
- MessageBox.Show("Файл сохранён: " + outputFile, "ОК", MessageBoxButtons.OK,
- MessageBoxIcon.Information);
- }
- else
- {
- MessageBox.Show("Выберите файл для продолжения работы", "Ошибка", MessageBoxButtons.OK,
- MessageBoxIcon.Error);
- }
- }
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- keyLengthLabel.Text = "";
- IVLengthLabel.Text = "";
- keyBoxLength.Text = "";
- IVBoxLength.Text = "";
- }
- private void keyBox_TextChanged(object sender, EventArgs e)
- {
- // char занимает в памяти 2 байта
- keyLengthLabel.Text = (keyBox.Text.Length*8/2) + " бит";
- keyBoxLength.Text = keyBox.Text.Length.ToString();
- }
- private void initVectorBox_TextChanged(object sender, EventArgs e)
- {
- IVLengthLabel.Text = (initVectorBox.Text.Length*8/2) + " бит";
- IVBoxLength.Text = initVectorBox.Text.Length.ToString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement