Answer the question
In order to leave comments, you need to log in
Playfair cipher. Why is the index out of bounds?
Playfair encryption
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication6
{
class Program
{
static int t, x1, x2, y1, y2;
static string temp;
const int MaxX = 6;//столбцы
const int MaxY = 5;//строки
static string URusa = "абвгдежзиклмнопрстуфхцчшщъыэюя";
//string[] URusa2 = URusa.Split(',');
static char[,] array = new char[MaxY, MaxX];
public static void SimbolPoc(char s, out int x, out int y)
{
x = 0;
y = 0;
for (var i = 0; i < MaxY; i++)
{
for (var j = 0; j < MaxX; j++)
{
if (s == array[i, j])
{
x = j; y = i;
//Environment.Exit;
}
}
}
}
public static void Playfair_crypt(string s, string key)
{
key = key.ToLower();
s = s.ToLower();
//Удаляем из строки все символы, Не входящие в наш алфавит
temp = "";
for (var i = 0; i < s.Length; i++)
{
if (Convert.ToInt32(URusa.Contains(s[i])) != 0)
{
temp += s[i];
}
}
s = temp;
//Создание ключевой матрицы, с использованием ключевого слова "key".
temp = "";
for (var i = 0; i < key.Length; i++)
{
if (Convert.ToInt32(temp.Contains(key[i])) == 0) //!!!!!!!!!!!!!!!!!!!!!
temp += key[i];
}
for (var i = 0; i < URusa.Length; i++)
{
if (Convert.ToInt32(temp.Contains(URusa[i])) == 0) //!!!!!!!!!!!!!!!!!!!!!
temp += URusa[i];
}
t = 0;
for (var i = 0; i < MaxY; i++)
{
for (var j = 0; j < MaxX; j++)
{
array[i, j] = temp[t];
t++;
Console.Write("{0} ", array[i, j]);
}
Console.WriteLine();
}
//Console.WriteLine(s);
//просмотр строки по парам символов и вставка разделяющего символа
//"ъ" в случае когда в паре попались одинаковые символы.
for (var i = 0; i < s.Length / 2; i++)
{
if (s[2 * i] == s[2 * i + 1])
{
s = s.Insert(2 * i + 1, "ъ");
}
}
if (s.Length % 2 == 1)
{
if (s[s.Length - 1] != 'ъ')
s = s + 'ъ';
else
s = s + 'я';
}
//Console.WriteLine(s);
Console.WriteLine(s);
temp = "";
for (var i = 0; i < s.Length / 2; i++)
{
SimbolPoc(s[2 * i], out x1, out y1);
SimbolPoc(s[2 * i + 1], out x2, out y2);
//Console.WriteLine(x1);
//Правило1
if (y1 == y2)
{
x1++;
x2++;
if (x1 > MaxX) x1 = x1 - MaxX;
if (x2 > MaxX) x2 = x2 - MaxX;
temp = temp + array[y1, x1] + array[y2, x2];
}/*
//Правило2
if (x1 == x2)
{
y1++;
y2++;
if (y1 > MaxY) y1 = y1 - MaxY;
if (y2 > MaxY) y2 = y2 - MaxY;
temp = temp + array[y1, x1] + array[y2, x2];
}
//Правило3
if ((x1 != x2) && (y1 != y2)) temp = temp + array[y1, x2] + array[y2, x1];*/
}
Console.WriteLine(temp);
}
static void Main(string[] args)
{
Playfair_crypt("Россия", "Форум");
}
}
}
temp = temp + array[y1, x1] + array[y2, x2];
- out of bounds, until this step everything seems to be doing correctly. Accordingly, other rules are also commented out.
When we get to this line, and if we remove s = , we s = s.Insert(2 * i + 1, "ъ");
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question