Шифрующая таблица Трисемуса с ключевым словом - C#

Узнай цену своей работы

Формулировка задачи:

Всем привет.Есть программа для шифрования/дешифрования, но не могу сделать что бы шифровалось по ключевом слове. Буду рад любой помощи.
Листинг программы
  1. namespace WindowsFormsApplication1
  2. {
  3. public partial class Form1 : Form
  4. {
  5. public Form1()
  6. {
  7. InitializeComponent();
  8. }
  9. private void button1_Click(object sender, EventArgs e)
  10. {
  11. if (openFileDialog1.ShowDialog() == DialogResult.OK)
  12. {
  13. StreamReader sr = new StreamReader(openFileDialog1.FileName);
  14. textBox1.Text = sr.ReadToEnd();
  15. sr.Close();
  16. }
  17. }
  18. private void pictureBox1_Click(object sender, EventArgs e)
  19. {
  20. }
  21. private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
  22. {
  23. }
  24. private void выходToolStripMenuItem_Click(object sender, EventArgs e)
  25. {
  26. Application.Exit();
  27. }
  28. private void button3_Click(object sender, EventArgs e)
  29. {
  30. string Ex2 = textBox2.Text;
  31. int cols1 = (int)Math.Ceiling(Math.Sqrt(Ex2.Length));
  32. int rows1 = (int)Math.Ceiling(Ex2.Length / (double)cols1);
  33. dataGridView2.RowCount = rows1;
  34. dataGridView2.ColumnCount = cols1;
  35. for (int j = 0; j < rows1; j++)
  36. for (int i = 0; i < cols1; i++)
  37. if (Ex2.Length > j * cols1 + i) dataGridView2[i, j].Value = Ex2[j * cols1 + i];
  38. else dataGridView1[i, j].Value = '+';
  39. StringBuilder sb1 = new StringBuilder();
  40. for (int i = 0; i < cols1; i++)
  41. for (int j = 0; j < rows1; j++)
  42. sb1.Append(dataGridView2[i, j].Value.ToString());
  43. string str1 = sb1.ToString();
  44. string str = "";
  45. for (int i = 0; i < str1.Length; i++)
  46. {
  47. if (char.IsLetter(str1[i])) str = str + str1[i];
  48. else
  49. {
  50. str = str;
  51. }
  52. }
  53. textBox3.Text = str;
  54. }
  55. private void button2_Click(object sender, EventArgs e)
  56. {
  57. string s = textBox1.Text;
  58. int cols = (int)Math.Ceiling(Math.Sqrt(s.Length));
  59. int rows = (int)Math.Ceiling(s.Length / (double)cols);
  60. dataGridView1.RowCount = rows;
  61. dataGridView1.ColumnCount = cols;
  62. for (int i = 0; i < cols; i++)
  63. for (int j = 0; j < rows; j++)
  64. if (s.Length > i * rows + j) dataGridView1[i, j].Value = s[i * rows + j];
  65. else dataGridView1[i, j].Value = '+';
  66. StringBuilder sb = new StringBuilder();
  67. for (int j = 0; j < rows; j++)
  68. for (int i = 0; i < cols; i++)
  69. sb.Append(dataGridView1[i, j].Value.ToString());
  70. textBox2.Text = sb.ToString();
  71. }
  72. }

Решение задачи: «Шифрующая таблица Трисемуса с ключевым словом»

textual
Листинг программы
  1. # -*- coding: utf-8 -*-
  2.  
  3. # autor: maksim32
  4. # task: Реализация шифрующей таблицы Трисемуса
  5. # date: 2017-09-10
  6.  
  7. import sys
  8.  
  9. g_alphabet = u"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ."
  10.  
  11. def Trisemus(key, strval, action):
  12.     keyword, (height, width) = key
  13.     isEncode = True if action == "encode" else False
  14.     isDecode = True if action == "decode" else False
  15.    
  16.     # построение таблицы
  17.     pos = 0
  18.     table = [['.' for x in xrange(width)] for y in xrange(height)]
  19.     hchars = {}
  20.     for i in keyword + g_alphabet:
  21.         if hchars.get(i) == None:
  22.             hchars[i] = pos
  23.             table[pos / width][pos % width] = i
  24.             pos += 1
  25.             if pos >= width * height:
  26.                 break
  27.     #print '\n'.join(' '.join(j for j in table[i]) for i in range(len(table))) # debug: output table
  28.    
  29.     result = ""
  30.     for i in strval:
  31.         pos = hchars.get(i)
  32.         if pos != None:
  33.             x = pos % width
  34.             if isEncode:
  35.                 y = (pos / width + 1) % height
  36.             elif isDecode:
  37.                 y = (pos / width - 1 + height) % height
  38.             else:
  39.                 y = pos / width % height # do nothing
  40.             result += table[y][x]
  41.         else: # далее нужно выбрать одно из действий с символами, отсутсвующими в таблице:
  42.             result += i # оставить неизменными
  43.             #result += "" # удалить
  44.             #result += table[height - 1][width - 1] # заменять на определённый
  45.    
  46.     return result
  47. # end def
  48.  
  49.  
  50. keyword = u"ПРЕФЕКТУРА"
  51. tablesize = (5, 7)
  52. key = (keyword, tablesize)
  53. print "key = " + str(key)
  54.  
  55. inputstr = unicode(raw_input("Text to encode: "), sys.stdout.encoding)
  56. inputstr = u"АББАТ ТРИСЕМУС, ТАБЛИЦА." if inputstr == "" else inputstr # default
  57.  
  58. print inputstr
  59. s = Trisemus(key, inputstr, "encode")
  60. print s
  61. s = Trisemus(key, s, "decode")
  62. print s

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут