Опубликован: 05.08.2010 | Доступ: свободный | Студентов: 2007 / 44 | Оценка: 4.50 / 4.40 | Длительность: 60:26:00
Лекция 6:

Работа с потоками данных

< Лекция 5 || Лекция 6: 12345678910111213

Пример 2. Поток CryptoStream и шифрование в файл

В данном примере мы разработаем диалоговое приложение Windows Forms, иллюстрирующее работу алгоритмов шифрования/дешифрования в файл. Вернее, приложение уже разработано и ниже приводятся его составляющие, с которыми нужно разобраться самостоятельно. Но прежде нужно собрать приложение полностью и только потом испытывать, иначе посыпятся ошибки! Итак, собираем...

  • Добавьте к решению CryptoStream новый проект с именем Demo2 и назначьте его стартовым

  • В панели Solution Explorer откройте интерфейсный файл Form1.Designer.cs и заполните его следующим кодом (приводится полностью)
namespace Demo2
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;
    
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    
        #region Windows Form Designer generated code
    
        private void InitializeComponent()
        {
            this.cmbCodec = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txtSourceFile = new System.Windows.Forms.TextBox();
            this.btnSelectFile = new System.Windows.Forms.Button();
            this.txtDestinationDir = new System.Windows.Forms.TextBox();
            this.btnDestinationDir = new System.Windows.Forms.Button();
            this.label4 = new System.Windows.Forms.Label();
            this.txtKey = new System.Windows.Forms.TextBox();
            this.btnClose = new System.Windows.Forms.Button();
            this.numKeySize = new System.Windows.Forms.NumericUpDown();
            this.numBlockSize = new System.Windows.Forms.NumericUpDown();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.btnEncrypt = new System.Windows.Forms.Button();
            this.btnDecrypt = new System.Windows.Forms.Button();
            this.btnShowFile = new System.Windows.Forms.Button();
            this.btnNewFile = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.numKeySize)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.numBlockSize)).BeginInit();
            this.SuspendLayout();
            // 
            // cmbCodec
            // 
            this.cmbCodec.FormattingEnabled = true;
            this.cmbCodec.Location = new System.Drawing.Point(94, 21);
            this.cmbCodec.Name = "cmbCodec";
            this.cmbCodec.Size = new System.Drawing.Size(280, 24);
            this.cmbCodec.TabIndex = 0;
            this.cmbCodec.SelectedIndexChanged += new System.EventHandler(this.cmbCodec_SelectedIndexChanged);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(17, 24);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(71, 17);
            this.label1.TabIndex = 1;
            this.label1.Text = "Algorithm:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(5, 156);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(83, 17);
            this.label2.TabIndex = 2;
            this.label2.Text = "Source File:";
            // 
            // txtSourceFile
            // 
            this.txtSourceFile.Location = new System.Drawing.Point(94, 155);
            this.txtSourceFile.Name = "txtSourceFile";
            this.txtSourceFile.Size = new System.Drawing.Size(280, 22);
            this.txtSourceFile.TabIndex = 3;
            this.txtSourceFile.KeyDown += new System.Windows.Forms.KeyEventHandler(this.EditKeyDown);
            this.txtSourceFile.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.EditKeyPress);
            // 
            // btnSelectFile
            // 
            this.btnSelectFile.Font = new System.Drawing.Font("Agency FB", 7.2F, System.Drawing.FontStyle.Bold, 
            	System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnSelectFile.Location = new System.Drawing.Point(380, 155);
            this.btnSelectFile.Name = "btnSelectFile";
            this.btnSelectFile.Size = new System.Drawing.Size(25, 23);
            this.btnSelectFile.TabIndex = 4;
            this.btnSelectFile.Text = "...";
            this.btnSelectFile.UseVisualStyleBackColor = true;
            this.btnSelectFile.Click += new System.EventHandler(this.btnSelectFile_Click);
            // 
            // txtDestinationDir
            // 
            this.txtDestinationDir.Location = new System.Drawing.Point(94, 198);
            this.txtDestinationDir.Name = "txtDestinationDir";
            this.txtDestinationDir.Size = new System.Drawing.Size(280, 22);
            this.txtDestinationDir.TabIndex = 6;
            // 
            // btnDestinationDir
            // 
            this.btnDestinationDir.Font = new System.Drawing.Font("Agency FB", 7.2F, System.Drawing.FontStyle.Bold, 
            	System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnDestinationDir.Location = new System.Drawing.Point(380, 198);
            this.btnDestinationDir.Name = "btnDestinationDir";
            this.btnDestinationDir.Size = new System.Drawing.Size(25, 23);
            this.btnDestinationDir.TabIndex = 7;
            this.btnDestinationDir.Text = "...";
            this.btnDestinationDir.UseVisualStyleBackColor = true;
            this.btnDestinationDir.Click += new System.EventHandler(this.btnDestinationDir_Click);
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(52, 67);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(36, 17);
            this.label4.TabIndex = 8;
            this.label4.Text = "Key:";
            // 
            // txtKey
            // 
            this.txtKey.Location = new System.Drawing.Point(94, 66);
            this.txtKey.Name = "txtKey";
            this.txtKey.Size = new System.Drawing.Size(280, 22);
            this.txtKey.TabIndex = 9;
            // 
            // btnClose
            // 
            this.btnClose.AutoSize = true;
            this.btnClose.Location = new System.Drawing.Point(353, 256);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(75, 27);
            this.btnClose.TabIndex = 12;
            this.btnClose.Text = "Close";
            this.btnClose.UseVisualStyleBackColor = true;
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            // 
            // numKeySize
            // 
            this.numKeySize.Location = new System.Drawing.Point(111, 110);
            this.numKeySize.Name = "numKeySize";
            this.numKeySize.Size = new System.Drawing.Size(55, 22);
            this.numKeySize.TabIndex = 13;
            this.numKeySize.ValueChanged += new System.EventHandler(this.Numeric_ValueChanged);
            this.numKeySize.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.EditKeyPress);
            this.numKeySize.KeyDown += new System.Windows.Forms.KeyEventHandler(this.EditKeyDown);
            // 
            // numBlockSize
            // 
            this.numBlockSize.Location = new System.Drawing.Point(299, 110);
            this.numBlockSize.Name = "numBlockSize";
            this.numBlockSize.Size = new System.Drawing.Size(55, 22);
            this.numBlockSize.TabIndex = 14;
            this.numBlockSize.ValueChanged += new System.EventHandler(this.Numeric_ValueChanged);
            this.numBlockSize.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.EditKeyPress);
            this.numBlockSize.KeyDown += new System.Windows.Forms.KeyEventHandler(this.EditKeyDown);
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(38, 111);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(67, 17);
            this.label5.TabIndex = 15;
            this.label5.Text = "Key Size:";
            // 
            // label6
            // 
            this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(216, 111);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(77, 17);
            this.label6.TabIndex = 16;
            this.label6.Text = "Block Size:";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(8, 186);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(79, 34);
            this.label3.TabIndex = 5;
            this.label3.Text = "Destination\r\ndirectory:";
            this.label3.TextAlign = System.Drawing.ContentAlignment.TopRight;
            // 
            // btnEncrypt
            // 
            this.btnEncrypt.AutoSize = true;
            this.btnEncrypt.Location = new System.Drawing.Point(98, 256);
            this.btnEncrypt.Name = "btnEncrypt";
            this.btnEncrypt.Size = new System.Drawing.Size(75, 27);
            this.btnEncrypt.TabIndex = 19;
            this.btnEncrypt.Text = "Encrypt";
            this.btnEncrypt.UseVisualStyleBackColor = true;
            this.btnEncrypt.Click += new System.EventHandler(this.btnEncrypt_Click);
            // 
            // btnDecrypt
            // 
            this.btnDecrypt.AutoSize = true;
            this.btnDecrypt.Location = new System.Drawing.Point(182, 256);
            this.btnDecrypt.Name = "btnDecrypt";
            this.btnDecrypt.Size = new System.Drawing.Size(75, 27);
            this.btnDecrypt.TabIndex = 20;
            this.btnDecrypt.Text = "Decrypt";
            this.btnDecrypt.UseVisualStyleBackColor = true;
            this.btnDecrypt.Click += new System.EventHandler(this.btnDecrypt_Click);
            // 
            // btnShowFile
            // 
            this.btnShowFile.AutoSize = true;
            this.btnShowFile.Location = new System.Drawing.Point(266, 256);
            this.btnShowFile.Name = "btnShowFile";
            this.btnShowFile.Size = new System.Drawing.Size(78, 27);
            this.btnShowFile.TabIndex = 21;
            this.btnShowFile.Text = "Show File";
            this.btnShowFile.UseVisualStyleBackColor = true;
            this.btnShowFile.Click += new System.EventHandler(this.btnShowFile_Click);
            // 
            // btnNewFile
            // 
            this.btnNewFile.AutoSize = true;
            this.btnNewFile.Location = new System.Drawing.Point(14, 256);
            this.btnNewFile.Name = "btnNewFile";
            this.btnNewFile.Size = new System.Drawing.Size(75, 27);
            this.btnNewFile.TabIndex = 22;
            this.btnNewFile.Text = "New File";
            this.btnNewFile.UseVisualStyleBackColor = true;
            this.btnNewFile.Click += new System.EventHandler(this.btnNewFile_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(442, 296);
            this.Controls.Add(this.btnNewFile);
            this.Controls.Add(this.btnShowFile);
            this.Controls.Add(this.btnDecrypt);
            this.Controls.Add(this.btnEncrypt);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.numBlockSize);
            this.Controls.Add(this.numKeySize);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.txtKey);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.btnDestinationDir);
            this.Controls.Add(this.txtDestinationDir);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.btnSelectFile);
            this.Controls.Add(this.txtSourceFile);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.cmbCodec);
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.Text = "SymmetricAlgorithm with Files";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            ((System.ComponentModel.ISupportInitialize)(this.numKeySize)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.numBlockSize)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
        }
    
        #endregion
    
        private System.Windows.Forms.ComboBox cmbCodec;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtSourceFile;
        private System.Windows.Forms.Button btnSelectFile;
        private System.Windows.Forms.TextBox txtDestinationDir;
        private System.Windows.Forms.Button btnDestinationDir;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox txtKey;
        private System.Windows.Forms.Button btnClose;
        private System.Windows.Forms.NumericUpDown numKeySize;
        private System.Windows.Forms.NumericUpDown numBlockSize;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button btnEncrypt;
        private System.Windows.Forms.Button btnDecrypt;
        private System.Windows.Forms.Button btnShowFile;
        private System.Windows.Forms.Button btnNewFile;
    }
}

