source: trunk/CrypPlugins/Enigma/Enigma.cs @ 353

Last change on this file since 353 was 353, checked in by Arno Wacker, 13 years ago

Enigma: major update

  • Included double-stepping, hence the compatibility to a real Enigma should now be complete
  • Complete rewrite of basic code (old code is uncommented and just for archiving still there; will be removed with next check-in), leading to some speed-up. Improvement still possible.
  • Added a ciphertext-only crypt-analyzer to the plugin. The analyzer follows the algorithm given by James Gillogly in Cryptologia October 1995; Volume XIX, Number 4 (http://www.fortunecity.com/skyscraper/coding/379/gillog1.htm); activate the analyzer by choosing "Analyze" as operation mode.
  • The analyzer still uses only the index of coincidences as the cost function, unlike proposed by J. Gillogly. Improvement for plug-detection is expected when using a specific log-trigraph sum as the cost function.
  • Added four new samples for demostrating the plugin (encryption/decryption/cryptanalysis), including a short description inside the samples
  • The plugin is still work-in-progress and still missing some feature, e.g.
    • no description available yet
    • no quickwatch or presentation available
    • only the 3-rotor "Enigma I / M3" is currently supported, other models are prepared (can actually be selected in the settings) however, the implementation is not done for them, hence the plugin will quit with a controlled error-message.
    • The analyzer only uses one CPU core for the heavy work, i.e. it works strictly sequentially. Since the heavy work is searching through the rotor-space, it could be improved by searching the key space in parallel.
  • Property svn:eol-style set to CRLF
  • Property svn:keywords set to URL Author Date Rev Id
File size: 61.1 KB
Line 
1/*                              Apache License
2                           Version 2.0, January 2004
3                        http://www.apache.org/licenses/
4
5   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
7   1. Definitions.
8
9      "License" shall mean the terms and conditions for use, reproduction,
10      and distribution as defined by Sections 1 through 9 of this document.
11
12      "Licensor" shall mean the copyright owner or entity authorized by
13      the copyright owner that is granting the License.
14
15      "Legal Entity" shall mean the union of the acting entity and all
16      other entities that control, are controlled by, or are under common
17      control with that entity. For the purposes of this definition,
18      "control" means (i) the power, direct or indirect, to cause the
19      direction or management of such entity, whether by contract or
20      otherwise, or (ii) ownership of fifty percent (50%) or more of the
21      outstanding shares, or (iii) beneficial ownership of such entity.
22
23      "You" (or "Your") shall mean an individual or Legal Entity
24      exercising permissions granted by this License.
25
26      "Source" form shall mean the preferred form for making modifications,
27      including but not limited to software source code, documentation
28      source, and configuration files.
29
30      "Object" form shall mean any form resulting from mechanical
31      transformation or translation of a Source form, including but
32      not limited to compiled object code, generated documentation,
33      and conversions to other media types.
34
35      "Work" shall mean the work of authorship, whether in Source or
36      Object form, made available under the License, as indicated by a
37      copyright notice that is included in or attached to the work
38      (an example is provided in the Appendix below).
39
40      "Derivative Works" shall mean any work, whether in Source or Object
41      form, that is based on (or derived from) the Work and for which the
42      editorial revisions, annotations, elaborations, or other modifications
43      represent, as a whole, an original work of authorship. For the purposes
44      of this License, Derivative Works shall not include works that remain
45      separable from, or merely link (or bind by name) to the interfaces of,
46      the Work and Derivative Works thereof.
47
48      "Contribution" shall mean any work of authorship, including
49      the original version of the Work and any modifications or additions
50      to that Work or Derivative Works thereof, that is intentionally
51      submitted to Licensor for inclusion in the Work by the copyright owner
52      or by an individual or Legal Entity authorized to submit on behalf of
53      the copyright owner. For the purposes of this definition, "submitted"
54      means any form of electronic, verbal, or written communication sent
55      to the Licensor or its representatives, including but not limited to
56      communication on electronic mailing lists, source code control systems,
57      and issue tracking systems that are managed by, or on behalf of, the
58      Licensor for the purpose of discussing and improving the Work, but
59      excluding communication that is conspicuously marked or otherwise
60      designated in writing by the copyright owner as "Not a Contribution."
61
62      "Contributor" shall mean Licensor and any individual or Legal Entity
63      on behalf of whom a Contribution has been received by Licensor and
64      subsequently incorporated within the Work.
65
66   2. Grant of Copyright License. Subject to the terms and conditions of
67      this License, each Contributor hereby grants to You a perpetual,
68      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69      copyright license to reproduce, prepare Derivative Works of,
70      publicly display, publicly perform, sublicense, and distribute the
71      Work and such Derivative Works in Source or Object form.
72
73   3. Grant of Patent License. Subject to the terms and conditions of
74      this License, each Contributor hereby grants to You a perpetual,
75      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76      (except as stated in this section) patent license to make, have made,
77      use, offer to sell, sell, import, and otherwise transfer the Work,
78      where such license applies only to those patent claims licensable
79      by such Contributor that are necessarily infringed by their
80      Contribution(s) alone or by combination of their Contribution(s)
81      with the Work to which such Contribution(s) was submitted. If You
82      institute patent litigation against any entity (including a
83      cross-claim or counterclaim in a lawsuit) alleging that the Work
84      or a Contribution incorporated within the Work constitutes direct
85      or contributory patent infringement, then any patent licenses
86      granted to You under this License for that Work shall terminate
87      as of the date such litigation is filed.
88
89   4. Redistribution. You may reproduce and distribute copies of the
90      Work or Derivative Works thereof in any medium, with or without
91      modifications, and in Source or Object form, provided that You
92      meet the following conditions:
93
94      (a) You must give any other recipients of the Work or
95          Derivative Works a copy of this License; and
96
97      (b) You must cause any modified files to carry prominent notices
98          stating that You changed the files; and
99
100      (c) You must retain, in the Source form of any Derivative Works
101          that You distribute, all copyright, patent, trademark, and
102          attribution notices from the Source form of the Work,
103          excluding those notices that do not pertain to any part of
104          the Derivative Works; and
105
106      (d) If the Work includes a "NOTICE" text file as part of its
107          distribution, then any Derivative Works that You distribute must
108          include a readable copy of the attribution notices contained
109          within such NOTICE file, excluding those notices that do not
110          pertain to any part of the Derivative Works, in at least one
111          of the following places: within a NOTICE text file distributed
112          as part of the Derivative Works; within the Source form or
113          documentation, if provided along with the Derivative Works; or,
114          within a display generated by the Derivative Works, if and
115          wherever such third-party notices normally appear. The contents
116          of the NOTICE file are for informational purposes only and
117          do not modify the License. You may add Your own attribution
118          notices within Derivative Works that You distribute, alongside
119          or as an addendum to the NOTICE text from the Work, provided
120          that such additional attribution notices cannot be construed
121          as modifying the License.
122
123      You may add Your own copyright statement to Your modifications and
124      may provide additional or different license terms and conditions
125      for use, reproduction, or distribution of Your modifications, or
126      for any such Derivative Works as a whole, provided Your use,
127      reproduction, and distribution of the Work otherwise complies with
128      the conditions stated in this License.
129
130   5. Submission of Contributions. Unless You explicitly state otherwise,
131      any Contribution intentionally submitted for inclusion in the Work
132      by You to the Licensor shall be under the terms and conditions of
133      this License, without any additional terms or conditions.
134      Notwithstanding the above, nothing herein shall supersede or modify
135      the terms of any separate license agreement you may have executed
136      with Licensor regarding such Contributions.
137
138   6. Trademarks. This License does not grant permission to use the trade
139      names, trademarks, service marks, or product names of the Licensor,
140      except as required for reasonable and customary use in describing the
141      origin of the Work and reproducing the content of the NOTICE file.
142
143   7. Disclaimer of Warranty. Unless required by applicable law or
144      agreed to in writing, Licensor provides the Work (and each
145      Contributor provides its Contributions) on an "AS IS" BASIS,
146      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147      implied, including, without limitation, any warranties or conditions
148      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149      PARTICULAR PURPOSE. You are solely responsible for determining the
150      appropriateness of using or redistributing the Work and assume any
151      risks associated with Your exercise of permissions under this License.
152
153   8. Limitation of Liability. In no event and under no legal theory,
154      whether in tort (including negligence), contract, or otherwise,
155      unless required by applicable law (such as deliberate and grossly
156      negligent acts) or agreed to in writing, shall any Contributor be
157      liable to You for damages, including any direct, indirect, special,
158      incidental, or consequential damages of any character arising as a
159      result of this License or out of the use or inability to use the
160      Work (including but not limited to damages for loss of goodwill,
161      work stoppage, computer failure or malfunction, or any and all
162      other commercial damages or losses), even if such Contributor
163      has been advised of the possibility of such damages.
164
165   9. Accepting Warranty or Additional Liability. While redistributing
166      the Work or Derivative Works thereof, You may choose to offer,
167      and charge a fee for, acceptance of support, warranty, indemnity,
168      or other liability obligations and/or rights consistent with this
169      License. However, in accepting such obligations, You may act only
170      on Your own behalf and on Your sole responsibility, not on behalf
171      of any other Contributor, and only if You agree to indemnify,
172      defend, and hold each Contributor harmless for any liability
173      incurred by, or claims asserted against, such Contributor by reason
174      of your accepting any such warranty or additional liability.
175
176   END OF TERMS AND CONDITIONS
177
178   APPENDIX: How to apply the Apache License to your work.
179
180      To apply the Apache License to your work, attach the following
181      boilerplate notice, with the fields enclosed by brackets "[]"
182      replaced with your own identifying information. (Don't include
183      the brackets!)  The text should be enclosed in the appropriate
184      comment syntax for the file format. We also recommend that a
185      file or class name and description of purpose be included on the
186      same "printed page" as the copyright notice for easier
187      identification within third-party archives.
188
189   Copyright [2008] [Dr. Arno Wacker, University of Duisburg-Essen]
190
191   Licensed under the Apache License, Version 2.0 (the "License");
192   you may not use this file except in compliance with the License.
193   You may obtain a copy of the License at
194
195       http://www.apache.org/licenses/LICENSE-2.0
196
197   Unless required by applicable law or agreed to in writing, software
198   distributed under the License is distributed on an "AS IS" BASIS,
199   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200   See the License for the specific language governing permissions and
201   limitations under the License.
202*/
203
204
205using System;
206using System.Collections.Generic;
207using System.Linq;
208using System.Text;
209
210// additional needed libs
211using System.Windows.Controls;
212using System.ComponentModel;
213using System.Threading;
214using System.Collections;
215using System.Diagnostics;
216
217//Cryptool 2.0 specific includes
218using Cryptool.PluginBase;
219using Cryptool.PluginBase.Cryptography;
220using Cryptool.PluginBase.Miscellaneous;
221using Cryptool.PluginBase.IO;
222
223
224
225namespace Cryptool.Enigma
226{
227    [Author("Dr. Arno Wacker", "arno.wacker@cryptool.org", "Uni Duisburg-Essen", "http://www.uni-duisburg-essen.de")]
228    [PluginInfo(false, "Enigma", "Polyalphabetic rotor-cipher machine.", null,
229      "Enigma/Images/Enigma.png", "Enigma/Images/encrypt.png", "Enigma/Images/decrypt.png")]
230    [EncryptionType(EncryptionType.Classic)]
231    public class Enigma: IEncryption
232    {
233        #region Private variables
234
235        private bool stop = false;
236
237        private EnigmaSettings settings;
238        private EnigmaCore core;
239        private EnigmaAnalyzer analyzer;
240        private string inputString;
241        private string outputString;
242        private string savedKey;
243       
244        //private class analysisConfigSettings :IComparable<analysisConfigSettings>
245        //{
246        //    public int Rotor1;
247        //    public int Rotor2;
248        //    public int Rotor3;
249        //    public int Ring1;
250        //    public int Ring2;
251        //    public int Ring3;
252        //    public string Key;
253        //    public string PlugBoard = "-- no plugs --";
254        //    public double IC;
255
256        //    #region IComparable<analysisConfigSettings> Member
257
258        //    public int CompareTo(analysisConfigSettings other)
259        //    {
260        //        return this.IC.CompareTo(other.IC);
261        //    }
262
263        //    #endregion
264        //}
265
266        //private List<analysisConfigSettings> analysisCandidates = new List<analysisConfigSettings>();
267        //private const int maxAnalysisEntries = 10;
268       
269       
270        #endregion
271
272        #region Private methods
273
274        #region Formatting stuff
275
276        /// <summary>
277        /// Encrypts or decrypts a string with the given key (rotor positions) and formats
278        /// the output according to the settings
279        /// </summary>
280        /// <param name="rotor1Pos">Position of rotor 1 (fastest)</param>
281        /// <param name="rotor2Pos">Position of rotor 2 (middle)</param>
282        /// <param name="rotor3Pos">Position of rotor 3 (slowest)</param>
283        /// <param name="rotor4Pos">Position of rotor 4 (extra rotor for M4)</param>
284        /// <param name="text">The text for en/decryption. This string may contain
285        /// arbitrary characters, which will be dealt with according to the settings given</param>
286        /// <returns>The encrypted/decrypted string</returns>
287        private string FormattedEncrypt(int rotor1Pos, int rotor2Pos, int rotor3Pos, int rotor4Pos, string text)
288        {
289            return postFormatOutput(core.Encrypt(rotor1Pos, rotor2Pos, rotor3Pos, rotor4Pos, preFormatInput(text)));
290        }
291
292        /// <summary>
293        /// Format the string to contain only alphabet characters in upper case
294        /// </summary>
295        /// <param name="text">The string to be prepared</param>
296        /// <returns>The properly formated string to be processed direct by the encryption function</returns>
297        private string preFormatInput(string text)
298        {
299            StringBuilder result = new StringBuilder();
300
301            foreach (char c in text)
302            {
303                if (!settings.Alphabet.Contains(char.ToUpper(c)))
304                {
305                    switch (settings.UnknownSymbolHandling)
306                    {
307                        case 0: // ignore
308                            result.Append(c);
309                            break;
310                        case 1: // remove
311                            continue;
312                        case 2: // replace by X
313                            result.Append('X');
314                            break;
315                    }
316                }
317                else
318                    result.Append(c);
319            }
320
321            return result.ToString();
322
323        }
324
325        /// <summary>
326        /// Formats the string processed by the encryption for presentation according
327        /// to the settings given
328        /// </summary>
329        /// <param name="text">The encrypted text</param>
330        /// <returns>The formatted text for output</returns>
331        private string postFormatOutput(string text)
332        {
333            switch (settings.CaseHandling)
334            {
335                case 0: // preserve
336                    break;
337                case 1: // upper
338                    return text.ToUpper();
339                case 2: // lower
340                    return text.ToLower();
341            }
342            return text;
343        }
344
345        #endregion
346
347        #region Analyzer
348
349        /// <summary>
350        /// This venthandler is called, when the analyzer has an intermediate result
351        /// </summary>
352        /// <param name="sender"></param>
353        /// <param name="e"></param>
354        private void analyzer_OnIntermediateResult(object sender, IntermediateResultEventArgs e)
355        {
356            // Got an intermidate results from the analyzer, hence display it
357            outputString = e.Result;
358            OnPropertyChanged("OutputString");
359        }
360
361
362
363        //private void printBestCandidates()
364        //{
365        //    StringBuilder message = new StringBuilder("  -- Analysis results --" + Environment.NewLine);
366        //    message.AppendLine("=====================================");
367
368        //    foreach (analysisConfigSettings cfg in analysisCandidates)
369        //    {
370        //        message.AppendFormat("{0} | {1},{2},{3} | {4},{5},{6} | {7} | {8}" + Environment.NewLine,
371        //            cfg.IC.ToString(),
372        //            (rotorEnum)cfg.Rotor3, (rotorEnum)cfg.Rotor2, (rotorEnum)cfg.Rotor1,
373        //            cfg.Ring3.ToString("00"), cfg.Ring2.ToString("00"), cfg.Ring1.ToString("00"),
374        //            cfg.Key, pB2String(cfg.PlugBoard));
375        //    }
376
377        //    EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(message.ToString(), this, NotificationLevel.Info));
378        //}
379
380        //private string analyze(int rotor1Pos, int rotor2Pos, int rotor3Pos, string text)
381        //{
382        //    string result = core.Encrypt(rotor1Pos, rotor2Pos, rotor3Pos,0,text);
383        //    double newIC = calculateIC(result);
384
385        //    if (analysisCandidates.Count >= maxAnalysisEntries)
386        //    {
387        //        // List is full, check if we need to remove one
388        //        if (newIC > analysisCandidates[0].IC)
389        //        {
390        //            double currentMax = analysisCandidates[analysisCandidates.Count - 1].IC;
391
392        //            analysisConfigSettings csetting = new analysisConfigSettings();
393        //            csetting.IC = newIC;
394        //            csetting.Rotor1 = core.Rotor1;
395        //            csetting.Rotor2 = core.Rotor2;
396        //            csetting.Rotor3 = core.Rotor3;
397        //            csetting.Ring1 = core.Ring1;
398        //            csetting.Ring2 = core.Ring2;
399        //            csetting.Ring3 = core.Ring3;
400        //            csetting.PlugBoard = core.Plugboard;
401        //            csetting.Key = settings.Alphabet[rotor3Pos].ToString() + settings.Alphabet[rotor2Pos].ToString() + settings.Alphabet[rotor1Pos].ToString();
402
403        //            analysisCandidates.Add(csetting);
404        //            analysisCandidates.Sort();
405
406        //            // remove the smallest one
407        //            analysisCandidates.RemoveAt(0);
408
409
410        //            if (newIC > currentMax)
411        //            {
412        //                // new best option
413        //                string status = String.Format("ANALYSIS: ==> Found better rotor settings: {0},{1},{2}; {3},{4},{5}; Key: {6}; I.C.={7} <==",
414        //                (rotorEnum)csetting.Rotor3, (rotorEnum)csetting.Rotor2, (rotorEnum)csetting.Rotor1,
415        //                csetting.Ring3.ToString("00"), csetting.Ring2.ToString("00"), csetting.Ring1.ToString("00"),
416        //                csetting.Key, newIC.ToString());
417        //                EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(status, this, NotificationLevel.Info));
418
419        //                printBestCandidates();
420
421        //                outputString = result;
422        //                OnPropertyChanged("OutputString");
423        //            }
424
425                   
426        //        }
427        //    }
428        //    else
429        //    {
430        //        //there is room left, hence add the element
431
432        //        analysisConfigSettings csetting = new analysisConfigSettings();
433        //        csetting.IC = newIC;
434        //        csetting.Rotor1 = core.Rotor1;
435        //        csetting.Rotor2 = core.Rotor2;
436        //        csetting.Rotor3 = core.Rotor3;
437        //        csetting.Ring1 = core.Ring1;
438        //        csetting.Ring2 = core.Ring2;
439        //        csetting.Ring3 = core.Ring3;
440        //        csetting.PlugBoard = core.Plugboard;
441        //        csetting.Key = settings.Alphabet[rotor3Pos].ToString() + settings.Alphabet[rotor2Pos].ToString() + settings.Alphabet[rotor1Pos].ToString();
442
443        //        analysisCandidates.Add(csetting);
444        //        analysisCandidates.Sort();
445
446        //        if (analysisCandidates.Count == maxAnalysisEntries)
447        //        {
448        //            printBestCandidates();
449
450        //            // current best option
451        //            analysisConfigSettings bestOption = analysisCandidates[analysisCandidates.Count - 1];
452
453        //            string status = String.Format("ANALYSIS: Best candidates is filled. Best option so far: {0},{1},{2}; Key: {3}; I.C.={4}",
454        //            (rotorEnum)bestOption.Rotor3, (rotorEnum)bestOption.Rotor2, (rotorEnum)bestOption.Rotor1, bestOption.Key, bestOption.IC.ToString());
455        //            EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(status, this, NotificationLevel.Debug));
456
457        //            // fire the event, so someting becomes visible..
458        //            outputString = result;
459        //            OnPropertyChanged("OutputString");
460        //        }
461
462        //    }
463
464        //    return result;
465        //}
466
467        //private double calculateIC(string input)
468        //{
469        //    int[] statistics = new int[settings.Alphabet.Length];
470        //    long cipherTextLength = 0; //input.Length; //n
471        //    long countDoubleCharacters = 0;
472
473        //    // first count the frequency of (single) letters
474        //    foreach (char c in input)
475        //    {
476        //        int i = settings.Alphabet.IndexOf(char.ToUpper(c));
477        //        if (i >= 0) statistics[i]++;
478        //    }
479
480
481        //    // now calculate the index of coincidences
482        //    for (int i = 0; i < statistics.Length; i++)
483        //    {
484        //        cipherTextLength += statistics[i];
485        //        countDoubleCharacters += (statistics[i] * (statistics[i] - 1));
486        //    }
487
488        //    return((double)countDoubleCharacters / (double)(cipherTextLength * (cipherTextLength - 1)));
489        //}
490
491        //private void runAnalysis(string inputText)
492        //{
493        //    LogMessage("=========> ANALYSIS OF ENIGMA MESSAGE STARTED <=========", NotificationLevel.Info);
494
495
496        //    // some initialisation
497        //    analysisCandidates.Clear();
498
499
500        //    //prepare for analysis
501        //    LogMessage("ANALYSIS: Preformatting text...", NotificationLevel.Debug);
502        //    string preformatedText = preFormatInput(inputText);
503
504        //    if (settings.AnalyzeRotors)
505        //    {
506        //        LogMessage("ANALYSIS: ====> Stage 1 - Searching used rotors <====", NotificationLevel.Info);
507        //        analyzeRotors(preformatedText);
508        //    }
509        //    else
510        //    {
511        //        LogMessage("ANALYSIS: ====> Skipping stage 1 - Using rotors  from settings <====", NotificationLevel.Info);
512        //        analysisConfigSettings settingsConfig = new analysisConfigSettings();
513        //        settingsConfig.Rotor1 = settings.Rotor1;
514        //        settingsConfig.Rotor2 = settings.Rotor2;
515        //        settingsConfig.Rotor3 = settings.Rotor3;
516        //        settingsConfig.Ring1 = settings.AnalyzeRings ? 1 : settings.Ring1;
517        //        settingsConfig.Ring2 = settings.AnalyzeRings ? 1 : settings.Ring2;
518        //        settingsConfig.Ring3 = settings.AnalyzeRings ? 1 : settings.Ring3;
519        //        settingsConfig.Key = settings.Key;
520
521        //        analysisCandidates.Add(settingsConfig);
522        //    }
523           
524        //    // just for debugging
525        //    //analysisCandidates[analysisCandidates.Count-1].Rotor1 = 2;
526        //    //analysisCandidates[analysisCandidates.Count - 1].Rotor2 = 0;
527        //    //analysisCandidates[analysisCandidates.Count - 1].Rotor3 = 1;
528        //    //analysisCandidates[analysisCandidates.Count - 1].Key = "BKF";
529
530        //    printBestCandidates();
531
532        //    // put the core in quiet mode, since now many internal changes occur
533        //    core.VerboseLevel = VerboseLevels.Quiet;
534
535        //    if (settings.AnalyzeRings)
536        //    {
537        //        LogMessage("ANALYSIS: ====> Stage 2 - Searching ring positions <====", NotificationLevel.Info);
538
539        //        for (int j = analysisCandidates.Count - 1; j >= 0; j--)
540        //        {
541        //            analysisCandidates[j].PlugBoard = settings.Alphabet; // empty plugs
542        //            analyzeRings(analysisCandidates[j], preformatedText);
543        //        }
544
545        //        analysisCandidates.Sort();
546        //    }
547        //    else
548        //    {
549        //        LogMessage("ANALYSIS: ====> Skipping stage 2 - Using provided ring settings <====", NotificationLevel.Info);
550
551        //        for (int j = analysisCandidates.Count - 1; j >= 0; j--)
552        //        {
553        //            analysisCandidates[j].PlugBoard = settings.Alphabet; // empty plugs
554        //            analysisCandidates[j].Ring1 = settings.Ring1;
555        //            analysisCandidates[j].Ring2 = settings.Ring2;
556        //            analysisCandidates[j].Ring3 = settings.Ring3;
557        //        }
558        //    }
559
560        //    printBestCandidates();
561
562
563        //    if (settings.AnalyzePlugs)
564        //    {
565        //        LogMessage("ANALYSIS: ====> Stage 3 - Searching used plugs <====", NotificationLevel.Info);
566
567        //        for (int j = analysisCandidates.Count - 1; j >= 0; j--)
568        //        {
569        //            analyzePlugs(analysisCandidates[j], settings.MaxSearchedPlugs, preformatedText);
570        //        }
571
572        //        analysisCandidates.Sort();
573        //    }
574        //    else
575        //    {
576        //        LogMessage("ANALYSIS: ====> Skipping stage 3 - Using provided plugboard <====", NotificationLevel.Info);
577
578        //        for (int j = analysisCandidates.Count - 1; j >= 0; j--)
579        //        {
580        //            analysisCandidates[j].PlugBoard = settings.PlugBoard;
581        //        }
582        //    }
583
584        //    printBestCandidates();
585
586           
587        //    LogMessage("=========> ANALYSIS OF ENIGMA MESSAGE DONE <=========", NotificationLevel.Info);
588
589        //    // switch back to verbose core
590        //    core.VerboseLevel = VerboseLevels.VeryVerbose;
591
592        //    // decrypt with best option
593        //    analysisConfigSettings bestConfig = analysisCandidates[analysisCandidates.Count - 1];
594
595        //    core.setInternalConfig(bestConfig.Rotor1, bestConfig.Rotor2, bestConfig.Rotor3, 0, settings.Reflector, bestConfig.Ring1, bestConfig.Ring2, bestConfig.Ring3, 1, bestConfig.PlugBoard);
596        //    int r1p = settings.Alphabet.IndexOf(bestConfig.Key[2]);
597        //    int r2p = settings.Alphabet.IndexOf(bestConfig.Key[1]);
598        //    int r3p = settings.Alphabet.IndexOf(bestConfig.Key[0]);
599        //    outputString = postFormatOutput(core.Encrypt(r1p, r2p, r3p, 0, preformatedText));
600        //    OnPropertyChanged("OutputString");
601
602        //}
603
604        //private void analyzeRotors(string text)
605        //{
606        //    // Start the stopwatch
607        //    Stopwatch sw = Stopwatch.StartNew();
608        //    int trials = 0;
609
610        //    for (int i = 0; i < 8; i++)
611        //    {
612        //        //Rotor 3 (slowest)
613        //        if (!includeRotor(i)) continue;
614        //        settings.Rotor3 = i;
615        //        for (int j = 0; j < 8; j++)
616        //        {
617        //            // Rotor 2 (middle)
618        //            if (!includeRotor(j) || j==i) continue;
619        //            settings.Rotor2 = j;
620
621        //            for (int k = 0; k < 8; k++)
622        //            {
623        //                // Rotor 1 (fastest)
624        //                if (!includeRotor(k) || k == i || k == j) continue;
625        //                settings.Rotor1 = k;
626
627        //                //set the internal Config to the new rotors
628        //                core.setInternalConfig(k, j, i, 0, settings.Reflector,
629        //                    settings.AnalyzeRings?1: settings.Ring1,
630        //                    settings.AnalyzeRings ? 1 : settings.Ring2,
631        //                    settings.AnalyzeRings ? 1 : settings.Ring3,
632        //                    settings.Ring4,
633        //                    settings.AnalyzePlugs ? settings.Alphabet: settings.PlugBoard);
634
635        //                analyzeKey(text);
636        //                trials++;
637
638        //                EventsHelper.ProgressChanged(OnPluginProgressChanged, this,
639        //                        new PluginProgressEventArgs(i * Math.Pow(8, 2) + j * 8 + k, Math.Pow(8, 3)));
640
641        //                if (stop) break;
642        //            } // Rotor 1
643        //            if (stop) break;
644        //        } // Rotor 2
645        //        if (stop) break;
646        //    } // Rotor 3
647
648        //    // Stop the stopwatch
649        //    sw.Stop();
650
651        //    string msg = String.Format("Processed {0} rotor permutations in {1}!",
652        //        trials, sw.Elapsed.ToString());
653        //    LogMessage(msg, NotificationLevel.Info);
654        //}
655
656        //private bool includeRotor(int i)
657        //{
658        //    switch (i)
659        //    {
660        //        case 0: return settings.AnalysisUseRotorI;
661        //        case 1: return settings.AnalysisUseRotorII;
662        //        case 2: return settings.AnalysisUseRotorIII;
663        //        case 3: return settings.AnalysisUseRotorIV;
664        //        case 4: return settings.AnalysisUseRotorV;
665        //        case 5: return settings.AnalysisUseRotorVI;
666        //        case 6: return settings.AnalysisUseRotorVII;
667        //        case 7: return settings.AnalysisUseRotorVIII;
668        //    }
669        //    return false;
670        //}
671
672        //private void analyzeKey(string text)
673        //{
674        //    /////////////////////////////////////////
675        //    // now run through all rotor positions..
676
677        //    // Start the stopwatch
678        //    Stopwatch sw = Stopwatch.StartNew();
679        //    int trials = 0;
680
681        //    // Rotor 1 positions (fastest)
682        //    for (int l = 0; l < 26; l++)
683        //    {
684        //        for (int m = 0; m < 26; m++)
685        //        {
686        //            for (int n = 0; n < 26; n++)
687        //            {
688        //                analyze(l, m, n, text);
689        //                trials++;
690        //                if (stop) break;
691        //            }
692        //            if (stop) break;
693        //        }
694        //        if (stop) break;
695        //    } // Rotor1 positions
696
697        //    // Stop the stopwatch
698        //    sw.Stop();
699
700        //    string msg = String.Format("Processed {0} rotor positions for {1},{2},{3} in {4}!",
701        //        trials, (rotorEnum)core.Rotor3, (rotorEnum)core.Rotor2, (rotorEnum)core.Rotor1, sw.Elapsed.ToString());
702        //    LogMessage(msg, NotificationLevel.Info);
703        //}
704
705        //private void analyzeRings(analysisConfigSettings enigmaConfig, string text)
706        //{
707
708        //    // get the current rotor positions
709        //    int r1pos = settings.Alphabet.IndexOf(enigmaConfig.Key[2]);
710        //    int r2pos = settings.Alphabet.IndexOf(enigmaConfig.Key[1]);
711        //    int r3pos = settings.Alphabet.IndexOf(enigmaConfig.Key[0]);
712
713        //    if (settings.AnalyzeKey)
714        //    {
715        //        // turn fast rotor
716        //        for (int i = 1; i <= settings.Alphabet.Length; i++)
717        //        {
718        //            core.setInternalConfig(enigmaConfig.Rotor1, enigmaConfig.Rotor2, enigmaConfig.Rotor3, 0, settings.Reflector, i, 1, 1, 1, enigmaConfig.PlugBoard);
719
720
721        //            int rotatedR1Pos;
722        //            if (settings.AnalyzeKey)
723        //                // rotate the fast rotor with the ring
724        //                rotatedR1Pos = (r1pos + (i - 1)) % settings.Alphabet.Length;
725        //            else
726        //                rotatedR1Pos = r1pos;
727
728
729        //            string result = core.Encrypt(rotatedR1Pos, r2pos, r3pos, 0, text);
730
731        //            double newIC = calculateIC(result);
732
733        //            if (newIC > enigmaConfig.IC)
734        //            {
735        //                //better value, hence update the data
736        //                enigmaConfig.IC = newIC;
737        //                enigmaConfig.Ring1 = i;
738        //                enigmaConfig.Key = settings.Alphabet[r3pos].ToString() + settings.Alphabet[r2pos].ToString() + settings.Alphabet[rotatedR1Pos].ToString();
739        //            }
740
741        //        }
742
743        //        // update the current rotor positions (only rotor 1 might have changed)
744        //        r1pos = settings.Alphabet.IndexOf(enigmaConfig.Key[2]);
745
746        //        // turn middle rotor
747        //        for (int i = 1; i <= settings.Alphabet.Length; i++)
748        //        {
749        //            core.setInternalConfig(enigmaConfig.Rotor1, enigmaConfig.Rotor2, enigmaConfig.Rotor3, 0, settings.Reflector, enigmaConfig.Ring1, i, 1, 1, enigmaConfig.PlugBoard);
750
751        //            int rotatedR2Pos;
752        //            if (settings.AnalyzeKey)
753        //                // rotate the middle rotor with the ring
754        //                rotatedR2Pos = (r2pos + (i - 1)) % settings.Alphabet.Length;
755        //            else
756        //                rotatedR2Pos = r2pos;
757
758        //            string result = core.Encrypt(r1pos, rotatedR2Pos, r3pos, 0, text);
759
760        //            double newIC = calculateIC(result);
761
762        //            if (newIC > enigmaConfig.IC)
763        //            {
764        //                //better value, hence update the data
765        //                enigmaConfig.IC = newIC;
766        //                enigmaConfig.Ring2 = i;
767        //                enigmaConfig.Key = settings.Alphabet[r3pos].ToString() + settings.Alphabet[rotatedR2Pos].ToString() + settings.Alphabet[r1pos].ToString();
768        //            }
769        //        }
770        //    }
771        //    else
772        //    {
773        //        // in case the key is fixed, we search all combinations, i.e. 26*26*26
774        //        for (int i = 1; i <= settings.Alphabet.Length; i++)
775        //        {
776        //            for (int j = 1; j <= settings.Alphabet.Length; j++)
777        //            {
778        //                for (int k = 1; k <= settings.Alphabet.Length; k++)
779        //                {
780        //                    core.setInternalConfig(enigmaConfig.Rotor1, enigmaConfig.Rotor2, enigmaConfig.Rotor3, 0, settings.Reflector, k, j, i, 1, enigmaConfig.PlugBoard);
781        //                    string result = core.Encrypt(r1pos, r2pos, r3pos, 0, text);
782        //                    double newIC = calculateIC(result);
783
784        //                    if (newIC > enigmaConfig.IC)
785        //                    {
786        //                        //better value, hence update the data
787        //                        enigmaConfig.IC = newIC;
788        //                        enigmaConfig.Ring1 = k;
789        //                        enigmaConfig.Ring2 = j;
790        //                        enigmaConfig.Ring2 = i;
791        //                        enigmaConfig.Key = settings.Alphabet[r3pos].ToString() + settings.Alphabet[r2pos].ToString() + settings.Alphabet[r1pos].ToString();
792        //                    }
793        //                }
794        //            }
795        //        }
796        //    }
797
798        //    // print best option
799        //    string msg = String.Format("ANALYSIS: Best ring setting: {0} | {1},{2},{3} | {4},{5},{6} | {7} | {8}",
800        //        enigmaConfig.IC.ToString(),
801        //        (rotorEnum)enigmaConfig.Rotor3, (rotorEnum)enigmaConfig.Rotor2, (rotorEnum)enigmaConfig.Rotor1,
802        //        enigmaConfig.Ring3.ToString("00"), enigmaConfig.Ring2.ToString("00"), enigmaConfig.Ring1.ToString("00"),
803        //        enigmaConfig.Key, pB2String(enigmaConfig.PlugBoard));
804        //    LogMessage(msg, NotificationLevel.Info);
805
806        //}
807
808        //private void analyzePlugs(analysisConfigSettings enigmaConfig, int maxPlugs, string text)
809        //{
810        //    string tmp;
811        //    bool plugFound = false;
812        //    int trials = 0;
813
814        //    for (int n = 0; n < maxPlugs; n++)
815        //    {
816
817        //        //LogMessage(String.Format("ANALYSIS: ====> Stage 3.{0} - Searching plugs <====",(n+1)), NotificationLevel.Info);
818
819        //        tmp = enigmaConfig.PlugBoard;
820        //        plugFound = false;
821
822        //        for (int i = 0; i < settings.Alphabet.Length; i++)
823        //        {
824        //            for (int j = i + 1; j < settings.Alphabet.Length; j++)
825        //            {
826        //                //create a "clean" plugboard
827        //                StringBuilder plugboard = new StringBuilder(tmp);
828
829        //                //if both selected letters are pluged, ignore them
830        //                if (plugboard[i] != settings.Alphabet[i] && plugboard[j] != settings.Alphabet[j])
831        //                    continue;
832                       
833        //                if (plugboard[i] != settings.Alphabet[i])
834        //                {
835        //                    plugFound = plugFound | resolvePlugConflict(i, j, enigmaConfig, plugboard.ToString(), text);
836        //                    trials += 3;
837        //                    continue;
838        //                }
839
840        //                if (plugboard[j] != settings.Alphabet[j])
841        //                {
842        //                    plugFound = plugFound | resolvePlugConflict(j, i, enigmaConfig, plugboard.ToString(), text);
843        //                    trials += 3;
844        //                    continue;
845        //                }
846
847        //                //swap i with j
848        //                plugboard[i] = settings.Alphabet[j];
849        //                plugboard[j] = settings.Alphabet[i];
850
851        //                core.setInternalConfig(enigmaConfig.Rotor1, enigmaConfig.Rotor2, enigmaConfig.Rotor3, 0, settings.Reflector, enigmaConfig.Ring1, enigmaConfig.Ring2, 1, 1, plugboard.ToString());
852
853
854        //                int r1pos = settings.Alphabet.IndexOf(enigmaConfig.Key[2]);
855        //                int r2pos = settings.Alphabet.IndexOf(enigmaConfig.Key[1]);
856        //                int r3pos = settings.Alphabet.IndexOf(enigmaConfig.Key[0]);
857        //                string result = core.Encrypt(r1pos, r2pos, r3pos, 0, text);
858
859        //                double newIC = calculateIC(result);
860        //                trials++;
861
862        //                if (newIC > enigmaConfig.IC)
863        //                {
864        //                    enigmaConfig.IC = newIC;
865        //                    enigmaConfig.PlugBoard = plugboard.ToString();
866        //                    plugFound = true;
867        //                }
868        //            }
869        //        }
870
871
872        //        string msg = String.Format("ANALYSIS: Plugs setting in round {0} after {1} trials: {2} | {3},{4},{5} | {6},{7},{8} | {9} | {10}",
873        //            (n+1),trials, enigmaConfig.IC.ToString(),
874        //            (rotorEnum)enigmaConfig.Rotor3, (rotorEnum)enigmaConfig.Rotor2, (rotorEnum)enigmaConfig.Rotor1,
875        //            enigmaConfig.Ring3, enigmaConfig.Ring2, enigmaConfig.Ring1,
876        //            enigmaConfig.Key, pB2String(enigmaConfig.PlugBoard));
877        //        LogMessage(msg, NotificationLevel.Info);
878
879        //        // no plug could lead to a better result, hence abort plug search.
880        //        if (!plugFound)
881        //            break;
882        //    }
883        //}
884
885        //private bool resolvePlugConflict(int conflictLetterPos, int otherLetterPos, analysisConfigSettings enigmaConfig, string unmodifiedPlugboard, string text)
886        //{
887        //    bool found = false;
888
889        //    int pluggedLetterPos = settings.Alphabet.IndexOf(unmodifiedPlugboard[conflictLetterPos]);
890
891
892        //    // plug otherLetter together with pluggedLetter and restore the coflictLetter
893        //    StringBuilder o2pPlugPlugboard = new StringBuilder(unmodifiedPlugboard);
894        //    o2pPlugPlugboard[conflictLetterPos] = settings.Alphabet[conflictLetterPos]; // restore conflictLetter
895        //    o2pPlugPlugboard[otherLetterPos] = settings.Alphabet[pluggedLetterPos];     // swap other with
896        //    o2pPlugPlugboard[pluggedLetterPos] = settings.Alphabet[otherLetterPos];     // plugged
897
898
899        //    // plug conflictLetter with otherLetter and restore pluggedLetter one
900        //    StringBuilder c2oPlugboard = new StringBuilder(unmodifiedPlugboard);
901        //    c2oPlugboard[pluggedLetterPos] = settings.Alphabet[pluggedLetterPos]; // restore pluggedLetter
902        //    c2oPlugboard[conflictLetterPos] = settings.Alphabet[otherLetterPos];  // swap conflictLetter
903        //    c2oPlugboard[otherLetterPos] = settings.Alphabet[conflictLetterPos];  // with otherLetter
904
905
906        //    // now we habe three different plug-posibilities and need to determine
907        //    // the best one, which remains set, hence we do 3 trial encryptions
908           
909
910        //    // get the current key
911        //    int r1pos = settings.Alphabet.IndexOf(enigmaConfig.Key[2]);
912        //    int r2pos = settings.Alphabet.IndexOf(enigmaConfig.Key[1]);
913        //    int r3pos = settings.Alphabet.IndexOf(enigmaConfig.Key[0]);
914
915
916        //    // start with the unmodified
917        //    core.setInternalConfig(enigmaConfig.Rotor1, enigmaConfig.Rotor2, enigmaConfig.Rotor3, 0, settings.Reflector, enigmaConfig.Ring1, enigmaConfig.Ring2, enigmaConfig.Ring3, 1, unmodifiedPlugboard);
918        //    double unmodifiedIC = calculateIC(core.Encrypt(r1pos, r2pos, r3pos, 0, text));
919
920        //    // now o2p
921        //    core.setInternalConfig(enigmaConfig.Rotor1, enigmaConfig.Rotor2, enigmaConfig.Rotor3, 0, settings.Reflector, enigmaConfig.Ring1, enigmaConfig.Ring2, enigmaConfig.Ring3, 1, o2pPlugPlugboard.ToString());
922        //    double o2pIC = calculateIC(core.Encrypt(r1pos, r2pos, r3pos, 0, text));
923
924        //    // now c2o
925        //    core.setInternalConfig(enigmaConfig.Rotor1, enigmaConfig.Rotor2, enigmaConfig.Rotor3, 0, settings.Reflector, enigmaConfig.Ring1, enigmaConfig.Ring2, enigmaConfig.Ring3, 1, c2oPlugboard.ToString());
926        //    double c2oIC = calculateIC(core.Encrypt(r1pos, r2pos, r3pos, 0, text));
927
928        //    string bestPlugBoard = enigmaConfig.PlugBoard;
929        //    double newIC;
930
931        //    if (c2oIC > unmodifiedIC)
932        //    {
933        //        if (c2oIC > o2pIC)
934        //        {
935        //            bestPlugBoard = c2oPlugboard.ToString();
936        //            newIC = c2oIC;
937        //        }
938        //        else
939        //        {
940        //            bestPlugBoard = o2pPlugPlugboard.ToString();
941        //            newIC = o2pIC;
942        //        }
943        //    }
944        //    else
945        //    {
946        //        if (unmodifiedIC > o2pIC)
947        //        {
948        //            bestPlugBoard = unmodifiedPlugboard;
949        //            newIC = unmodifiedIC;
950        //        }
951        //        else
952        //        {
953        //            bestPlugBoard = o2pPlugPlugboard.ToString();
954        //            newIC = o2pIC;
955        //        }
956        //    }
957
958
959        //    if (newIC > enigmaConfig.IC)
960        //    {
961        //        enigmaConfig.IC = newIC;
962        //        enigmaConfig.PlugBoard = bestPlugBoard;
963        //        found = true;
964        //    }
965
966        //    //string msg = String.Format("ANALYSIS PlUG CONFLICT: Unmodified [{0}] => {1}; Variant A [{2}] => {3}; Variant B[{4}] => {5} || Selected [{6}]",
967        //    //    pB2String(unmodifiedPlugboard), unmodifiedIC,
968        //    //    pB2String(c2oPlugboard.ToString()), c2oIC,
969        //    //    pB2String(o2pPlugPlugboard.ToString()), o2pIC,
970        //    //    pB2String(bestPlugBoard));
971
972        //    //LogMessage(msg, NotificationLevel.Info);
973
974        //    return found;
975        //}
976
977        #endregion
978
979        #region Encryption/Decryption
980
981        //private string crypt()
982        //{
983
984        //    DateTime start = DateTime.Now;
985
986        //    configureEnimga();
987
988        //    StringBuilder output = new StringBuilder("");
989        //    int i = 0;
990        //    char resultChar = '?';
991        //    bool wasUpperCase = false;
992
993        //    // re-set the key to initial value..
994        //    //settings.Key = initialKey;
995           
996
997
998        //    // now process each letter
999        //    foreach (char c in inputString.ToCharArray())
1000        //    {
1001        //        if (settings.Action == 0) EventsHelper.ProgressChanged(OnPluginProgressChanged, this, new PluginProgressEventArgs(i++, inputString.Length));
1002
1003        //        wasUpperCase = char.IsUpper(c);
1004        //        char upperC = char.ToUpper(c);
1005
1006        //        if (settings.Alphabet.Contains(upperC))
1007        //        {
1008        //            resultChar = enigmacrypt(upperC);
1009
1010        //        }
1011        //        else
1012        //        {
1013        //            switch (settings.UnknownSymbolHandling)
1014        //            {
1015        //                case 0: // ignore
1016        //                    resultChar = c;
1017        //                    break;
1018        //                case 1: // remove
1019        //                    continue;
1020        //                case 2: // replace by X
1021        //                    resultChar = enigmacrypt('X');
1022        //                    break;
1023        //            }
1024        //        }
1025
1026
1027        //        // case handling
1028        //        switch (settings.CaseHandling)
1029        //        {
1030        //            case 0: // preserve
1031        //                if (wasUpperCase)
1032        //                    resultChar = char.ToUpper(resultChar);
1033        //                else
1034        //                    resultChar = char.ToLower(resultChar);
1035        //                break;
1036        //            case 1: // upper
1037        //                resultChar = char.ToUpper(resultChar);
1038        //                break;
1039        //            case 2: // lower
1040        //                resultChar = char.ToLower(resultChar);
1041        //                break;
1042        //        }
1043
1044
1045        //        // append the calculated value to the output
1046        //        output.Append(resultChar);
1047        //    }
1048
1049        //    procTime = DateTime.Now.Subtract(start);
1050
1051        //    return output.ToString();
1052        //}
1053
1054        //private void configureEnimga()
1055        //{
1056        //    // set some helper variables
1057        //    A = settings.Alphabet + settings.Alphabet + settings.Alphabet;
1058        //    aLength = settings.Alphabet.Length;
1059
1060        //    // prepare the current string for the forward substitution. We use a the string 3-times, since this saves some alphabet wrap-arround checking
1061        //    rotor1For = rotors[settings.Model, settings.Rotor1] + rotors[settings.Model, settings.Rotor1] + rotors[settings.Model, settings.Rotor1];
1062        //    rotor2For = rotors[settings.Model, settings.Rotor2] + rotors[settings.Model, settings.Rotor2] + rotors[settings.Model, settings.Rotor2];
1063        //    rotor3For = rotors[settings.Model, settings.Rotor3] + rotors[settings.Model, settings.Rotor3] + rotors[settings.Model, settings.Rotor3];
1064        //    if (settings.Rotor4 < 8)
1065        //    {
1066        //        rotor4For = rotors[settings.Model, settings.Rotor4] + rotors[settings.Model, settings.Rotor4] + rotors[settings.Model, settings.Rotor4];
1067        //    }
1068
1069
1070        //    if (settings.Model > 0) // the Enigma A/B did not have a reflector, hence there is no reverse substitution
1071        //    {
1072        //        // prepare the current string for the reflector
1073        //        reflector = reflectors[settings.Model, settings.Reflector] + reflectors[settings.Model, settings.Reflector] + reflectors[settings.Model, settings.Reflector];
1074
1075        //        // prepare the current string for the reverse substitution.
1076        //        rotor1Rev = generateReverseSubst(rotors[settings.Model, settings.Rotor1]);
1077        //        rotor1Rev += rotor1Rev + rotor1Rev;
1078        //        rotor2Rev = generateReverseSubst(rotors[settings.Model, settings.Rotor2]);
1079        //        rotor2Rev += rotor2Rev + rotor2Rev;
1080        //        rotor3Rev = generateReverseSubst(rotors[settings.Model, settings.Rotor3]);
1081        //        rotor3Rev += rotor3Rev + rotor3Rev;
1082        //        if (settings.Rotor4 < 8)
1083        //        {
1084        //            rotor4Rev = generateReverseSubst(rotors[settings.Model, settings.Rotor4]);
1085        //            rotor4Rev += rotor4Rev + rotor4Rev;
1086        //        }
1087        //    }
1088        //    // configure rotor notches
1089        //    rotor1notches = notches[settings.Rotor1];
1090        //    rotor2notches = notches[settings.Rotor2];
1091        //    rotor3notches = notches[settings.Rotor3];
1092
1093
1094        //    //retrieve the current key from the settings           
1095        //    //currentKey[3] = settings.Key[settings.Key.Length - 1];
1096        //    //currentKey[2] = settings.Key[settings.Key.Length - 2];
1097        //    //currentKey[1] = settings.Key[settings.Key.Length - 3];
1098        //    //if (settings.Key.Length == 4) currentKey[0] = settings.Key[settings.Key.Length - 4];
1099        //}
1100
1101        //private char enigmacrypt(char keyPressed)
1102        //{
1103        //    //1. Substitution with plugboard
1104        //    char entrySubst = this.settings.PlugBoard(keyPressed);
1105
1106        //    //2. Spindle substitution
1107        //    char spindleSubst = enigmaSpindle(entrySubst);
1108
1109        //    //3. Substitution with plugboard
1110        //    return this.settings.PlugBoard(spindleSubst);
1111        //}
1112
1113        //private char enigmaSpindle(char entrySubst)
1114        //{
1115
1116        //    char ch = entrySubst;
1117
1118
1119        //    // get the position of each rotor           
1120        //    int rotor1Pos = settings.Alphabet.IndexOf(currentKey[3]);
1121        //    int rotor2Pos = settings.Alphabet.IndexOf(currentKey[2]);
1122        //    int rotor3Pos = settings.Alphabet.IndexOf(currentKey[1]);
1123        //    int rotor4Pos = settings.Alphabet.IndexOf(currentKey[0]);
1124
1125
1126        //    //check notches and update the rotor position
1127        //    foreach (char n in rotor1notches)
1128        //    {
1129        //        if (n == currentKey[3]) rotor2Pos = (rotor2Pos + 1) % aLength;
1130        //    }
1131
1132        //    foreach (char n in rotor2notches)
1133        //    {
1134        //        if (n == currentKey[2]) rotor3Pos = (rotor3Pos + 1) % aLength;
1135        //    }
1136
1137        //    foreach (char n in rotor3notches)
1138        //    {
1139        //        if (n == currentKey[1]) rotor4Pos = (rotor4Pos + 1) % aLength;
1140        //    }
1141
1142        //    rotor1Pos = (rotor1Pos + 1) % aLength;
1143
1144        //    currentKey[3] = A[rotor1Pos];
1145        //    currentKey[2] = A[rotor2Pos];
1146        //    currentKey[1] = A[rotor3Pos];
1147        //    currentKey[0] = A[rotor4Pos];
1148
1149        //    // write back the updated rotor settings
1150        //    //settings.Key = new string(currentKey);
1151
1152        //    //add the ring-offset
1153        //    rotor1Pos = (aLength + rotor1Pos - (settings.Ring1 - 1)) % aLength;
1154        //    rotor2Pos = (aLength + rotor2Pos - (settings.Ring2 - 1)) % aLength;
1155        //    rotor3Pos = (aLength + rotor3Pos - (settings.Ring3 - 1)) % aLength;
1156
1157        //    // now do the substitution
1158        //    ch = A[aLength + A.IndexOf(rotor1For[aLength + A.IndexOf(ch) + rotor1Pos]) - rotor1Pos];
1159        //    ch = A[aLength + A.IndexOf(rotor2For[aLength + A.IndexOf(ch) + rotor2Pos]) - rotor2Pos];
1160        //    ch = A[aLength + A.IndexOf(rotor3For[aLength + A.IndexOf(ch) + rotor3Pos]) - rotor3Pos];
1161        //    ch = reflector[aLength + A.IndexOf(ch)];
1162        //    ch = A[aLength + A.IndexOf(rotor3Rev[aLength + A.IndexOf(ch) + rotor3Pos]) - rotor3Pos];
1163        //    ch = A[aLength + A.IndexOf(rotor2Rev[aLength + A.IndexOf(ch) + rotor2Pos]) - rotor2Pos];
1164        //    ch = A[aLength + A.IndexOf(rotor1Rev[aLength + A.IndexOf(ch) + rotor1Pos]) - rotor1Pos];
1165
1166        //    return ch;
1167        //}
1168
1169        //private string generateReverseSubst(string p)
1170        //{
1171        //    char[] result = new char[aLength];
1172
1173        //    for (int i = 0; i < aLength; i++)
1174        //    {
1175        //        result[i] = settings.Alphabet[p.IndexOf(settings.Alphabet[i])];
1176        //    }
1177
1178        //    return new string(result);
1179        //}
1180
1181        #endregion
1182
1183        #endregion
1184
1185        #region Contstructor
1186
1187        public Enigma()
1188        {
1189            this.settings = new EnigmaSettings();
1190            this.core = new EnigmaCore(this);
1191            this.analyzer = new EnigmaAnalyzer(this);
1192            this.analyzer.OnIntermediateResult += new EventHandler<IntermediateResultEventArgs>(analyzer_OnIntermediateResult);
1193        }
1194
1195        #endregion
1196
1197        #region Events
1198
1199#pragma warning disable 67
1200        public event StatusChangedEventHandler OnPluginStatusChanged;
1201#pragma warning restore
1202        public event GuiLogNotificationEventHandler OnGuiLogNotificationOccured;
1203        public event PluginProgressChangedEventHandler OnPluginProgressChanged;
1204       
1205        #endregion
1206
1207        #region IPlugin properties
1208
1209        public ISettings Settings
1210        {
1211            get { return this.settings; }
1212        }
1213
1214        public UserControl Presentation
1215        {
1216            get { return null; }
1217        }
1218
1219        public UserControl QuickWatchPresentation
1220        {
1221            get { return null; }
1222        }
1223
1224        #endregion
1225
1226        #region Connector properties
1227
1228        [PropertyInfo(Direction.Input, "Text input", "Input a string to be processed by the Enigma machine", "", true, false, DisplayLevel.Beginner, QuickWatchFormat.Text, null)]
1229        public string InputString
1230        {
1231            get { return this.inputString; }
1232            set
1233            {
1234                if (value != inputString)
1235                {
1236                    this.inputString = value;
1237                    OnPropertyChanged("InputString");
1238                }
1239            }
1240        }
1241
1242        [PropertyInfo(Direction.Output, "Text output", "The string after processing with the Enigma machine", "", false, false, DisplayLevel.Beginner, QuickWatchFormat.Text, null)]
1243        public string OutputString
1244        {
1245            get { return this.outputString; }
1246            set
1247            {
1248                outputString = value;
1249                OnPropertyChanged("OutputString");
1250            }
1251        }
1252
1253        #endregion
1254
1255        #region Public methods
1256
1257        public void PreExecution()
1258        {
1259            EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs("Preparing enigma for operation..", this,  NotificationLevel.Info));
1260
1261            if (settings.Model != 3)
1262            {
1263                EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs("This simulator is work in progress. As of right now only Enigma I is supported!!", this, NotificationLevel.Warning));
1264                return;
1265            }
1266
1267            // remember the current key-setting, in order to restore on stop
1268            savedKey = settings.Key;
1269
1270            //configure the enigma
1271            core.setInternalConfig(settings.Rotor1, settings.Rotor2, settings.Rotor3, settings.Rotor4,
1272                        settings.Reflector, settings.Ring1, settings.Ring2, settings.Ring3, settings.Ring4,
1273                        settings.PlugBoard);
1274           
1275            // re-set the stop-flag
1276            //stop = false;
1277        }
1278
1279        public void Execute()
1280        {
1281            if (inputString == null)
1282                return;
1283
1284
1285            if (settings.Model != 3)
1286            {
1287                LogMessage("This simulator is work in progress. As of right now only Enigma I is supported!!", NotificationLevel.Error);
1288                return;
1289            }
1290
1291           
1292
1293            switch (settings.Action)
1294            {
1295                case 0:
1296                    LogMessage("Enigma encryption/decryption started...", NotificationLevel.Info);
1297
1298                    // re-set the key, in case we get executed again during single run
1299                    settings.Key = savedKey;
1300
1301                    // do the encryption
1302                    outputString = FormattedEncrypt(settings.Alphabet.IndexOf(settings.Key[2]), 
1303                        settings.Alphabet.IndexOf(settings.Key[1]),
1304                        settings.Alphabet.IndexOf(settings.Key[0]), 
1305                        0, inputString);
1306
1307
1308                    LogMessage("Enigma encryption done. The resulting index of coincidences is " + analyzer.IndexOfCoincidences(outputString), NotificationLevel.Info);
1309
1310                    // "fire" the output
1311                    OnPropertyChanged("OutputString");
1312                    break;
1313                case 1:
1314                    LogMessage("Enigma analysis starting ...", NotificationLevel.Info);
1315
1316                    //prepare for analysis
1317                    LogMessage("ANALYSIS: Preformatting text...", NotificationLevel.Debug);
1318                    string preformatedText = preFormatInput(inputString);
1319
1320                    // perform the analysis
1321                    outputString = postFormatOutput(analyzer.Analyze(preformatedText));
1322                    OnPropertyChanged("OutputString");
1323
1324                    ShowProgress(1000, 1000);
1325                   
1326                    // old version
1327                    //runAnalysis(inputString);
1328                    break;
1329                default:
1330                    break;
1331            }
1332
1333        }
1334
1335        public void PostExecution()
1336        {
1337            LogMessage("Enigma shutting down. Reverting key to inial value!", NotificationLevel.Info);
1338            if (savedKey.Length > 0)
1339            {
1340                settings.Key = savedKey; // re-set the key
1341            }
1342           
1343        }
1344
1345        public void Pause()
1346        {
1347            LogMessage("The \"Pause\"-Feature is not implemented!", NotificationLevel.Warning);
1348        }
1349
1350        public void Stop()
1351        {
1352            LogMessage("Enigma stopped", NotificationLevel.Info);
1353            //stop = true;
1354            analyzer.StopAnalysis();
1355        }
1356
1357        public void Initialize()
1358        {
1359            LogMessage("Initialize", NotificationLevel.Debug);
1360        }
1361
1362        public void Dispose()
1363        {
1364            LogMessage("Dispose", NotificationLevel.Debug);
1365        }
1366
1367
1368
1369        /// <summary>
1370        /// Logs a message to the Cryptool console
1371        /// </summary>
1372        public void LogMessage(string msg, NotificationLevel level)
1373        {
1374            EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(msg, this, level));
1375        }
1376
1377        /// <summary>
1378        /// Sets the progress bar for this plugin
1379        /// </summary>
1380        /// <param name="val"></param>
1381        /// <param name="max"></param>
1382        public void ShowProgress(double val, double max)
1383        {
1384            EventsHelper.ProgressChanged(OnPluginProgressChanged, this, new PluginProgressEventArgs(val, max));
1385        }
1386
1387        /// <summary>
1388        /// Returns a formated string with all plugs from a given substitution string
1389        /// This method should be move to some more adequate place
1390        /// </summary>
1391        /// <param name="pb">The substitution string for a plugboard</param>
1392        /// <returns>A list of plugs</returns>
1393        public string pB2String(string pb)
1394        {
1395            if (pb.Length != settings.Alphabet.Length)
1396                return "-- no plugs --";
1397
1398
1399            StringBuilder result = new StringBuilder();
1400
1401            for (int i = 0; i < settings.Alphabet.Length; i++)
1402            {
1403                if (settings.Alphabet[i] != pb[i] && !result.ToString().Contains(settings.Alphabet[i]))
1404                {
1405                    if (result.Length > 0)
1406                        result.Append(' ');
1407
1408                    result.Append(settings.Alphabet[i].ToString() + pb[i].ToString());
1409                }
1410            }
1411
1412            if (result.Length == 0)
1413                result.Append("-- no plugs --");
1414
1415            return result.ToString();
1416        }
1417
1418        #endregion
1419
1420        #region INotifyPropertyChanged Member
1421
1422        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
1423
1424        public void OnPropertyChanged(string name)
1425        {
1426            EventsHelper.PropertyChanged(PropertyChanged, this, new PropertyChangedEventArgs(name));
1427        }
1428
1429        #endregion
1430    }
1431}
Note: See TracBrowser for help on using the repository browser.