public void Execute()
        {
            this.genAttacker  = new GeneticAttacker();
            this.dicAttacker  = new DictionaryAttacker();
            this.hillAttacker = new HillclimbingAttacker();

            Boolean inputOK = true;

            // Clear presentation
            ((AssignmentPresentation)Presentation).Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
            {
                try
                {
                    ((AssignmentPresentation)Presentation).Entries.Clear();
                }
                catch (Exception ex)
                {
                    GuiLogMessage("Exception while clearing entries list:" + ex.Message, NotificationLevel.Error);
                }
            }, null);

            // Prepare the cryptanalysis of the ciphertext
            ciphertext = ciphertext.ToLower();

            // Set alphabets
            string lang = LanguageStatistics.LanguageCode(settings.Language);

            grams = new Tetragrams(lang, settings.UseSpaces);

            plaintextalphabet  = grams.Alphabet;
            ciphertextalphabet = String.IsNullOrEmpty(CiphertextAlphabet)
                ? new string(Ciphertext.ToLower().Distinct().OrderBy(c => c).ToArray()).Replace("\r", "").Replace("\n", "")
                : new string(CiphertextAlphabet.ToLower().Distinct().OrderBy(c => c).ToArray()).Replace("\r", "").Replace("\n", "");

            if (ciphertextalphabet[0] == ' ')
            {
                ciphertextalphabet = ciphertextalphabet.Trim() + " ";
            }

            ptAlphabet = new Alphabet(plaintextalphabet);
            ctAlphabet = new Alphabet(ciphertextalphabet);

            if (settings.ChooseAlgorithm == 1)
            {
                ciphertext         = ciphertext.ToLower();
                plaintextalphabet  = plaintextalphabet.ToLower();
                ciphertextalphabet = plaintextalphabet;

                ptAlphabet = new Alphabet(plaintextalphabet);
                ctAlphabet = new Alphabet(ciphertextalphabet);

                // Dictionary
                try
                {
                    langDic = new Dictionary(LanguageStatistics.LanguageCode(settings.Language) + "-small.dic", plaintextalphabet.Length);
                }
                catch (Exception ex)
                {
                    GuiLogMessage(Resources.error_dictionary + ": " + ex.Message, NotificationLevel.Error);
                }
                // Dictionary correct?
                if (this.langDic == null)
                {
                    GuiLogMessage(Resources.no_dictionary, NotificationLevel.Warning);
                }
            }

            // Plaintext Alphabet
            this.plaintextalphabetoutput = plaintextalphabet;
            OnPropertyChanged("PlaintextAlphabetOutput");

            if (ciphertext != null)
            {
                this.cText = new Text(ciphertext.ToLower(), this.ctAlphabet, settings.TreatmentInvalidChars);
            }
            else
            {
                this.cText = null;
            }

            // PTAlphabet correct?
            if (this.ptAlphabet == null)
            {
                GuiLogMessage(Resources.no_plaintext_alphabet, NotificationLevel.Error);
                inputOK = false;
            }

            // CTAlphabet correct?
            if (this.ctAlphabet == null)
            {
                GuiLogMessage(Resources.no_ciphertext_alphabet, NotificationLevel.Error);
                inputOK = false;
            }

            // Ciphertext correct?
            if (this.cText == null)
            {
                GuiLogMessage(Resources.no_ciphertext, NotificationLevel.Error);
                inputOK = false;
            }

            // Check length of ciphertext and plaintext alphabet
            if (this.ctAlphabet.Length > this.ptAlphabet.Length)
            {
                //if ciphertext alphabet is too long, we fallback to the plaintext alphabet
                GuiLogMessage(String.Format(Resources.error_alphabet_length, ciphertextalphabet, ciphertextalphabet.Length, plaintextalphabet, plaintextalphabet.Length), NotificationLevel.Warning);
                ctAlphabet = ptAlphabet;
            }

            // If input incorrect return otherwise execute analysis
            lock (this.stopFlag)
            {
                if (this.stopFlag.Stop)
                {
                    return;
                }
            }

            if (!inputOK)
            {
                inputOK = true;
                return;
            }

            this.UpdateDisplayStart();

            //this.masPresentation.DisableGUI();
            this.masPresentation.UpdateOutputFromUserChoice = this.UpdateOutput;
            this.keyCandidates = new List <KeyCandidate>();

            /* Algorithm:
             * 0 = Hillclimbing CPU
             * 1 = Genetic & Dictionary */
            if (settings.ChooseAlgorithm == 0)
            {
                AnalyzeHillclimbing(false);
                totalKeys = hillAttacker.TotalKeys;
            }
            else if (settings.ChooseAlgorithm == 1)
            {
                if (this.langDic != null)
                {
                    AnalyzeDictionary();
                }
                AnalyzeGenetic();
            }

            this.UpdateDisplayEnd();

            //set final plugin progress to 100%:
            OnPluginProgressChanged(this, new PluginProgressEventArgs(1.0, 1.0));
        }
Example #2
0
        public Text(string text, Alphabet alpha, int treatmentInvalidChars, bool caseSensitive = false)
        {
            this.invalidCharProcess = treatmentInvalidChars;
            this.caseSensitive      = caseSensitive;

            string curString = "";
            string c         = "";

            string prep_text = text;

            if (!this.caseSensitive)
            {
                for (int i = 0; i < prep_text.Length; i++)
                {
                    bool status = false;

                    int j = 0;
                    do
                    {
                        j++;
                        curString = prep_text.Substring(i, j);

                        c = curString;
                        if (char.IsUpper(c.ToCharArray()[0]))
                        {
                            status = true;
                            c      = c.ToLower();
                        }
                    }while (alpha.GetNumberOfLettersStartingWith(c) > 1);

                    if (alpha.GetNumberOfLettersStartingWith(c) == 1)
                    {
                        this.text.Add(alpha.GetPositionOfLetter(c));
                        this.orgCapital.Add(status);
                    }
                    else if (alpha.GetNumberOfLettersStartingWith(c) == 0)
                    {
                        this.notInAlphabet.Add(curString);
                        this.text.Add(-this.notInAlphabet.Count);
                        this.orgCapital.Add(false);
                    }
                    i += j - 1;
                }
            }
            else
            {
                for (int i = 0; i < prep_text.Length; i++)
                {
                    int j = 0;
                    do
                    {
                        j++;
                        curString = prep_text.Substring(i, j);
                        c         = curString;
                    }while (alpha.GetNumberOfLettersStartingWith(c) > 1);

                    if (alpha.GetNumberOfLettersStartingWith(c) == 1)
                    {
                        this.text.Add(alpha.GetPositionOfLetter(c));
                        this.orgCapital.Add(false);
                    }
                    else if (alpha.GetNumberOfLettersStartingWith(c) == 0)
                    {
                        this.notInAlphabet.Add(curString);
                        this.text.Add(-this.notInAlphabet.Count);
                        this.orgCapital.Add(false);
                    }
                    i += j - 1;
                }
            }
        }
Example #3
0
        private int[] CombineKeys(int[] p1, double fit_p1, int[] p2, double fit_p2, Text ciphertext, Alphabet ciphertext_alphabet)
        {
            int[]  res = new int[this.ciphertext_alphabet.Length];
            int[]  less_fit;
            double fitness;
            double new_fitness;
            Text   plaintext;

            if (fit_p1 > fit_p2)
            {
                p1.CopyTo(res, 0);
                less_fit = p2;
                fitness  = fit_p1;
            }
            else
            {
                p2.CopyTo(res, 0);
                less_fit = p1;
                fitness  = fit_p2;
            }

            int index = -1;

            for (int i = 0; i < res.Length; i++)
            {
                if (res[i] != less_fit[i])
                {
                    for (int j = 0; j < res.Length; j++)
                    {
                        if (res[j] == less_fit[i])
                        {
                            index = j;
                            break;
                        }
                    }
                    int helper = res[i];
                    res[i]      = res[index];
                    res[index]  = helper;
                    plaintext   = DecryptCiphertext(res, ciphertext, ciphertext_alphabet);
                    new_fitness = this.grams.CalculateCost(plaintext.ToIntArray());
                    if (fitness > new_fitness)
                    {
                        helper     = res[i];
                        res[i]     = res[index];
                        res[index] = helper;
                    }
                }
            }

            return(res);
        }
Example #4
0
        private int[] KeyCreatedByMatch(int[] key, Alphabet cipher_alpha, string ct_word, Alphabet plain_alpha, string dic_word)
        {
            int[] newkey = new int[key.Length];
            for (int i = 0; i < newkey.Length; i++)
            {
                newkey[i] = key[i];
            }
            int ct_index;
            int pt_index;

            for (int i = 0; i < ct_word.Length; i++)
            {
                ct_index = cipher_alpha.GetPositionOfLetter(ct_word.Substring(i, 1));
                pt_index = plain_alpha.GetPositionOfLetter(dic_word.Substring(i, 1));
                if ((!newkey.Contains(pt_index)) && (newkey[ct_index] == -1))
                {
                    newkey[ct_index] = pt_index;
                }

                if ((newkey[ct_index] != pt_index) && (newkey[ct_index] != -1))
                {
                    return(null);
                }
            }

            return(newkey);
        }