Этот код сразу определит интерфейс формы и мне не нужно будет писать (а вам - читать) таблицу свойств элементов.

  • Добавьте к текущему проекту командой Project/Add Class новый файл с именем MySettings.cs и заполните его следующим кодом (приводится полностью)
using System;
using System.Configuration;
    
namespace Demo2
{
    // Класс для сохранения параметров приложения
    class MySettings : ApplicationSettingsBase
    {
        [UserScopedSettingAttribute()]       // Область действия - 'Пользователь' 
        [DefaultSettingValueAttribute("C:\\")]   // Значение параметра по умолчанию
        public String DestinationDir
        {
            get
            {
                return ((String)this["DestinationDir"]);
            }
            set
            {
                this["DestinationDir"] = (String)value;
            }
        }
    
        [UserScopedSettingAttribute()]       // Область действия - 'Пользователь' 
        [DefaultSettingValueAttribute("")]   // Значение параметра по умолчанию
        public String SourceFile
        {
            get
            {
                return ((String)this["SourceFile"]);
            }
            set
            {
                this["SourceFile"] = (String)value;
            }
        }
    }
}
  • Откройте файл Form1.cs в режиме View Code и заполните его следующим кодом (приводится полностью)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
    
// Дополнительные пространства имен
using System.Security.Cryptography;
using System.IO;
    
namespace Demo2
{
    public partial class Form1 : Form
    {
        // Создаем объект симметричного шифрования
        SymmetricAlgorithm codec = null;// Тип общего предка 
        // Создаем объект сохранения параметров
        MySettings settings = new MySettings();// Это наш класс в файле MySettings.cs
    
        public Form1()
        {
            InitializeComponent();
    
            // Привязка именованных параметров к 
            // сохраняемым свойствам элементов управления
            txtDestinationDir.DataBindings.Add(new Binding("Text", settings, "DestinationDir"));
            txtSourceFile.DataBindings.Add(new Binding("Text", settings, "SourceFile"));
    
            // Настраиваем ComboBox динамически
            cmbCodec.Items.AddRange(
                new string[]
                {
                    "DESCryptoServiceProvider",
                    "RC2CryptoServiceProvider",
                    "RijndaelManaged",
                    "TripleDESCryptoServiceProvider",
                    "DefaultServiceProvider "
                });
    
            cmbCodec.SelectedIndex = 0;// Выделяем первый элемент
        }
    
        // Меняем алгоритм шифрования
        private void cmbCodec_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Блокируем обработчик Numeric_ValueChanged
            initFlag = false;
    
            ComboBox cmb = sender as ComboBox;
            switch (cmb.SelectedIndex)
            {
                case 0:
                    codec = new DESCryptoServiceProvider();
                    break;
                case 1:
                    codec = new RC2CryptoServiceProvider();
                    break;
                case 2:
                    codec = new RijndaelManaged();
                    break;
                case 3:
                    codec = new TripleDESCryptoServiceProvider();
                    break;
                case 4:
                    codec = SymmetricAlgorithm.Create();
                    break;
            }
    
            // Заполняем NumericUpDown
            foreach (KeySizes sizes in codec.LegalKeySizes)
            {
                numKeySize.Minimum = sizes.MinSize;
                numKeySize.Maximum = sizes.MaxSize;
                numKeySize.Increment = sizes.SkipSize;
                break;
            }
            numKeySize.Value = codec.KeySize;
            CorrectTextKey();
            foreach (KeySizes sizes in codec.LegalBlockSizes)
            {
                numBlockSize.Minimum = sizes.MinSize;
                numBlockSize.Maximum = sizes.MaxSize;
                numBlockSize.Increment = sizes.SkipSize;
                break;
            }
            numBlockSize.Value = codec.BlockSize;
    
            // Разблокируем обработчик Numeric_ValueChanged
            initFlag = true;
        }
    
        // Устанавливаем допустимую длину ввода
        void CorrectTextKey()
        {
            // Корректируем длину поля ввода ключа
            int lenKey = codec.KeySize / 8;
            int lenTextBox= ASCIIEncoding.ASCII.GetByteCount(txtKey.Text);
            if (lenTextBox > lenKey)// Убираем лишнее
                txtKey.Text = txtKey.Text.Substring(0, lenKey);
            txtKey.MaxLength = lenKey;
        }
    
        bool initFlag = false;
        private void Numeric_ValueChanged(object sender, EventArgs e)
        {
            if (initFlag)
            {
                codec.KeySize = (int)numKeySize.Value;
                codec.BlockSize = (int)numBlockSize.Value;
                CorrectTextKey();
            }
        }
    
        // Создать новый текстовый файл через блокнот
        private void btnNewFile_Click(object sender, EventArgs e)
        {
            // Создаем новый текстовый файл через блокнот
            System.Diagnostics.Process exe = new System.Diagnostics.Process();
            exe.StartInfo.FileName = "Notepad.exe"; //Имя программы для запуска
            //exe.StartInfo.Arguments = path;         //Аргументы
            exe.Start();        // Запускаем внешний процесс
            //exe.WaitForExit();// Останавливаем наш процесс до закрытия блокнота
            exe.Close();        // Освобождаем связанные с процессом ресурсы
        }
    
        // Посмотреть через блокнот результаты шифрования
        private void btnShowFile_Click(object sender, EventArgs e)
        {
            // Покажем выбранный файл через блокнот
            System.Diagnostics.Process exe = new System.Diagnostics.Process();
            exe.StartInfo.FileName = "Notepad.exe"; //Имя программы для запуска
            exe.StartInfo.Arguments = SelectFile(); //Выбрать файл через диалог
            exe.Start();        // Запускаем внешний процесс
            //exe.WaitForExit();// Останавливаем наш процесс до закрытия блокнота
            exe.Close();        // Освобождаем связанные с процессом ресурсы
        }
    
