Функції модуля кодування - Розробка та дослідження засобів ідентифікації, аутентифікації і надання прав доступу до інформації на носіях

Усім користувачам доступна форма шифрування (Див. Рис. 2.1.), яку можна відрити у третій формі. В ній користувач має змогу зашифрувати, розшифрувати текст алгоритмом RSA (Див. Рис. 2.2.), зберегти результат та загрузити з txt файлу. Для програмної реалізації шифрування було використано клас RSACryptoServiceProvider стандартної бібліотеки Visual Studio System. Security. Cryptography.

RSA - криптографічна система з відкритим ключем. Безпека алгоритму RSA побудована на принципі складності факторизації цілих чисел. Алгоритм використовує два ключі - відкритий (public) і секретний (private), разом відкритий і відповідний йому секретний ключі утворюють пари ключів (keypair). Відкритий ключ не потрібно зберігати в таємниці, він використовується для шифрування даних. Якщо повідомлення було зашифровано відкритим ключем, то розшифрувати його можна тільки відповідним секретним ключем.

Генерування ключів

Для того, щоб згенерувати пари ключів виконуються такі дії:

    1. Вибір двох взаємно простих більших чисел Р и Q 2. Визначення їхнього добутку: N =р * q 3. Визначення функції Ейлера: (n) = (p-1) (q-1) 4. Вибір відкритого ключа Е з урахуванням умов: 1 5. Визначення секретного ключа d, що задовольняє умові

Е * d = 1 (mod (n)), де d < n

Алгоритм шифрування повідомлення М (дії відправника):

    1. Розбиває вихідний текст повідомлення на блоки (MI=0,1,2,..., n) 2. Шифрує текст повідомлення у вигляді послідовності блоків:

Ci = Мie (mod n)

    3. Відправляє одержувачеві криптограму: C1, C2,..., CN 4. Одержувач розшифровує криптограму за допомогою секретного ключа D за формулою:

MI = CID (mod n)

вікно шифрування

Рис. 2.1. Вікно шифрування

блок-схема алгоритму шифрування rsa

Рис. 2.2. Блок-схема алгоритму шифрування RSA

Додаток

Код класу Users

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Namespace WindowsFormsApplication1

{

Public class Users

{

String login;

String password;

String rules;

Public Users()

{

Login = "";

Password = "";

Rules = "R";

}

Public Users (String Login, String Password)

{

Login = Login;

Password = Password;

Rules = "R";

}

Public Users (String Login, String Password, String Rules)

{

Login = Login;

Password = Password;

Rules = Rules;

}

Public string Login

{

Get

{

Return login;

}

Set

{

}

}

Public string Password

{

Get

{

Return password;

}

Set

{

}

}

Public string Rules

{

Get

{

Return rules;

}

Set

{

Rules = value;

}

}

}

}

Код першої форми (форми шифрування)

Using System;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Data;

Using System. Drawing;

Using System. Linq;

Using System. Text;

Using System. Windows. Forms;

Using System. Security. Cryptography;

Using System. IO;

Namespace WindowsFormsApplication1

{

Public partial class Form1: Form

{

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

String publicKey;

String privateKey;

Byte[] EncryptedData;

Byte[] DecryptedData;

Byte[] Data = new byte[1024];

Public Form1 ()

{

InitializeComponent();

PublicKey = RSA. ToXmlString(false);

PrivateKey = RSA. ToXmlString(true);

}

Private void button3_Click (object sender, EventArgs e)

{

Data = Encoding. UTF8. GetBytes (richTextBox1. Text);

EncryptedData = RSA. Encrypt (Data, false);

RichTextBox2. Text = Convert. ToBase64String(EncryptedData);

TextBox2. Text = privateKey;

}

Private void button4_Click (object sender, EventArgs e)

{

If (textBox2. Text!= privateKey &;&; textBox2. Text!= "")

{

PrivateKey = textBox2. Text;

RSA. FromXmlString(privateKey);

Data = Convert. FromBase64String (richTextBox2. Text);

DecryptedData = RSA. Decrypt (Data, false);

RichTextBox1. Text = Encoding. UTF8. GetString(DecryptedData);

}

Else

{

Data = Convert. FromBase64String (richTextBox2. Text);

DecryptedData = RSA. Decrypt (Data, false);

RichTextBox1. Text = Encoding. UTF8. GetString(DecryptedData);

}

}

Private void button1_Click (object sender, EventArgs e)

{

If (openFileDialog1. ShowDialog() == DialogResult. OK)

{

StreamReader sr = new StreamReader (openFileDialog1. FileName);

RichTextBox2. Text = sr. ReadToEnd();

Sr. Close();

}

}

Private void button2_Click (object sender, EventArgs e)

{

If (openFileDialog1. ShowDialog() == DialogResult. OK)

{

StreamWriter sw = new StreamWriter (openFileDialog1. FileName);

Sw. WriteLine (richTextBox2. Text);

Sw. Close();

}

}

Private void button5_Click (object sender, EventArgs e)

{

If (openFileDialog1. ShowDialog() == DialogResult. OK)

{

StreamWriter sw = new StreamWriter (openFileDialog1. FileName);

Sw. WriteLine (textBox2. Text);

Sw. Close();

}

}

Private void button6_Click (object sender, EventArgs e)

{

If (openFileDialog1. ShowDialog() == DialogResult. OK)

{

StreamReader sr = new StreamReader (openFileDialog1. FileName);

TextBox2. Text = sr. ReadToEnd();

Sr. Close();

}

}

}

}

Код другої форми (форми аутинфікації та ідентифікації)

Using System;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Data;

Using System. Drawing;

Using System. Linq;

Using System. Text;

Using System. Windows. Forms;

Using System. IO;

Namespace WindowsFormsApplication1

{

Public partial class Form2: Form

{

List<Users> Users = new List<Users>();

Double x;

Double a;

Double answer = 0;

Int result;

Int user_index = 0;

Public Form2 ()

{

InitializeComponent();

Users. Add (new Users ("admin", "admin", "A"));

Users. Add (new Users ("login", "password"));

Users. Add (new Users ("test1", "test1", "E"));

}

Private void button1_Click (object sender, EventArgs e)

{

If (textBox1. Text!= "" &;&; textBox2. Text!= "" &;&; textBox4. Text!= "")

{

If (Cheak (textBox1. Text, textBox2. Text) == true &;&; Convert. ToString(result) == textBox4. Text)

{

MessageBox. Show ("Вы вошли как" + textBox1. Text);

Form4 f = new Form4 (Users[user_index].Login, Users [user_index].Rules, Users, this);

F. Show();

This. Hide();

}

Else

{

If (textBox4. Text!= Convert. ToString(result))

{

MessageBox. Show ("Вы ввели не верный ответ");

Generate_answer();

}

Else

{

MessageBox. Show ("Неверный логин / пароль");

}

}

}

Else

{

MessageBox. Show ("Все поля должны быть заполнены");

}

}

Private void Form2_Load (object sender, EventArgs e)

{

Generate_answer();

Get_users();

}

Private void label6_Click (object sender, EventArgs e)

{

Form3 f = new Form3 (this);

F. Show();

}

Public void Generate_answer()

{

Random rnd = new Random();

X = rnd. Next (1, 100000);

A = rnd. Next (1, 100000);

Result = Convert. ToInt32 (Math. Log (a * x));

TextBox3. Text = "x =" + x +"; a =" + a +";";

TextBox4. Text = Convert. ToString(result);

}

Public Boolean Cheak (string login, string password)

{

For (int i = 0; i < Users. Count; i++)

{

If (login == Users[i].Login)

{

If (password == Users[i].Password)

{

User_index = i;

Return true;

}

Else

{

Return false;

}

}

}

Return false;

}

Public Boolean Cheak_logins (string login)

{

For (int i = 0; i < Users. Count; i++)

{

If (Users[i].Login == login)

{

Return false;

}

}

Return true;

}

Public void Get_users()

{

StreamReader sr = new StreamReader (Environment. CurrentDirectory + "Users. txt");

For (string a = "";! sr. EndOfStream;)

{

A = sr. ReadLine();

String[] b = a. Split (' ', ';', '-', ' ');

If (b[0]!= "" &;&; b[1]!= "" &;&; b[3]!= "")

{

Add_user (b[0], b[1], b[3]);

}

}

Sr. Close();

}

Public void Add_user (string login, string password, string rules)

{

Users. Add (new Users (login, password, rules));

}

Public void Delete_ueser (string my_login, string login)

{

If (my_login == "admin")

{

For (int i = 0; i < Users. Count; i++)

{

If (Users[i].Login == login)

{

Users. RemoveAt(i);

Break;

}

}

}

}

Public void Reset()

{

Users = null;

Users = new List<Users>();

Users. Add (new Users ("admin", "admin", "A"));

Users. Add (new Users ("login", "password"));

Users. Add (new Users ("test1", "test1", "E"));

TextBox1. Text = "";

TextBox2. Text = "";

TextBox4. Text = "";

Generate_answer();

Get_users();

}

}

}