Example #5
0
        private Population CreateNextGeneration(Population pop, Text ciphertext, Alphabet cipher_alpha, bool last)
        {
            Population next = new Population();


            next.prob    = pop.prob;
            next.fitness = new double[pop.keys.Length];
            next.keys    = new int[pop.keys.Length][];

            // Create population_size x children through crossover and mutate children
            int p1;
            int p2;
            int i1;
            int i2;
            int size = pop.prob.Length;
            int helper3;

            for (int i = 0; i < next.keys.Length; i++)
            {
                i1 = GeneticAttacker.rnd.Next(size);
                i2 = GeneticAttacker.rnd.Next(size);
                p1 = pop.prob[i1];
                p2 = pop.prob[i2];

                next.keys[i] = CombineKeys(pop.keys[p1], pop.fitness[p1], pop.keys[p2], pop.fitness[p2], this.ciphertext, this.ciphertext_alphabet);

                if (!last)
                {
                    for (int j = 0; j < next.keys[i].Length; j++)
                    {
                        if (GeneticAttacker.rnd.Next(GeneticAttacker.mutateProbability) == 0)
                        {
                            p1               = GeneticAttacker.rnd.Next(next.keys[i].Length);
                            p2               = GeneticAttacker.rnd.Next(next.keys[i].Length);
                            helper3          = next.keys[i][p1];
                            next.keys[i][p1] = next.keys[i][p2];
                            next.keys[i][p2] = helper3;
                        }
                    }
                }
            }

            // Calculate fitness of population
            for (int i = 0; i < next.keys.Length; i++)
            {
                next.fitness[i] = this.grams.CalculateCost(DecryptCiphertext(next.keys[i], ciphertext, cipher_alpha).ToIntArray());
            }

            // Sort keys according to their fitness
            int[]  helper1;
            double helper2;

            for (int i = 0; i < next.keys.Length; i++)
            {
                for (int j = 0; j < next.keys.Length; j++)
                {
                    if (next.fitness[i] > next.fitness[j])
                    {
                        helper1         = next.keys[i];
                        next.keys[i]    = next.keys[j];
                        next.keys[j]    = helper1;
                        helper2         = next.fitness[i];
                        next.fitness[i] = next.fitness[j];
                        next.fitness[j] = helper2;
                    }
                }
            }

            // Calculate change in development
            next.dev             = Math.Abs(Math.Abs(next.fitness[0]) - Math.Abs(pop.fit_lastbestkey));
            next.fit_lastbestkey = next.fitness[0];

            return(next);
        }
Example #6
0
        private void CreateInitialGeneration(Population pop, Text ciphertext, Alphabet cipher_alpha, Alphabet plain_alpha)
        {
            // Create initial population keys
            int[] newkey;
            int   keylength = cipher_alpha.Length;

            // Create the other population keys at random
            for (int i = 0; i < pop.keys.Length; i++)
            {
                newkey = this.CreateInitialKeyRandom(keylength);
                while (this.banlist.Contains(newkey))
                {
                    newkey = this.CreateInitialKeyRandom(keylength);
                }
                this.banlist.Add(newkey);
                pop.keys[i] = newkey;
            }

            // Calculate fitness of population keys
            for (int i = 0; i < pop.keys.Length; i++)
            {
                pop.fitness[i] = this.grams.CalculateCost(DecryptCiphertext(pop.keys[i], ciphertext, cipher_alpha).ToIntArray());
            }

            // Sort keys according to their fitness
            int[]  helper1;
            double helper2;

            for (int i = 0; i < pop.keys.Length; i++)
            {
                for (int j = 0; j < pop.keys.Length; j++)
                {
                    if (pop.fitness[i] > pop.fitness[j])
                    {
                        helper1        = pop.keys[i];
                        pop.keys[i]    = pop.keys[j];
                        pop.keys[j]    = helper1;
                        helper2        = pop.fitness[i];
                        pop.fitness[i] = pop.fitness[j];
                        pop.fitness[j] = helper2;
                    }
                }
            }

            // Calculate change in development
            pop.fit_lastbestkey = pop.fitness[0];
            pop.dev             = Math.Abs(pop.fitness[0]);
        }