public static string Decyphering(string closedMessageBlockDuoSS, string key)
        {
            int[]         blocksBeforeInputWhiting  = new int[4];
            Int32[]       blocksBeforeOutputWhiting = new Int32[4];
            List <string> openMessage = new List <string>();
            var           subkeysArr  = SubkeysGen.SubKeysGeneration(key);
            var           XDataBlocks = StringMethods.StringToList(closedMessageBlockDuoSS, XBlockLength);

            for (int i = 0; i < 4; i++)
            {
                blocksBeforeOutputWhiting[i] = Convert.ToInt32(XDataBlocks[i], 2) ^ Convert.ToInt32(subkeysArr[i + 36], 2);
            }
            for (int round = 15; round > -1; round--)
            {
                blocksBeforeOutputWhiting = OneRoundReverse(blocksBeforeOutputWhiting, subkeysArr, round);
            }
            for (int i = 0; i < 4; i++)
            {
                blocksBeforeInputWhiting[i] = blocksBeforeOutputWhiting[i] ^ Convert.ToInt32(subkeysArr[i], 2);
                openMessage.Add(StringMethods.MyConvertToString(blocksBeforeInputWhiting[i], 2, 32));
            }
            var resultStringDuoSS = StringMethods.ListToString(openMessage);

            return(resultStringDuoSS);
        }
        public static string Cyphering(string openMessageBlockDuoSS, string key)
        {
            int []        blocksAfterInputWhiting  = new int [4];
            int []        blocksAfterOutputWhiting = new int [4];
            List <string> closedMessage            = new List <string>();
            var           subkeysArr  = SubkeysGen.SubKeysGeneration(key);
            var           XDataBlocks = StringMethods.StringToList(openMessageBlockDuoSS, XBlockLength);

            for (int i = 0; i < 4; i++)
            {
                blocksAfterInputWhiting[i] = Convert.ToInt32(XDataBlocks[i], 2) ^ Convert.ToInt32(subkeysArr[i], 2);
            }

            for (int round = 0; round < 16; round++)
            {
                blocksAfterInputWhiting = OneRound(blocksAfterInputWhiting, subkeysArr, round);
            }

            for (int i = 0; i < 4; i++)
            {
                blocksAfterOutputWhiting[i] = blocksAfterInputWhiting[i] ^ Convert.ToInt32(subkeysArr[i + 36], 2);
                closedMessage.Add(StringMethods.MyConvertToString(blocksAfterOutputWhiting[i], 2, 32));
            }
            var resultStringDuoSS = StringMethods.ListToString(closedMessage);

            return(resultStringDuoSS);
        }
        public static int[] OneRoundReverse(int[] blocksArray, List <string> subKeys, int roundNum)
        {
            int[] roundResult = new int[4];
            int   shiftedD    = blocksArray[3];

            for (int i = 0; i < 8; i++)
            {
                shiftedD = Convert.ToInt32(MyMath.LeftCycleShift(StringMethods.MyConvertToString(shiftedD, 2, 32)), 2);
            }
            var blockCafterG = GFunction(StringMethods.MyConvertToString(blocksArray[2], 2, 32));
            var blockDafterG = GFunction(StringMethods.MyConvertToString(shiftedD, 2, 32));
            var blockCandD   = (Convert.ToInt32(blockCafterG, 2) + Convert.ToInt32(blockDafterG, 2)) % Math.Pow(2, 32);
            var CPlusKey     = blockCandD + Convert.ToInt32(subKeys.ElementAt(2 * roundNum + 8), 2);
            var DPlusKey     = blockCandD + Convert.ToInt32(subKeys.ElementAt(2 * roundNum + 9), 2);

            blocksArray[0] = Convert.ToInt32(MyMath.LeftCycleShift(StringMethods.MyConvertToString(blocksArray[0], 2, 32)), 2);
            blocksArray[1] = blocksArray[1] ^ (int)DPlusKey;
            blocksArray[1] = Convert.ToInt32(MyMath.RightCycleShift(StringMethods.MyConvertToString(blocksArray[1], 2, 32)), 2);
            blocksArray[0] = blocksArray[0] ^ (int)CPlusKey;
            roundResult[0] = blocksArray[2];
            roundResult[1] = blocksArray[3];
            roundResult[2] = blocksArray[0];
            roundResult[3] = blocksArray[1];

            return(roundResult);
        }
        public static int[] OneRound(int [] blocksArray, List <string> subKeys, int roundNum)
        {
            int [] roundResult = new int [4];
            var    stringB     = StringMethods.MyConvertToString(blocksArray[1], 2, 32);

            for (int i = 0; i < 8; i++)
            {
                stringB = MyMath.LeftCycleShift(stringB);
            }
            int shiftedB     = Convert.ToInt32(stringB, 2);
            var blockAafterG = GFunction(StringMethods.MyConvertToString(blocksArray[0], 2, 32));
            var blockBafterG = GFunction(StringMethods.MyConvertToString(shiftedB, 2, 32));
            var blockAandB   = (Convert.ToInt32(blockAafterG, 2) + Convert.ToInt32(blockBafterG, 2)) % Math.Pow(2, 32);
            var APlusKey     = blockAandB + Convert.ToInt32(subKeys.ElementAt(2 * roundNum + 8), 2);
            var BPlusKey     = blockAandB + Convert.ToInt32(subKeys.ElementAt(2 * roundNum + 9), 2);

            blocksArray[2] = blocksArray[2] ^ (int)APlusKey;
            blocksArray[3] = Convert.ToInt32(MyMath.LeftCycleShift(StringMethods.MyConvertToString(blocksArray[3], 2, 32)), 2);
            blocksArray[3] = blocksArray[3] ^ (int)BPlusKey;
            blocksArray[2] = Convert.ToInt32(MyMath.RightCycleShift(StringMethods.MyConvertToString(blocksArray[2], 2, 32)), 2);
            roundResult[0] = blocksArray[2];
            roundResult[1] = blocksArray[3];
            roundResult[2] = blocksArray[0];
            roundResult[3] = blocksArray[1];

            return(roundResult);
        }
        public static int[] OneRoundLog(int[] blocksArray, List <string> subKeys, int roundNum, string fileWay)
        {
            StringBuilder strBuild = new StringBuilder();

            string[] blocksName  = { "A", "B", "C", "D" };
            int[]    roundResult = new int[4];
            strBuild.AppendLine();
            strBuild.AppendLine($"-------------------------------Round{roundNum}------------------------------");
            strBuild.AppendLine($"Input blocks: [{blocksName[0]}]: {StringMethods.MyConvertToString(blocksArray[0], 2, 32)};");
            for (int i = 1; i < 4; i++)
            {
                strBuild.AppendLine($"              [{blocksName[i]}]: {StringMethods.MyConvertToString(blocksArray[i], 2, 32)};");
            }
            var stringB = StringMethods.MyConvertToString(blocksArray[1], 2, 32);

            for (int i = 0; i < 8; i++)
            {
                stringB = MyMath.LeftCycleShift(stringB);
            }
            strBuild.AppendLine($"Содержимое субблока B циклически сдвигается влево на 8 бит: [{blocksName[1]}]= {stringB};");
            int shiftedB     = Convert.ToInt32(stringB, 2);
            var blockAafterG = TwofishAlgo.GFunction(StringMethods.MyConvertToString(blocksArray[0], 2, 32));

            strBuild.AppendLine($"Субблок A обрабатывается операцией g(): [{blocksName[0]}]= {blockAafterG};");
            var blockBafterG = TwofishAlgo.GFunction(StringMethods.MyConvertToString(shiftedB, 2, 32));

            strBuild.AppendLine($"Субблок B также обрабатывается операцией g(): [{blocksName[1]}]= {blockBafterG};");
            var blockAandB = (Convert.ToInt32(blockAafterG, 2) + Convert.ToInt32(blockBafterG, 2)) % Math.Pow(2, 32);

            strBuild.AppendLine($"Субблок B накладывается на A с помощью сложения по модулю 232,\n после чего аналогичным образом выполняется наложение субблока A на субблок B: [{blocksName[0]}]= [{blocksName[1]}]= {StringMethods.MyConvertToString((int)blockAandB,2,32)};");
            var APlusKey = blockAandB + Convert.ToInt32(subKeys.ElementAt(2 * roundNum + 8), 2);

            strBuild.AppendLine($"Фрагмент расширенного ключа K2r+8 (где r — номер текущего раунда, начиная с 0) складывается с субблоком A по модулю 232: [{blocksName[0]}] = {StringMethods.MyConvertToString((int)APlusKey, 2, 32)};");
            var BPlusKey = blockAandB + Convert.ToInt32(subKeys.ElementAt(2 * roundNum + 9), 2);

            strBuild.AppendLine($"Аналогично предыдущему шагу, K2r+9 накладывается на субблок B: [{blocksName[1]}] = {StringMethods.MyConvertToString((int)BPlusKey, 2, 32)};");
            blocksArray[2] = blocksArray[2] ^ (int)APlusKey;
            strBuild.AppendLine($"Субблок A накладывается на C операцией XOR: [{blocksName[2]}] = {StringMethods.MyConvertToString(blocksArray[2], 2, 32)};");
            blocksArray[3] = Convert.ToInt32(MyMath.LeftCycleShift(StringMethods.MyConvertToString(blocksArray[3], 2, 32)), 2);
            strBuild.AppendLine($"Содержимое субблока D циклически сдвигается влево на 1 бит: [{blocksName[3]}] = {StringMethods.MyConvertToString(blocksArray[3], 2, 32)};");
            blocksArray[3] = blocksArray[3] ^ (int)BPlusKey;
            strBuild.AppendLine($"Субблок B накладывается на D операцией XOR: [{blocksName[3]}] = {StringMethods.MyConvertToString(blocksArray[3], 2, 32)};");
            blocksArray[2] = Convert.ToInt32(MyMath.RightCycleShift(StringMethods.MyConvertToString(blocksArray[2], 2, 32)), 2);
            strBuild.AppendLine($"Содержимое субблока C циклически сдвигается вправо на 1 бит: [{blocksName[2]}] = {StringMethods.MyConvertToString(blocksArray[2], 2, 32)};");
            roundResult[0] = blocksArray[2];
            roundResult[1] = blocksArray[3];
            roundResult[2] = blocksArray[0];
            roundResult[3] = blocksArray[1];
            strBuild.AppendLine($"Output blocks: [{blocksName[0]}]: {StringMethods.MyConvertToString(roundResult[0], 2, 32)};");
            for (int i = 1; i < 4; i++)
            {
                strBuild.AppendLine($"              [{blocksName[i]}]: {StringMethods.MyConvertToString(roundResult[i], 2, 32)};");
            }

            File.AppendAllText(fileWay, strBuild.ToString());
            return(roundResult);
        }
