вторник, 29 марта 2011 г.

шифр плейфера

using System;

namespace ConsoleApplication1
{
    class Program
    {
        //переменки
        static string Al = "ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯabcdefghijklmnopqrstuvwxyzабвгдеёжзийклмнопрстуфхцчшщъыьэюя !@\"#№$;%^:&?*()-_+={}[]\\/<>.,~`0123456789";
        static string MyText = "";        // введенный текст
        static string Key = "";        // введенный ключ
        static string R = "";        // полученная решетка
        static string ResText = "";        // полученный текст
        static char[,] Resh = new char[10, 16];        // массив букв решетки
        static string str = "";
        static int x = 0;

        static void Main(string[] args)
        {
            Console.WriteLine("Введите ключевое слово");
            Key = Console.ReadLine();//вводим ключ

            Clean_Key();//чистим ключ от повторов
            Make_Resh();//создаем решетку
            Print_Resh();//вывод решетки на экран

            Console.WriteLine("Введите текст для шифрования");
            MyText = Console.ReadLine();//вводим ключ


            //qbtp
            encrypt();
            Console.WriteLine("\nзашифрованное\n{0}", ResText);//снести
            decrypt();
            Console.WriteLine("\nрасшифрованное\n{0}", MyText);//снести

            //////////////////////////////////////////////////////////
            Console.ReadKey();
        }

        //****************************************************************************//
        //* Функция убирает повторяющиеся символы из ключевого слова                 *//
        //****************************************************************************//
        static void Clean_Key()
        {
            x = 0;
            do
            {
                if (Key[x] != (char)1)
                    Key = Key.Substring(0, x + 1) + Key.Substring(x + 1, Key.Length - x - 1).Replace(Key[x], (char)1);
                x++;
            } while (x != Key.Length);
            //убираем (char)1
            str = "";
            x = 0;
            do
            {
                if (Key[x] != (char)1)
                    str += Key[x];
                x++;
            } while (x != Key.Length);
            Key = str;
        }

        //****************************************************************************//
        //* Функция создает решетку                                                  *//
        //****************************************************************************//
        static void Make_Resh()
        {
            R = Key + Al;
            // полученная решетка
            for (int i = 0; i < Key.Length; i++)
                R = R.Substring(0, i + 1) + R.Substring(i + 1, R.Length - i - 1).Replace(R[i], (char)1);
            //убираем (char)1
            str = "";
            x = 0;
            do
            {
                if (R[x] != (char)1)
                    str += R[x];
                x++;
            } while (x != R.Length);
            // создали строку с решеткой
            R = str;
            // заполняем массив букв решетки
            int num = 0;
            // массив букв решетки
            for (int i = 0; i < 10; i++)//10
                for (int j = 0; j < 16; j++)//16
                {
                    Resh[i, j] = R[num];
                    num++;
                }
        }

        //****************************************************************************//
        //* Функция выводит решетку на экран                                         *//
        //****************************************************************************//
        static void Print_Resh()
        {
            Console.WriteLine("\nПолучившееся решетка");
            for (int i = 0; i < 10; i++)//10
            {
                for (int j = 0; j < 16; j++)//16
                    Console.Write("{0} ", Resh[i, j]);
                Console.WriteLine();
            }
            Console.WriteLine();
        }

        //****************************************************************************//
        //* Функция зашифровки                                                       *//
        //****************************************************************************//
        static void encrypt()
        {


            int i = 0;
            int j = 0;
            int[] pos1 = new int[2];
            int[] pos2 = new int[2];
            for (int k = 0; k < MyText.Length - 1; k = k + 2)
                if (MyText[k] == MyText[k + 1] /*&& MyText[k + 1] != 'й'*/)
                    MyText = MyText.Insert(k + 1, "й");

            //проверка на четность
            if (MyText.Length % 2 != 0)
                MyText += " ";

            Console.WriteLine("тест {0}", MyText);


            for (int k = 0; k < MyText.Length - 1; k = k + 2)
            {
                for (i = 0; i < 10; i++)
                {
                    for (j = 0; j < 16; j++)
                    {
                        if (Resh[i, j] == MyText[k]) { pos1[0] = i; pos1[1] = j; }
                        if (Resh[i, j] == MyText[k + 1]) { pos2[0] = i; pos2[1] = j; }
                    }
                }

                if (pos1[0] == pos2[0])
                {
                    if (pos1[1] < pos2[1])
                        ResText = ResText + Resh[pos1[0], (pos1[1] + 1) % 16] + Resh[pos2[0], (pos2[1] + 1) % 16];
                    else if (pos1[1] > pos2[1])
                        ResText = ResText + Resh[pos2[0], (pos1[1] + 1) % 16] + Resh[pos2[0], (pos2[1] + 1) % 16];
                }
                else if (pos1[1] == pos2[1])
                {
                    if (pos1[0] < pos2[0])
                        ResText = ResText + Resh[(pos1[0] + 1) % 10, pos2[1]] + Resh[(pos2[0] + 1) % 10, pos2[1]];
                    else if (pos1[0] > pos2[0])
                        ResText = ResText + Resh[(pos1[0] + 1) % 10, pos1[1]] + Resh[(pos2[0] + 1) % 10, pos1[1]];
                }
                else
                {
                    ResText = ResText + Resh[pos1[0], pos2[1]] + Resh[pos2[0], pos1[1]];
                }
            }
        }

        //****************************************************************************//
        //* Функция расшифровки                                                      *//
        //****************************************************************************//
        static void decrypt()
        {
            MyText = "";
            int i = 0;
            int j = 0;
            int[] pos1 = new int[2];
            int[] pos2 = new int[2];

            for (int k = 0; k < ResText.Length - 1; k += 2)
            {
                for (i = 0; i < 10; i++)
                {
                    for (j = 0; j < 16; j++)
                    {
                        if (Resh[i, j] == ResText[k]) { pos1[0] = i; pos1[1] = j; }
                        if (Resh[i, j] == ResText[k + 1]) { pos2[0] = i; pos2[1] = j; }
                    }
                }
                if (pos1[0] == pos2[0])
                {
                    if (pos1[1] < pos2[1])
                        MyText = MyText + Resh[pos1[0], (pos1[1] + 15) % 16] + Resh[pos2[0], (pos2[1] + 15) % 16];
                    else if (pos1[1] > pos2[1])
                        MyText = MyText + Resh[pos2[0], (pos1[1] + 15) % 16] + Resh[pos2[0], (pos2[1] + 15) % 16];
                }
                else if (pos1[1] == pos2[1])
                {
                    if (pos1[0] < pos2[0])
                        MyText = MyText + Resh[(pos1[0] + 9) % 10, pos2[1]] + Resh[(pos2[0] + 9) % 10, pos2[1]];
                    else if (pos1[0] > pos2[0])
                        MyText = MyText + Resh[(pos1[0] + 9) % 10, pos1[1]] + Resh[(pos2[0] + 9) % 10, pos1[1]];
                }
                else
                    MyText = MyText + Resh[pos1[0], pos2[1]] + Resh[pos2[0], pos1[1]];
            }
            for (int k = 1; k < MyText.Length - 1;k++ )
                if (MyText[k - 1] == MyText[k + 1] && MyText[k]=='й')
                    MyText = MyText.Remove(k,1);
            
                if (MyText[MyText.Length - 1] == ' ')
                    MyText = MyText.Substring(0, MyText.Length - 1);
        }
        /////////////////////////
    }
}

Комментариев нет: