예제 #1
0
        public string breakSubstitutionCipher(string cipherText)
        {
            //current
            int    count    = 0;
            string maxKey   = SubstitutionCipher.getAlphabet();
            double maxScore = -99e9;

            string parentKey   = maxKey;
            double parentScore = maxScore;

            DateTime start = DateTime.Now;

            while (DateTime.Now.Subtract(start).Seconds <= timeout)
            {
                count++;
                parentKey   = sb.generateNewKey();
                parentScore = getTextNgramFitness(sb.decode(cipherText, parentKey));

                for (int i = 0; i < 1000; i++)//i => iterations since last improvement. If > 1000, we are at local maximum
                {
                    string childKey   = sb.swapTwoChars(parentKey);
                    double childScore = getTextNgramFitness(sb.decode(cipherText, childKey));

                    if (childScore > parentScore)
                    {
                        parentScore = childScore;
                        parentKey   = childKey;
                        i           = 0;//made an improvement, reset counter
                    }
                }

                if (parentScore > maxScore)
                {
                    maxScore = parentScore;
                    maxKey   = parentKey;

                    Console.WriteLine("\nBest score so far: " + maxScore + " on iteration " + count);
                    Console.WriteLine("     Best key: " + maxKey);
                    Console.WriteLine("     Best Plaintext: " + sb.decode(cipherText, maxKey));
                }
            }

            return(maxKey);
        }
예제 #2
0
        static void Main(string[] args)
        {
            SubstitutionCipher sb        = new SubstitutionCipher();
            string             plainText = "The most merciful thing in the world, I think, is the inability of the human mind to correlate all its contents. We live on a placid island of ignorance in the midst of black seas of infinity, and it was not meant that we should voyage far. The sciences, each straining in its own direction, have hitherto harmed us little; but some day the piecing together of dissociated knowledge will open up such terrifying vistas of reality, and of our frightful position therein, that we shall either go mad from the revelation or flee from the light into the peace and safety of a new dark age.";

            plainText = plainText.Replace('’', '\'').Replace('‘', '\'');
            string key        = sb.generateNewShiftKey(10);
            string cipherText = sb.encode(plainText, key);
            string newPlain   = sb.decode(cipherText, key);

            Console.WriteLine("Key: " + key + "\nCipher: " + cipherText);
            Analysis analysis = new Analysis(4);

            analysis.breakSubstitutionCipher(cipherText);
        }