Взломать шифр Виженера методом частотного анализа - C#

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

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

Добрый вечер, сообщество. Возникла трудная задача, необходимо взломать шифр Виженера. Основная проблема в том, что я не могу найти внятную информацию о том как это сделать и хотя бы один законченный пример. Я приведу пример своего кода, здесь я шифрую текст, расшифровываю его для проверки работы алгоритма шифрования, потом получаю длину ключевого слово методом Касиски, но дальше ничего. Может хоть кто-нибудь знает как это сделать?
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Lab1IT
  5. {
  6. public class Lab1Task1
  7. {
  8. public List<char> abc = new List<char>();
  9. public int GetIndex(char c)
  10. {
  11. for (int i = 0; i < abc.Count; i++)
  12. {
  13. if (abc[i] == c)
  14. return i;
  15. }
  16. return 0;
  17. }
  18. public int GetOffeset(char c)
  19. {
  20. return GetIndex (c) - GetIndex ('a');
  21. }
  22. public void InitABC()
  23. {
  24. for (int i = 97; i < 123; i++)
  25. abc.Add ((char)i);
  26. // for (int i = 1072; i < 1104; i++)
  27. // abc.Add ((char)i);
  28. }
  29. public void Encrypt (string file, string resultFile, string key)
  30. {
  31. string result = "";
  32. string message = System.IO.File.ReadAllText(file);
  33. key = PreapareKey (key, message);
  34. for (int i = 0; i < message.Length; i++)
  35. {
  36. if (message [i] != ' ')
  37. {
  38. int index = GetIndex (message [i]);
  39. int res = (index + GetIndex (key [i])) % abc.Count;
  40. result += abc [res];
  41. }
  42. else
  43. result += ' ';
  44. }
  45. System.IO.File.WriteAllText (resultFile,result,System.Text.Encoding.UTF8);
  46. Console.WriteLine (result);
  47. }
  48. public void Decrypt (string file, string resultFile, string key)
  49. {
  50. string result = "";
  51. string message = System.IO.File.ReadAllText(file);
  52. key = PreapareKey (key, message);
  53. for (int i = 0; i < message.Length; i++)
  54. {
  55. if (message [i] != ' ')
  56. {
  57. int index = GetIndex(message[i]);
  58. int res = (index - GetIndex(key[i]) + abc.Count) % abc.Count;
  59. result += abc[res];
  60. }
  61. else
  62. result += ' ';
  63. }
  64. System.IO.File.WriteAllText (resultFile,result,System.Text.Encoding.UTF8);
  65. Console.WriteLine (result);
  66. }
  67. public string PreapareKey(string key, string message)
  68. {
  69. string newKey = "";
  70. while (newKey.Length < message.Length)
  71. newKey = newKey + key;
  72. if (newKey.Length < message.Length)
  73. newKey.Remove (message.Length);
  74. return newKey;
  75. }
  76. public Lab1Task1()
  77. {
  78. InitABC ();
  79. }
  80. }
  81.  
  82. public class Lab1Task2
  83. {
  84. public int lgramsLength = 3;
  85. public Dictionary <char,double> values = new Dictionary<char, double> ();
  86. public Lab1Task2()
  87. {
  88. values.Add ('a', 0.08167f);
  89. values.Add ('b', 0.01492f);
  90. values.Add ('c', 0.02782f);
  91. values.Add ('d', 0.04253f);
  92. values.Add ('e', 0.12702f);
  93. values.Add ('f', 0.02228f);
  94. values.Add ('g', 0.02015f);
  95. values.Add ('h', 0.06094f);
  96. values.Add ('i', 0.06966f);
  97. values.Add ('j', 0.00153f);
  98. values.Add ('k', 0.00772f);
  99. values.Add ('l', 0.04025f);
  100. values.Add ('m', 0.02406f);
  101. values.Add ('n', 0.06749f);
  102. values.Add ('o', 0.07507f);
  103. values.Add ('p', 0.01929f);
  104. values.Add ('q', 0.00095f);
  105. values.Add ('r', 0.05987f);
  106. values.Add ('s', 0.06327f);
  107. values.Add ('t', 0.09056f);
  108. values.Add ('u', 0.02758f);
  109. values.Add ('v', 0.00978f);
  110. values.Add ('w', 0.02360f);
  111. values.Add ('x', 0.00150f);
  112. values.Add ('y', 0.01974f);
  113. values.Add ('z', 0.00074f);
  114. // values.Add ('а', );
  115. // values.Add ('б', );
  116. // values.Add ('в', );
  117. // values.Add ('г', );
  118. // values.Add ('д', );
  119. // values.Add ('е', );
  120. // values.Add ('ж', );
  121. // values.Add ('з', );
  122. // values.Add ('и', );
  123. // values.Add ('к', );
  124. // values.Add ('л', );
  125. // values.Add ('м', );
  126. // values.Add ('н', );
  127. // values.Add ('о', );
  128. // values.Add ('п', );
  129. // values.Add ('р', );
  130. // values.Add ('с', );
  131. // values.Add ('т', );
  132. // values.Add ('у', );
  133. // values.Add ('ф', );
  134. // values.Add ('х', );
  135. // values.Add ('ц', );
  136. // values.Add ('ч', );
  137. // values.Add ('ш', );
  138. // values.Add ('щ', );
  139. // values.Add ('ъ', );
  140. // values.Add ('ы', );
  141. // values.Add ('ь', );
  142. // values.Add ('э', );
  143. // values.Add ('ю', );
  144. // values.Add ('я', );
  145. }
  146. int GCD(int a, int b)
  147. {
  148. return b == 0 ? a : GCD(b, a % b);
  149. }
  150. void GCD(List<int> repeatCount)
  151. {
  152. Dictionary<int,int> pairs = new Dictionary<int, int> ();
  153. Console.WriteLine (repeatCount.Count);
  154. for (int i = 0; i < repeatCount.Count; i++)
  155. {
  156. for (int j = i + 1; j < repeatCount.Count; j++)
  157. {
  158. int gc = GCD (repeatCount [i], repeatCount [j]);
  159. if (gc > 1)
  160. {
  161. if (pairs.ContainsKey (gc))
  162. pairs [gc]++;
  163. else
  164. pairs.Add (gc, 1);
  165. }
  166. }
  167. }
  168. var sortDict = pairs.OrderByDescending (x => x.Value).Take(5);
  169. foreach (var s in sortDict)
  170. {
  171. if(s.Value>0)
  172. {
  173. Console.Write (s.Key + " ");
  174. }
  175. }
  176. Console.WriteLine ();
  177. }
  178. public void SearchLGrams(string file)
  179. {
  180. string message = System.IO.File.ReadAllText(file);
  181. List<int> repeats = new List<int>();
  182. for (int i = 0; i < message.Length - lgramsLength; i++)
  183. {
  184. string lgram1 = message.Substring(i,lgramsLength);
  185. for (int j = i+1; j < message.Length - lgramsLength; j++)
  186. {
  187. string lgram2 = message.Substring(j,lgramsLength);
  188. if (lgram1.Equals(lgram2))
  189. {
  190. repeats.Add (j - i);
  191. }
  192. }
  193. }
  194. GCD (repeats);
  195. string text = message.Replace(" ", string.Empty).ToLower();
  196. double symbolsCount = text.Length;
  197.  
  198. SortedDictionary< char, int > dict = new SortedDictionary<char, int>();
  199. for (int i = 0; i < text.Length; i++)
  200. if (dict.ContainsKey(text[i]))
  201. dict[text[i]]++;
  202. else
  203. dict.Add(text[i], 1);
  204. var sortDict = dict.OrderByDescending(x => x.Value);
  205. Dictionary<char,double> resultedValues = new Dictionary<char, double> ();
  206. foreach (KeyValuePair< char, int > kvp in sortDict)
  207. {
  208. double val = System.Math.Round((double)kvp.Value/symbolsCount,5);
  209. resultedValues.Add(kvp.Key,val);
  210. Console.WriteLine ("Символ: {0}, встречается {1} раз. Частота {2}. Дано {3}", kvp.Key,
  211. kvp.Value,val,System.Math.Round((double)values[kvp.Key],5));
  212. }
  213. }
  214. }
  215.  
  216. class MainClass
  217. {
  218. public static void Main (string[] args)
  219. {
  220. Lab1Task1 lab1Task1 = new Lab1Task1 ();
  221. lab1Task1.Encrypt ("/Users/Alexander/Projects/Lab1IT/Lab1IT/files/code.txt", "/Users/Alexander/Projects/Lab1IT/Lab1IT/files/encoded.txt", "abcdefg");
  222. lab1Task1.Decrypt ("/Users/Alexander/Projects/Lab1IT/Lab1IT/files/encoded.txt", "/Users/Alexander/Projects/Lab1IT/Lab1IT/files/decoded.txt", "abcdefg");
  223. Lab1Task2 lab1Task2 = new Lab1Task2 ();
  224. lab1Task2.SearchLGrams ("/Users/Alexander/Projects/Lab1IT/Lab1IT/files/encoded.txt");
  225. }
  226. }
  227. }

Решение задачи: «Взломать шифр Виженера методом частотного анализа»

textual
Листинг программы
  1.         for (int j = 0; j < (message.Length / keyLength)+1; j++)
  2.                     if (dict.ContainsKey(strings[j,i]))
  3.                         dict[strings[j,i]]++;
  4.                     else
  5.                         dict.Add(strings[j,i], 1);

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


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

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

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

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

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

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