Exemplo n.º 1
0
        public static string Encrypt(string clearText, string key)
        {
            char[][] firstTable = new char[(int)Math.Ceiling((float)clearText.Length / key.Length + 1)][];

            for (int i = 0; i < firstTable.Length; i++)
            {
                firstTable[i] = new char[key.Length];
            }

            for (int j = 0; j < firstTable[0].Length; j++)
            {
                firstTable[0][j] = key[j];
            }

            for (int i = 1; i < firstTable.Length; i++)
            {
                for (int j = 0; j < firstTable[i].Length; j++)
                {
                    int tempId = (i - 1) * firstTable[i].Length + j;

                    if (tempId < clearText.Length)
                    {
                        firstTable[i][j] = clearText[tempId];
                    }
                    else
                    {
                        firstTable[i][j] = ' ';
                    }
                }
            }

            char[][] secondTable = new char[firstTable.Length][];
            int[]    shuffle     = LetterMap(key);

            for (int i = 0; i < firstTable.Length; i++)
            {
                secondTable[i] = new char[firstTable[i].Length];

                for (int j = 0; j < firstTable[i].Length; j++)
                {
                    secondTable[i][shuffle[j]] = firstTable[i][j];
                }
            }


            for (int i = 1; i < secondTable.Length; i++)
            {
                for (int j = 0; j < secondTable[i].Length; j++)
                {
                    if (secondTable[i][j] != ' ')
                    {
                        secondTable[i][j] = Vigenere.Encrypt(secondTable[i][j], secondTable[0][j]);
                    }
                }
            }

            string result = "";

            for (int multipleOfFive = 0;
                 multipleOfFive < (int)Math.Ceiling((float)secondTable.Length / 5);
                 multipleOfFive++)
            {
                for (int j = 0; j < secondTable[0].Length; j++)
                {
                    for (int i = 0; i < 5; i++)
                    {
                        int x = i + multipleOfFive * 5 + 1;
                        if (x < secondTable.Length &&
                            secondTable[x][j] != ' ')
                        {
                            result += secondTable[x][j];
                        }
                    }
                }
            }

            return(result);
        }