Взлом шифра "решётка Кардано" - C#
Формулировка задачи:
У меня шифр решетка Кардано без поворотов. Есть шифруемое слово(word), есть текст для шифрования(input). Слово шифруется правилом: ищется каждый символ слова word по первому вхождению(подчеркнул это верхним регистром) в input выдает на найденные буквы единицы, остальные ноли(так я получаю так называемый трафарет с вырезами). Это и есть ключ криптограммы из 0 и 1. Аналогично расшифровываю.
Как можно взломать данный шифр?
1) Для частотного анализа вроде как слишком мало букв для input; 2) Можно наверно как то пробивать по заранее созданному словарю все возможно составляемые слова, также по первому вхождению вырвать слова и смотреть на выходе осмысленный ли текст.Подскажите пожалуйста
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
public static string word = "приветбрат!";
public static string input = "ПеРгамент клеопатры Из египта отраВлЕн Токсином, Будь остоРожен с ним, цезАрь, Такова твоя учесть!";
static void Main(string[] args)
{
Console.WriteLine("Шифруемое слово: " + word + "\n");
Console.WriteLine("Криптограмма : " + input + "\n");
input = input.Replace(' ', '_');
input = input.ToLower();
Matrix();
Console.WriteLine("\nКриптограмма: " + input);
Console.WriteLine("\nКлюч : " + Crypt(word, input));
string key = Crypt(word, input);
Console.Write("\nДешифровка : ");
DeCrypt(input, key);
Console.ReadLine();
}
public static void Matrix()
{
Console.WriteLine("Матрица:");
int b = 0;
int c = input.Length / word.Length;
if (input.Length % word.Length != 0)
{
int d = input.Length % word.Length;
c++;
int f = word.Length - d;
input = input.PadRight(input.Length + f);
}
char[,] Matrix = new char[word.Length, c];
for (int j = 0; j < c; j++)
{
for (int i = 0; i < word.Length; i++)
{
Matrix[i, j] = input[b];
Console.Write("{0} ", Matrix[i, j]);
b++;
}
Console.WriteLine();
}
}
static string Crypt(string word, string input)
{
var sb = new StringBuilder();
int i = 0, j = 0;
for (; i < word.Length; i++)
{
for (; j < input.Length; j++)
{
if (word[i] == input[j])
{
sb.Append("1");
j++;
break;
}
sb.Append("0");
}
}
for (; j < input.Length; j++)
sb.Append("0");
return sb.ToString();
}
static void DeCrypt(string input, string key)
{
key = Crypt(word, input);
for (int i = 0; i < key.Length; i++)
{
if (Convert.ToString(key[i]) == "1")
{
Console.Write(input[i]);
}
}
}
}
}Решение задачи: «Взлом шифра "решётка Кардано"»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
namespace ConsoleApplication4
{
class Program
{
public static string word = "приветбрат!";
public static string input = "ПеРгамент клеопатры Из египта отраВлЕн Токсином, Будь остоРожен с ним, цезАрь, Такова твоя учесть!";
static void Main(string[] args)
{
Console.WriteLine("Шифруемое слово: " + word + "\n");
Console.WriteLine("Криптограмма: " + input + "\n");
input = input.Replace(' ', '_');
input = input.ToLower();
Matrix();
Console.WriteLine("\nКриптограмма: " + input);
Console.WriteLine("\nКлюч : " + Crypt(word, input));
string key = Crypt(word, input);
Console.Write("\nДешифровка : ");
DeCrypt(input, key);
Console.WriteLine("\n");
Analize(input);
Console.ReadLine();
}
public static void Matrix()
{
Console.WriteLine("Матрица:");
int b = 0;
int c = input.Length / word.Length;
if (input.Length % word.Length != 0)
{
int d = input.Length % word.Length;
c++;
int f = word.Length - d;
input = input.PadRight(input.Length + f);
}
char[,] Matrix = new char[word.Length, c];
for (int j = 0; j < c; j++)
{
for (int i = 0; i < word.Length; i++)
{
Matrix[i, j] = input[b];
Console.Write("{0} ", Matrix[i, j]);
b++;
}
Console.WriteLine();
}
}
static string Crypt(string word, string input)
{
var sb = new StringBuilder();
int i = 0, j = 0;
for (; i < word.Length; i++)
{
for (; j < input.Length; j++)
{
if (word[i] == input[j])
{
sb.Append("1");
j++;
break;
}
sb.Append("0");
}
}
for (; j < input.Length; j++)
sb.Append("0");
return sb.ToString();
}
static void DeCrypt(string input, string key)
{
key = Crypt(word, input);
for (int i = 0; i < key.Length; i++)
{
if (Convert.ToString(key[i]) == "1")
{
Console.Write(input[i]);
}
}
}
public static void Analize(string input)
{
Console.WriteLine("Частотный анализ, буквы криптограммы:");
SortedDictionary<char, double> dict = new SortedDictionary<char, double>();
for (int i = 0; i < input.Length; i++)
if (dict.ContainsKey(input[i]))
dict[input[i]]++;
else
dict.Add(input[i], 1);
var sortDict = dict.OrderByDescending(x => x.Value);
foreach (KeyValuePair<char, double> kvp in sortDict)
Console.WriteLine("Символ: {0}, вероятность {1:F3} раз.", kvp.Key, kvp.Value / input.Length);
Console.ReadLine();
}
}
}