        // Выполнить шифрование
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            if (txtKey.Text == "")
            {
                MessageBox.Show(this, "Введите ключ для шифрования", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
    
            string destinationFile = "";
            if (Path.GetExtension(txtSourceFile.Text) != ".txt")
            {
                MessageBox.Show(this, "Выберите файл '*.txt' для шифрования", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            else
            {
                destinationFile = txtSourceFile.Text.Replace(".txt", String.Empty) + ".enc";
                destinationFile = Path.GetFileName(destinationFile);// Укороченное имя
                destinationFile = Path.Combine(txtDestinationDir.Text, destinationFile);
            }
    
            if (encryptData(txtSourceFile.Text, destinationFile, txtKey.Text))
                MessageBox.Show(this, "Выполнено!", "Шифрование файла",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show(this, "Процесс шифрования закончился неудачей!", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
    
        // Выполнить дешифрование
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            if (txtKey.Text == "")
            {
                MessageBox.Show(this, "Введите ключ для дешифрования", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
    
            string destinationFile = "";
            if (Path.GetExtension(txtSourceFile.Text) != ".enc")
            {
                MessageBox.Show(this, "Выберите файл '*.enc' для дешифрования", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            else
            {
                destinationFile = txtSourceFile.Text + ".txt";
                destinationFile = Path.GetFileName(destinationFile);// Укороченное имя
                destinationFile = Path.Combine(txtDestinationDir.Text, destinationFile);
            }
    
            if (decryptData(txtSourceFile.Text, destinationFile, txtKey.Text))
                MessageBox.Show(this, "Выполнено!", "Дешифрование файла",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show(this, "Процесс дешифрования закончился неудачей!", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
    
        // Шифруем заданный файл
        private bool encryptData(
            string sourceFile, string destinationFile, string cryptoKey)
        {
            FileStream inFileStream = null, outFileStream = null;
            CryptoStream cryptoStream = null;
            
            // Заготавливаем пустой ключ полного размера
            byte[] key = new byte[(int)numKeySize.Value / 8];
    
            try
            {
                // Создаем и настраиваем кодировщик
                ASCIIEncoding.ASCII.GetBytes(cryptoKey.Trim()).CopyTo(key, 0);// Заполняем ключ
                codec.Key = key;
                //codec.GenerateIV();
                ICryptoTransform encryptor = codec.CreateEncryptor();
    
                // Открываем исходный и результирующий файлы, используя файловый поток
                inFileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
                outFileStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write);
    
                // Создаем оболочку CryptoStream для записи шифрованного файла
                cryptoStream = new CryptoStream(outFileStream, encryptor, CryptoStreamMode.Write);
    
                // Объявляем массив файлов с длиной входного файла 
                byte[] bytes = new byte[inFileStream.Length];
    
                // Считываем входной файловый поток в массив байтов 
                // и записываем байты в CryptoStream
                inFileStream.Read(bytes, 0, bytes.Length);
                cryptoStream.Write(bytes, 0, bytes.Length);
    
                inFileStream.Flush();
                cryptoStream.FlushFinalBlock();
    
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(this, e.ToString(), "Encryption Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
    
                return false;
            }
            finally
            {
                // Освобождаем ресурсы в любом случае
                if (cryptoStream != null) cryptoStream.Close();
                if (inFileStream != null) inFileStream.Close();
                if (outFileStream != null) outFileStream.Close();
            }
        }
    
        // Расшифровываем указанный файл с тем же ключем и алгоритмом
        private bool decryptData(
            string sourceFile, string destinationFile, string cryptoKey)
        {
            CryptoStream cryptoStream = null;
            StreamWriter decryptedOut = null;
            FileStream decryptedFile = null;
            StreamReader streamReader = null;
    
            // Заготавливаем пустой ключ полного размера
            byte[] key = new byte[(int)numKeySize.Value / 8];
    
            try
            {
                // Создаем и настраиваем кодировщик
                ASCIIEncoding.ASCII.GetBytes(cryptoKey.Trim()).CopyTo(key, 0);// Заполняем ключ
                codec.Key = key;
                //codec.GenerateIV();
                ICryptoTransform decryptor = codec.CreateDecryptor();
    
                // Открываем исходный и результирующий файлы, используя файловый поток
                decryptedFile = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
    
                // Создаем оболочку CryptoStream для записи шифрованного файла
                cryptoStream = new CryptoStream(decryptedFile, decryptor, CryptoStreamMode.Read);
    
                decryptedOut = new StreamWriter(destinationFile);
                streamReader = new StreamReader(cryptoStream, Encoding.GetEncoding("windows-1251"));
                decryptedOut.Write(streamReader.ReadToEnd());
    
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(this, e.ToString(), "Decryption Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
    
                return false;
            }
            finally
            {
                // Освобождаем ресурсы в любом случае
                if (streamReader != null) streamReader.Close();
                if (cryptoStream != null) cryptoStream.Close();
                if (decryptedOut != null) decryptedOut.Close();
                if (decryptedFile != null) decryptedFile.Close();
            }
        }
    
        // Диалог выбора файла для обработки
        OpenFileDialog openFileDialog = new OpenFileDialog();
        String SelectFile()
        {
            // Настраиваем диалог выбора файла
            if (txtSourceFile.Text == String.Empty)
                openFileDialog.InitialDirectory = txtDestinationDir.Text;
            else
                openFileDialog.InitialDirectory = Path.GetDirectoryName(txtSourceFile.Text);
    
            openFileDialog.FileName = "";
            openFileDialog.Filter = "Source Files(*.txt;*.enc)|*.txt;*.enc";
            DialogResult result = openFileDialog.ShowDialog();
            if (result != DialogResult.Cancel)
                return openFileDialog.FileName; // Полное имя
            else
                return txtSourceFile.Text;
        }
    
        // Запуск диалога выбора файла
        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            txtSourceFile.Text = SelectFile();
            txtSourceFile.Focus();// Без этого не сохранится в установках приложения
        }
    
        // Запуск диалога выбора папки назначения
        FolderBrowserDialog dialogFolder = new FolderBrowserDialog();
        private void btnDestinationDir_Click(object sender, EventArgs e)
        {
            if (txtDestinationDir.Text == String.Empty ||
                Directory.Exists(txtDestinationDir.Text) == false)
            {
                dialogFolder.RootFolder =
                    System.Environment.SpecialFolder.MyComputer;
                dialogFolder.SelectedPath = "";
                txtDestinationDir.Text = String.Empty;
            }
            else
            {
                dialogFolder.SelectedPath = txtDestinationDir.Text;
            }
    
            dialogFolder.Description =
                "Выберите место размещения целевого файла";
    
            dialogFolder.ShowDialog();
            txtDestinationDir.Text = dialogFolder.SelectedPath;
            txtDestinationDir.Focus();
        }
    
        // Блокировка редактирования TextBox и NumericUpDown вручную
        private void EditKeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;
        }
        private void EditKeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }
    
        // При закрытии формы сохраняем параметры
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            settings.Save();
        }
    
        // Закрываем форму
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Каждый используемый алгоритм шифрования имеет свой фиксированный размер ключа, нарушение которого генерирует исключение. Поэтому мы вначале создаем байтовый массив фиксированного размера, а потом копируем в него содержимое пользовательского ключа, не превышающего по размеру допустимого. Незаполненные байты массива остаются нулевыми, зато этот прием позволяет принимать от пользователя ключи любой длины, не превышающей допустимую. В дополнение к этому на поле ввода ключа txtKey наложено ограничение по максимальной длине текста.

  • Запустите приложение Demo2 - оно вполне работоспособно и справляется с шифрованием при правильном обращении с ним
  • Разберитесь с кодом ( кому надо!), да простят меня классики

Внешний вид окна будет таким


Естественно, что при шифровании и дешифровании одного и того же документа алгоритм, ключ и его размер, а также размер блока шифрования должны быть одинаковыми.

< Лекция 5 || Лекция 6: 12345678910111213
Алексей Бабушкин
Алексей Бабушкин

При выполнении в лабораторной работе упражнения №1 , а именно при выполнении нижеследующего кода:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using Microsoft.Xna.Framework.Graphics;

   

namespace Application1

{

    public partial class MainForm : Form

    {

        // Объявим поле графического устройства для видимости в методах

        GraphicsDevice device;

   

        public MainForm()

        {

            InitializeComponent();

   

            // Подпишемся на событие Load формы

            this.Load += new EventHandler(MainForm_Load);

   

            // Попишемся на событие FormClosed формы

            this.FormClosed += new FormClosedEventHandler(MainForm_FormClosed);

        }

   

        void MainForm_FormClosed(object sender, FormClosedEventArgs e)

        {

            //  Удаляем (освобождаем) устройство

            device.Dispose();

            // На всякий случай присваиваем ссылке на устройство значение null

            device = null;       

        }

   

        void MainForm_Load(object sender, EventArgs e)

        {

            // Создаем объект представления для настройки графического устройства

            PresentationParameters presentParams = new PresentationParameters();

            // Настраиваем объект представления через его свойства

            presentParams.IsFullScreen = false; // Включаем оконный режим

            presentParams.BackBufferCount = 1;  // Включаем задний буфер

                                                // для двойной буферизации

            // Переключение переднего и заднего буферов

            // должно осуществляться с максимальной эффективностью

            presentParams.SwapEffect = SwapEffect.Discard;

            // Устанавливаем размеры заднего буфера по клиентской области окна формы

            presentParams.BackBufferWidth = this.ClientSize.Width;

            presentParams.BackBufferHeight = this.ClientSize.Height;

   

            // Создадим графическое устройство с заданными настройками

            device = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, DeviceType.Hardware,

                this.Handle, presentParams);

        }

   

        protected override void OnPaint(PaintEventArgs e)

        {

            device.Clear(Microsoft.Xna.Framework.Graphics.Color.CornflowerBlue);

   

            base.OnPaint(e);

        }

    }

}

Выбрасывается исключение:

Невозможно загрузить файл или сборку "Microsoft.Xna.Framework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d" или один из зависимых от них компонентов. Не удается найти указанный файл.

Делаю все пунктуально. В чем может быть проблема?