Код третьої форми (форми реєстрації)

Using System;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Data;

Using System. Drawing;

Using System. Linq;

Using System. Text;

Using System. Windows. Forms;

Using System. IO;

Namespace WindowsFormsApplication1

{

Public partial class Form3: Form

{

Form2 F;

Public Form3 ()

{

InitializeComponent();

}

Public Form3 (Form2 f)

{

InitializeComponent();

F = f;

}

Private void button1_Click (object sender, EventArgs e)

{

If (textBox2. Text == textBox3. Text &;&; textBox2. Text!= "" &;&; textBox1. Text!= "")

{

If (F. Cheak_logins (textBox1. Text) == true)

{

StreamWriter sw = new StreamWriter (Environment. CurrentDirectory + "Users. txt", true);

Sw. WriteLine (textBox1. Text +";" + textBox2. Text +" - R");

Sw. Close();

F. Add_user (textBox1. Text, textBox2. Text, "R");

MessageBox. Show ("Регистрация прошла успешно");

This. Close();

}

Else

{

MessageBox. Show ("Такой логин уже зарегистрирован, введите другой");

}

}

Else

{

MessageBox. Show ("Ошибка ввода данных");

}

}

}

}

Код четвертої форми (форми доступу до локальних дисків)

Using System;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Data;

Using System. Drawing;

Using System. Linq;

Using System. Text;

Using System. Windows. Forms;

Using System. IO;

Namespace WindowsFormsApplication1

{

Public partial class Form4: Form

{

String login = "";

String rules = "R";

List<Users> Users;

Form2 F;

Public Form4 ()

{

InitializeComponent();

}

Public Form4 (string Login, string Rules, List<Users> user, Form2 f)

{

InitializeComponent();

Login = Login;

Rules = Rules;

This. Text = login;

Users = user;

F = f;

}

Private void Form4_Load (object sender, EventArgs e)

{

String system = Environment. GetFolderPath (Environment. SpecialFolder. System);

DirectoryInfo dirInfo = new DirectoryInfo(system);

DriveInfo[] dr = DriveInfo. GetDrives();

Foreach (DriveInfo d in dr)

{

Try

{

If (d. DriveType!= DriveType. CDRom)

{

If (d. RootDirectory. Name!= dirInfo. Root. Name)

{

TreeNode aNode = new TreeNode (d. Name);

TreeView1. Nodes. Add(aNode);

}

Else

{

If (login == "admin" || rules == "A")

{

TreeNode aNode = new TreeNode (d. Name);

TreeView1. Nodes. Add(aNode);

}

}

}

}

Catch (Exception)

{

MessageBox. Show ("Устройство не готово");

}

}

If (login == "admin")

{

УправлениеПользователямиToolStripMenuItem. Enabled = true;

}

}

Private void treeView1_AfterSelect (object sender, TreeViewEventArgs e)

{

String path = treeView1. SelectedNode. FullPath;

DirectoryInfo dir = new DirectoryInfo(path);

TreeNode aNode = new TreeNode(path);

Foreach (DirectoryInfo drs in dir. GetDirectories())

{

Add_node (treeView1. SelectedNode, drs. Name);

}

}

Public void Add_node (TreeNode node, string value)

{

Node. Nodes. Add(value);

}

Private void treeView1_NodeMouseDoubleClick (object sender, TreeNodeMouseClickEventArgs e)

{

String path = treeView1. SelectedNode. FullPath;

DirectoryInfo dir = new DirectoryInfo(path);

System. Diagnostics. Process. Start ("explorer", dir. FullName);

}

Private void открытьФормуШифрованияToolStripMenuItem_Click (object sender, EventArgs e)

{

Form1 f = new Form1 ();

F. Show();

}

Private void управлениеПользователямиToolStripMenuItem_Click (object sender, EventArgs e)

{

Form5 f = new Form5 (Users);

F. Show();

}

Private void завершитьСеансToolStripMenuItem_Click (object sender, EventArgs e)

{

F. Reset();

F. Show();

This. Close();

}

}

}

Код п'ятої форми (форми керуванням зареєстрованими користувачами)

Using System;

Using System. Collections. Generic;

Using System. ComponentModel;

Using System. Data;

Using System. Drawing;

Using System. Linq;

Using System. Text;

Using System. Windows. Forms;

Using System. IO;

Namespace WindowsFormsApplication1

{

Public partial class Form5: Form

{

List<Users> Users;

Public Form5 ()

{

InitializeComponent();

}

Public Form5 (List<Users> users)

{

InitializeComponent();

Users = users;

}

Private void Form5_Load (object sender, EventArgs e)

{

For (int i = 0; i < Users. Count; i++)

{

ComboBox1. Items. Add (Users[i].Login);

}

}

Private void button1_Click (object sender, EventArgs e)

{

String path = Environment. CurrentDirectory + "Users. txt";

String str = "";

Try

{

Using (StreamReader sr = new StreamReader(path))

{

While (sr. Peek() >= 0)

{

String temp = sr. ReadLine();

If (temp. IndexOf (comboBox1. Text)!= -1)

{

ComboBox1. Items. Remove (comboBox1. Text);

TextBox1. Text = "";

}

Else

{

Str += temp + " ";

}

}

}

If (! str. Equals(""))

Str = str. Substring (0, str. Length - 2);

}

Catch (Exception)

{

MessageBox. Show ("Возникли проблемы с чтением данных!");

Return;

}

Try

{

Using (StreamWriter sw = new StreamWriter(path))

{

Sw. Write(str);

}

}

Catch (Exception)

{

MessageBox. Show ("Возникли проблемы с записью данных!");

}

MessageBox. Show ("Пользователь успешно удален!");

}

Private void comboBox1_TextChanged (object sender, EventArgs e)

{

For (int i = 0; i < Users. Count; i++)

{

If (comboBox1. Text == Users[i].Login)

{

TextBox1. Text = Users[i].Rules;

}

}

}

Private void button2_Click (object sender, EventArgs e)

{

If (textBox1. Text!= "")

{

For (int i = 0; i < Users. Count; i++)

{

If (Users[i].Login == comboBox1. Text)

{

Users[i].Rules = textBox1. Text;

String path = Environment. CurrentDirectory + "Users. txt";

String str = "";

Try

{

Using (StreamReader sr = new StreamReader(path))

{

While (sr. Peek() >= 0)

{

String temp = sr. ReadLine();

If (temp. IndexOf (comboBox1. Text)!= -1)

{

Str += Users[i].Login +";" + Users[i].Password +" - "+ Users[i].Rules + " ";

}

Else

{

Str += temp + " ";

}

}

}

// if (! str. Equals(""))

// str = str. Substring (0, str. Length - 2);

}

Catch (Exception)

{

MessageBox. Show ("Возникли проблемы с чтением данных!");

Return;

}

Try

{

Using (StreamWriter sw = new StreamWriter(path))

{

Sw. Write(str);

}

}

Catch (Exception)

{

MessageBox. Show ("Возникли проблемы с записью данных!");

}

MessageBox. Show ("Права изменены");

}

}

}

}

}

}

Похожие статьи




Функції модуля кодування - Розробка та дослідження засобів ідентифікації, аутентифікації і надання прав доступу до інформації на носіях

Предыдущая | Следующая