Beispiel #6
0
        public static string ConvertTextToBinString(string textMessage)
        {
            var    bytesData      = Encoding.Default.GetBytes(textMessage);
            string openMessageBin = "";

            for (int i = 0; i < bytesData.Length; i++)
            {
                openMessageBin += (StringMethods.MyConvertToString(Convert.ToInt32(bytesData[i]), 2, 8));
            }
            return(openMessageBin);
        }
        public static void LogEncrypt(string key, string openMes, string fileWay)
        {
            StringBuilder strBuild = new StringBuilder();

            int[]         blocksAfterInputWhiting  = new int[4];
            int[]         blocksAfterOutputWhiting = new int[4];
            List <string> closedMessage            = new List <string>();
            var           subkeysArr = SubkeysGen.SubKeysGeneration(key);

            strBuild.AppendLine($"Open message block: {openMes};");
            strBuild.AppendLine($"Key({key.Length.ToString()}): {key};");
            strBuild.AppendLine($"RoundKeys: {subkeysArr[0]};");
            for (int i = 1; i < 40; i++)
            {
                strBuild.AppendLine($"           {subkeysArr[i]};");
            }
            var XDataBlocks = StringMethods.StringToList(openMes, TwofishAlgo.XBlockLength);

            strBuild.AppendLine();
            strBuild.AppendLine($"**************************Input Whiting**************************");
            strBuild.AppendLine();

            for (int i = 0; i < 4; i++)
            {
                blocksAfterInputWhiting[i] = Convert.ToInt32(XDataBlocks[i], 2) ^ Convert.ToInt32(subkeysArr[i], 2);
                strBuild.AppendLine($"{XDataBlocks[i]} xor {subkeysArr[i]} = {StringMethods.MyConvertToString(blocksAfterInputWhiting[i], 2, 32)};");
            }
            strBuild.AppendLine();
            strBuild.AppendLine($"**************************The Main Cycle**************************");
            File.AppendAllText(fileWay, strBuild.ToString());

            for (int round = 0; round < 16; round++)
            {
                blocksAfterInputWhiting = OneRoundLog(blocksAfterInputWhiting, subkeysArr, round, fileWay);
            }
            strBuild.AppendLine();
            strBuild.AppendLine($"**************************Output Whiting**************************");
            strBuild.AppendLine();

            for (int i = 0; i < 4; i++)
            {
                blocksAfterOutputWhiting[i] = blocksAfterInputWhiting[i] ^ Convert.ToInt32(subkeysArr[i + 36], 2);
                closedMessage.Add(StringMethods.MyConvertToString(blocksAfterOutputWhiting[i], 2, 32));
                strBuild.AppendLine($"{StringMethods.MyConvertToString(blocksAfterInputWhiting[i], 2, 32)} xor {subkeysArr[i+36]} = {StringMethods.MyConvertToString(blocksAfterOutputWhiting[i], 2, 32)};");
            }
            var resultStringDuoSS = StringMethods.ListToString(closedMessage);

            strBuild.AppendLine($"Closed message block: {resultStringDuoSS};");
        }
        public static string GFunction(string dataBlock32)
        {
            int[,] matrixAfterQ = new int[1, 4];
            //int[,] resultArrayStep5 = new int[1, 4];
            string block32BitAfterQ = "";
            var    eightBitBlocks   = StringMethods.StringToList(dataBlock32, 8);
            int    blockNum         = 0;
            string gResult          = "";

            foreach (string subWord in eightBitBlocks)
            {
                int y         = 0;
                var a0        = Convert.ToInt32(subWord, 2) / 16;
                var b0        = Convert.ToInt32(subWord, 2) % 16;
                var a1        = a0 ^ b0;
                var b0Nibbles = StringMethods.StringToList(StringMethods.MyConvertToString(b0, 2, 8), SubkeysGen.NibbleLength);
                foreach (string nibble in b0Nibbles)
                {
                    MyMath.RightCycleShift(nibble);
                }
                var b1 = (a0 ^ Convert.ToInt32(StringMethods.ListToString(b0Nibbles), 2) ^ (8 * a0)) % 16;
                if (SubkeysGen.qOperationMatrix[4, blockNum] == 0)
                {
                    var a2        = Convert.ToInt32(SubkeysGen.tItoeForQ0[0, a1], 16);
                    var b2        = Convert.ToInt32(SubkeysGen.tItoeForQ0[1, b1], 16);
                    var a3        = a2 ^ b2;
                    var b2Nibbles = StringMethods.StringToList(StringMethods.MyConvertToString(b2, 2, 8), SubkeysGen.NibbleLength);
                    foreach (string nibble in b2Nibbles)
                    {
                        MyMath.RightCycleShift(nibble);
                    }
                    var b3 = (a2 ^ Convert.ToInt32(StringMethods.ListToString(b2Nibbles), 2) ^ (8 * a2)) % 16;
                    var a4 = Convert.ToInt32(SubkeysGen.tItoeForQ0[2, a3], 16);
                    var b4 = Convert.ToInt32(SubkeysGen.tItoeForQ0[3, b3], 16);
                    y = 16 * a4 + b4;
                }
                else
                {
                    var a2        = Convert.ToInt32(SubkeysGen.tItoeForQ1[0, a1], 16);
                    var b2        = Convert.ToInt32(SubkeysGen.tItoeForQ1[1, b1], 16);
                    var a3        = a2 ^ b2;
                    var b2Nibbles = StringMethods.StringToList(StringMethods.MyConvertToString(b2, 2, 8), SubkeysGen.NibbleLength);
                    foreach (string nibble in b2Nibbles)
                    {
                        MyMath.RightCycleShift(nibble);
                    }
                    var b3 = (a2 ^ Convert.ToInt32(StringMethods.ListToString(b2Nibbles), 2) ^ (8 * a2)) % 16;
                    var a4 = Convert.ToInt32(SubkeysGen.tItoeForQ1[2, a3], 16);
                    var b4 = Convert.ToInt32(SubkeysGen.tItoeForQ1[3, b3], 16);
                    y = 16 * a4 + b4;
                }
                block32BitAfterQ += StringMethods.MyConvertToString(y, 2, 32);
                blockNum++;
            }
            var arrayAfterQ = StringMethods.StringToList(block32BitAfterQ, 8);

            for (int k = 0; k < 4; k++)
            {
                matrixAfterQ[0, k] = Convert.ToInt32(arrayAfterQ.ElementAt(k), 2);
            }

            //resultArrayStep5 = MyMath.MatrixMultiplication(SubkeysGen.M1Matrix, matrixAfterQ);

            for (int j = 0; j < 4; j++)
            {
                gResult += StringMethods.MyConvertToString(matrixAfterQ[0, j], 2, 8);
            }

            return(gResult);
        }
        public static List <string> SubKeysGeneration(string key)
        {
            if (key.Length < 128)
            {
                while (key.Length != 128)
                {
                    key = key.Insert(0, "0");
                }
            }
            else if (key.Length < 192)
            {
                while (key.Length != 192)
                {
                    key = key.Insert(0, "0");
                }
            }
            else if (key.Length < 256)
            {
                while (key.Length != 256)
                {
                    key = key.Insert(0, "0");
                }
            }

            var forCalculations  = key.Length / 64;
            var bigMKeyBlocks    = StringMethods.StringToList(key, XBlockLength);
            var lilMKeyBlocksBin = StringMethods.StringToList(key, byteLength);

            int[]         arrayV  = new int[forCalculations];
            List <string> arrayMe = new List <string>();
            List <string> arrayMo = new List <string> ();

            int[,] lilMKeyBlocksMatrix = new int[8, 1];
            List <string> subkeys = new List <string>();

            for (int i = 0; i < forCalculations; i++)
            {
                for (int k = 0; k < 8; k++)
                {
                    lilMKeyBlocksMatrix[k, 0] = Convert.ToInt32(lilMKeyBlocksBin[i * 8 + k], 2);
                }

                var promezhutoch = MyMath.MatrixMultiplication(M2Matrix, lilMKeyBlocksMatrix);
                int vItoe        = 0;
                for (int j = 0; j < 4; j++)
                {
                    vItoe += (int)(promezhutoch[j, 0]);
                }
                arrayV[forCalculations - i - 1] = vItoe;//можно объединить с фором выше
                arrayMe.Add(bigMKeyBlocks[2 * i]);
                arrayMo.Add(bigMKeyBlocks[2 * i + 1]);
            }

            for (int i = 0; i < 40; i++)
            {
                var AItoe = HFunction(StringMethods.MyConvertToString((int)(2 * i * p), 2, 32), arrayMe, forCalculations);
                var BItoe = StringMethods.MyConvertToString(HFunction(StringMethods.MyConvertToString((int)((2 * i + 1) * p), 2, 32), arrayMo, forCalculations), 2, 32);
                for (int j = 0; j < 8; j++)
                {
                    BItoe = MyMath.LeftCycleShift(BItoe);
                }

                if ((i % 2) == 0)
                {
                    var subkeyI = StringMethods.MyConvertToString((int)(AItoe + Convert.ToInt32(BItoe, 2) % Math.Pow(2, 32)), 2, 32);
                    subkeys.Add(subkeyI);
                }
                else
                {
                    var subkeyI = StringMethods.MyConvertToString((int)(AItoe + Convert.ToInt32(BItoe, 2) * 2 % Math.Pow(2, 32)), 2, 32);
                    for (int j = 0; j < 9; j++)
                    {
                        subkeyI = MyMath.LeftCycleShift(subkeyI);
                    }
                    subkeys.Add(subkeyI);
                }
            }

            return(subkeys);
        }
        public static int HFunction(string word32BitDuoSS, List <string> arrayForCalculations, int kNumber)
        {
            int[,] matrixStep5 = new int[1, 4];
            //int[,] resultArrayStep5 = new int[1, 4];

            while (word32BitDuoSS.Length != 32)
            {
                word32BitDuoSS = word32BitDuoSS.Insert(0, "0");
            }
            string stepResult = word32BitDuoSS;

            int stepNum = 2;

            if (kNumber >= 2)
            {
                if (kNumber > 2)
                {
                    stepNum -= 1;
                    if (kNumber > 3)
                    {
                        stepNum -= 1;
                    }
                }
            }
            for (int i = stepNum; i < 5; i++)
            {
                string block32BitAfterQ = "";
                var    subWords8Bit     = StringMethods.StringToList(stepResult, byteLength);
                int    flag             = 0;
                foreach (string subWord in subWords8Bit)
                {
                    int y         = 0;
                    var a0        = Convert.ToInt32(subWord, 2) / 16;
                    var b0        = Convert.ToInt32(subWord, 2) % 16;
                    var a1        = a0 ^ b0;
                    var test      = StringMethods.MyConvertToString(b0, 2, 8);
                    var b0Nibbles = StringMethods.StringToList(StringMethods.MyConvertToString(b0, 2, 8), NibbleLength);
                    foreach (string nibble in b0Nibbles)
                    {
                        MyMath.RightCycleShift(nibble);
                    }
                    var b1 = (a0 ^ Convert.ToInt32(StringMethods.ListToString(b0Nibbles), 2) ^ (8 * a0)) % 16;
                    if (qOperationMatrix[stepNum, flag] == 0)
                    {
                        var a2        = Convert.ToInt32(tItoeForQ0[0, a1], 16);
                        var b2        = Convert.ToInt32(tItoeForQ0[1, b1], 16);
                        var a3        = a2 ^ b2;
                        var b2Nibbles = StringMethods.StringToList(StringMethods.MyConvertToString(b2, 2, 8), NibbleLength);
                        foreach (string nibble in b2Nibbles)
                        {
                            MyMath.RightCycleShift(nibble);
                        }
                        var b3 = (a2 ^ Convert.ToInt32(StringMethods.ListToString(b2Nibbles), 2) ^ (8 * a2)) % 16;
                        var a4 = Convert.ToInt32(tItoeForQ0[2, a3], 16);
                        var b4 = Convert.ToInt32(tItoeForQ0[3, b3], 16);
                        y = 16 * a4 + b4;
                    }
                    else
                    {
                        var a2        = Convert.ToInt32(tItoeForQ1[0, a1], 16);
                        var b2        = Convert.ToInt32(tItoeForQ1[1, b1], 16);
                        var a3        = a2 ^ b2;
                        var b2Nibbles = StringMethods.StringToList(StringMethods.MyConvertToString(b2, 2, 8), NibbleLength);
                        foreach (string nibble in b2Nibbles)
                        {
                            MyMath.RightCycleShift(nibble);
                        }
                        var b3 = (a2 ^ Convert.ToInt32(StringMethods.ListToString(b2Nibbles), 2) ^ (8 * a2)) % 16;
                        var a4 = Convert.ToInt32(tItoeForQ1[2, a3], 16);
                        var b4 = Convert.ToInt32(tItoeForQ1[3, b3], 16);
                        y = 16 * a4 + b4;
                    }
                    block32BitAfterQ += StringMethods.MyConvertToString(y, 2, 8);
                    flag++;
                }

                if (i != 4)
                {
                    stepResult = StringMethods.MyConvertToString(Convert.ToInt32(block32BitAfterQ, 2) ^ Convert.ToInt32(arrayForCalculations[3 - i], 2), 2, 32);
                }
                else
                {
                    var arrayAfterQ = StringMethods.StringToList(block32BitAfterQ, 8);
                    for (int k = 0; k < 4; k++)
                    {
                        matrixStep5[0, k] = Convert.ToInt32(arrayAfterQ[k], 2);
                    }
                    //resultArrayStep5 = MyMath.MatrixMultiplication(M1Matrix, matrixStep5);
                }
            }
            int hResult = 0;

            for (int j = 0; j < 3; j++)
            {
                hResult += (int)(matrixStep5[0, j]);
            }

            return(hResult);
        }