Практические работы Часть 2 / Практическая работа10 / пр10
.docxПрактическая работа №10
Шифрование данных в асимметричных криптосистемах
Цель работы: изучить методы шифрования данных по схеме Эль-Гамаля, алгоритма на основе задачи об укладке ранца и освоить их практическое применение.
Ход работы
Задание 1. Зашифровать свое ФИО с помощью шифра Эль-Гамаля (реализовать Windows Forms C#)
Листинг 1:
using System;
using System.Windows.Forms;
namespace ЭльГамаля {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
int p = int.Parse(textBox3.Text);
int g = int.Parse(textBox4.Text);
int x = int.Parse(textBox5.Text);
int k = int.Parse(textBox7.Text);
string openText = textBox1.Text;
ElGamalEncryption ex = new ElGamalEncryption(p, g, x, openText);
textBox2.Text = ex.GetCipher(k);
textBox6.Text = ex.Y.ToString();
textBox12.Text = textBox3.Text;
textBox11.Text = textBox4.Text;
textBox10.Text = textBox5.Text;
textBox8.Text = textBox7.Text;
textBox14.Text = textBox2.Text;
}
private void button2_Click(object sender, EventArgs e) {
int p = int.Parse(textBox12.Text);
int g = int.Parse(textBox11.Text);
int x = int.Parse(textBox10.Text);
int k = int.Parse(textBox8.Text);
string[] stringShifr = textBox14.Text.Split(' ');
int[] shifr = new int[stringShifr.Length - 1];
for (int i = 0; i < stringShifr.Length - 1; i++) {
shifr[i] = int.Parse(stringShifr[i]);
}
ElGamalEncryption ex = new ElGamalEncryption(p, g, x);
textBox13.Text = ex.GetDecryptedText(shifr);
}
}
public class ElGamalEncryption {
private int P;
private int G;
private int X;
private string alphabit = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя ";
public string OpenText { get; set; }
public int Y { get; private set; }
public ElGamalEncryption(int p, int g, int x, string openText) {
P = p; G = g; X = x;
OpenText = openText;
}
public ElGamalEncryption(int p, int g, int x) : this(p, g, x, null) { }
public string GetCipher(int k) {
if (ValidationX(P, G, X) == -1) {
MessageBox.Show("Не правильный закрытый ключ!");
return null;
}
int y = Convert.ToInt32(Math.Pow(G, X)) % P;
this.Y = y;
int a = Convert.ToInt32(Math.Pow(G, k)) % P;
int lengthAlphabit = alphabit.Length;
int lengthOpenText = OpenText.Length;
int[] indexesSymbols = new int[lengthOpenText];
double[] b = new double[lengthAlphabit];
for (int i = 0; i < lengthOpenText; i++) {
for (int j = 0; j < lengthAlphabit; j++) {
if (alphabit[j] == OpenText[i]) {
indexesSymbols[i] = (j + 1);
b[i] = (Math.Pow(y, k) * indexesSymbols[i]) % P;
break;
}
}
}
string shifr = "";
for (int i = 0; i < lengthOpenText; i++) {
shifr += b[i].ToString() + " ";
}
return shifr;
}
private int ValidationX(int p, int g, int x) {
double mod = Math.Pow(g, x) % p;
double mod2 = mod % p;
return mod2 != mod ? -1 : 0;
}
public string GetDecryptedText(int[] b) {
if (ValidationX(P, G, X) == -1) {
MessageBox.Show("Не правильный закрытый ключ!");
return null;
}
int lenghtB = b.Length;
int[] T = new int[lenghtB];
for (int i = 0; i < lenghtB; i++) {
T[i] = (b[i] * G) % P;
}
int lengthAlphabit = alphabit.Length;
string text = "";
for (int i = 0; i < lenghtB; i++) {
text += alphabit[T[i] - 1];
}
return text;
}
}
}
Результат работы программы:
Задание 2. Реализовать ассиметричное шифрование с помощью алгоритма на основе задачи об укладке ранца (Windows Form C#).
Листинг 2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace рюкзак {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
string openText = textBox1.Text;
int lenghtOpenText = openText.Length;
byte[] unicodeBytes = Encoding.Unicode.GetBytes(openText);
byte[] asciiBytes = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding("Windows-1251"), unicodeBytes);
string[] codeOpenText = new string[lenghtOpenText];
for (int i = 0; i < lenghtOpenText; i++)
codeOpenText[i] = Convert.ToString(asciiBytes[i], 2);
string[] key = publicKey(int.Parse(textBox4.Text), int.Parse(textBox5.Text),
textBox2.Text.Split(' '));
int[] summ = new int[lenghtOpenText];
for (int i = 0; i < lenghtOpenText; i++) {
string charSymbol = codeOpenText[i];
summ[i] = 0;
for (int j = 0; j < charSymbol.Length; j++)
if (charSymbol[j] == '1') summ[i] += int.Parse(key[j]);
}
textBox3.Clear();
for (int i = 0; i < lenghtOpenText; i++) {
if (i == lenghtOpenText - 1) textBox3.Text += summ[i];
else textBox3.Text += summ[i] + " ";
}
}
private string[] publicKey(int n, int m, string[] privateKey) {
string[] publicKey = new string[privateKey.Length];
for (int i = 0; i < privateKey.Length; i++) {
int key = int.Parse(privateKey[i]);
int key2 = (key * n) % m;
publicKey[i] = key2.ToString();
}
return publicKey;
}
private void button2_Click(object sender, EventArgs e) {
string[] shifr = textBox3.Text.Split(' ');
string[] c = publicKey(int.Parse(textBox7.Text), int.Parse(textBox5.Text), shifr);
string[] privateKey = textBox2.Text.Split(' ');
string text = "";
for (int i = 0; i < c.Length; i++) {
List<int> ves = new List<int>();
int value = int.Parse(c[i]);
int j;
int summ = ves.Sum();
while (int.Parse(c[i]) != summ) {
for (j = privateKey.Count() - 1; j >= 0; j--)
if (int.Parse(privateKey[j]) <= value) break;
ves.Add(int.Parse(privateKey[j]));
value -= int.Parse(privateKey[j]);
summ = ves.Sum();
}
byte[] binCode = new byte[privateKey.Count()];
for (int z = ves.Count() - 1; z >= 0; z--) {
int k;
for (k = 0; k < privateKey.Count(); k++)
if (ves[z] == int.Parse(privateKey[k])) break;
binCode[k] = 1;
}
string stringBinCode = "";
for (int z = 0; z < binCode.Count(); z++)
stringBinCode += binCode[z].ToString();
char ch = Encoding.GetEncoding(1251).GetString(new byte[] { Convert.ToByte(stringBinCode, 2) })[0];
text += ch;
}
textBox6.Text = text;
}
}
}
Результат работы программы: