コード例 #1
0
        //For SBoxes Transformation
        private string DoPermutation(string text, int[,] order)
        {
            int rowIndex = ToInt32(text[0].ToString() + text[text.Length - 1].ToString(), 2);
            int colIndex = ToInt32(text.Substring(1, 4), 2);

            return(Converts.FromDecimalToBinary(order[rowIndex, colIndex]));
        }
コード例 #2
0
        private string MainAlgorithm(bool isEncode, string text, string key, bool IsTextBinary)
        {
            var hexKey    = Converts.FromTextToHex(key);
            var binaryKey = Converts.FromHexToBinary(hexKey);
            var keyPlus   = DoPermutation(binaryKey, Rearranging.KeyPosition);
            var C0        = TextHelper.SetLeftHalvesKey(keyPlus);
            var D0        = TextHelper.SetRightHalvesKey(keyPlus);
            var keys      = SetAllKeys(C0, D0);


            var binaryText = !IsTextBinary?Converts.FromTextToBinary(text) : text;

            binaryText = TextHelper.setTextMutipleOf64Bits(binaryText);

            var cipherTextBuilder = new StringBuilder(binaryText.Length);

            for (int i = 0; i < (binaryText.Length / LENGTH_OF_DES_BLOCKS); i++)
            {
                var permutatedText = DoPermutation(
                    binaryText.Substring(i * LENGTH_OF_DES_BLOCKS, LENGTH_OF_DES_BLOCKS),
                    Rearranging.FirstChangingIP);
                var L0        = TextHelper.SetLeftHalvesKey(permutatedText);
                var R0        = TextHelper.SetRightHalvesKey(permutatedText);
                var finalText = FinalEncription(L0, R0, keys, !isEncode);

                if (!isEncode && LENGTH_OF_DES_BLOCKS * (i + 1) == binaryText.Length)
                {
                    var lastText = new StringBuilder(finalText.TrimEnd('0'));
                    var count    = finalText.Length - lastText.Length;

                    if ((count % 8) != 0)
                    {
                        count = 8 - (count % 8);
                    }

                    var appendText = string.Empty;
                    for (int k = 0; k < count; k++)
                    {
                        appendText += "0";
                    }

                    cipherTextBuilder.Append(lastText.ToString() + appendText);
                }
                else
                {
                    cipherTextBuilder.Append(finalText);
                }
            }

            return(Converts.FromBinaryToText(cipherTextBuilder.ToString()));
        }