Шифрующая таблица Трисемуса с ключевым словом - C#
Формулировка задачи:
Всем привет.Есть программа для шифрования/дешифрования, но не могу сделать что бы шифровалось по ключевом слове. Буду рад любой помощи.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
textBox1.Text = sr.ReadToEnd();
sr.Close();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void выходToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button3_Click(object sender, EventArgs e)
{
string Ex2 = textBox2.Text;
int cols1 = (int)Math.Ceiling(Math.Sqrt(Ex2.Length));
int rows1 = (int)Math.Ceiling(Ex2.Length / (double)cols1);
dataGridView2.RowCount = rows1;
dataGridView2.ColumnCount = cols1;
for (int j = 0; j < rows1; j++)
for (int i = 0; i < cols1; i++)
if (Ex2.Length > j * cols1 + i) dataGridView2[i, j].Value = Ex2[j * cols1 + i];
else dataGridView1[i, j].Value = '+';
StringBuilder sb1 = new StringBuilder();
for (int i = 0; i < cols1; i++)
for (int j = 0; j < rows1; j++)
sb1.Append(dataGridView2[i, j].Value.ToString());
string str1 = sb1.ToString();
string str = "";
for (int i = 0; i < str1.Length; i++)
{
if (char.IsLetter(str1[i])) str = str + str1[i];
else
{
str = str;
}
}
textBox3.Text = str;
}
private void button2_Click(object sender, EventArgs e)
{
string s = textBox1.Text;
int cols = (int)Math.Ceiling(Math.Sqrt(s.Length));
int rows = (int)Math.Ceiling(s.Length / (double)cols);
dataGridView1.RowCount = rows;
dataGridView1.ColumnCount = cols;
for (int i = 0; i < cols; i++)
for (int j = 0; j < rows; j++)
if (s.Length > i * rows + j) dataGridView1[i, j].Value = s[i * rows + j];
else dataGridView1[i, j].Value = '+';
StringBuilder sb = new StringBuilder();
for (int j = 0; j < rows; j++)
for (int i = 0; i < cols; i++)
sb.Append(dataGridView1[i, j].Value.ToString());
textBox2.Text = sb.ToString();
}
}Решение задачи: «Шифрующая таблица Трисемуса с ключевым словом»
textual
Листинг программы
# -*- coding: utf-8 -*-
# autor: maksim32
# task: Реализация шифрующей таблицы Трисемуса
# date: 2017-09-10
import sys
g_alphabet = u"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ."
def Trisemus(key, strval, action):
keyword, (height, width) = key
isEncode = True if action == "encode" else False
isDecode = True if action == "decode" else False
# построение таблицы
pos = 0
table = [['.' for x in xrange(width)] for y in xrange(height)]
hchars = {}
for i in keyword + g_alphabet:
if hchars.get(i) == None:
hchars[i] = pos
table[pos / width][pos % width] = i
pos += 1
if pos >= width * height:
break
#print '\n'.join(' '.join(j for j in table[i]) for i in range(len(table))) # debug: output table
result = ""
for i in strval:
pos = hchars.get(i)
if pos != None:
x = pos % width
if isEncode:
y = (pos / width + 1) % height
elif isDecode:
y = (pos / width - 1 + height) % height
else:
y = pos / width % height # do nothing
result += table[y][x]
else: # далее нужно выбрать одно из действий с символами, отсутсвующими в таблице:
result += i # оставить неизменными
#result += "" # удалить
#result += table[height - 1][width - 1] # заменять на определённый
return result
# end def
keyword = u"ПРЕФЕКТУРА"
tablesize = (5, 7)
key = (keyword, tablesize)
print "key = " + str(key)
inputstr = unicode(raw_input("Text to encode: "), sys.stdout.encoding)
inputstr = u"АББАТ ТРИСЕМУС, ТАБЛИЦА." if inputstr == "" else inputstr # default
print inputstr
s = Trisemus(key, inputstr, "encode")
print s
s = Trisemus(key, s, "decode")
print s