public void EnigmaMachine_ShouldDecodeWord_WithRotors123()
        {
            // Arrange
            var enigmaMachine = new EnigmaMachine();

            enigmaMachine.ChooseRotors(RotorNumber.Rotor1, RotorNumber.Rotor2, RotorNumber.Rotor3);
            enigmaMachine.SetRotorDials('a', 'a', 'z');

            enigmaMachine.SetPlugboardPair('h', 's');
            enigmaMachine.SetPlugboardPair('a', 'e');
            enigmaMachine.SetPlugboardPair('d', 'j');
            enigmaMachine.SetPlugboardPair('p', 'q');
            enigmaMachine.SetPlugboardPair('g', 'm');
            enigmaMachine.SetPlugboardPair('b', 'c');
            enigmaMachine.SetPlugboardPair('f', 'i');
            enigmaMachine.SetPlugboardPair('k', 'n');
            enigmaMachine.SetPlugboardPair('l', 'o');
            enigmaMachine.SetPlugboardPair('r', 't');

            // Act
            string encodedMessage = enigmaMachine.Encode("hello");

            // Assert
            Assert.AreEqual("ocfkj", encodedMessage);
        }
        public void EnigmaMachine_InitializedWithStaticFactory_IsNotNull()
        {
            var enigmaMachine = EnigmaMachine.Default();

            enigmaMachine.Should()
            .NotBeNull();
        }
Esempio n. 3
0
        public HttpResponseMessage Encrypt([FromBody] EnigmaMachineDto enigmaMachineDto, [FromUri] bool leaveWhiteSpace)
        {
            HttpResponseMessage response;
            EnigmaMachine       enigmaMachine;

            try
            {
                enigmaMachine = new EnigmaMachine();
                enigmaMachine.SetPlugboard(enigmaMachineDto.Plugboard.Wiring);

                enigmaMachine.ChooseRotors(
                    (RotorNumber)enigmaMachineDto.Rotor1.RotorNum,
                    (RotorNumber)enigmaMachineDto.Rotor2.RotorNum,
                    (RotorNumber)enigmaMachineDto.Rotor3.RotorNum);

                enigmaMachine.SetRotorDials(
                    enigmaMachineDto.Rotor1.InitialDialSetting,
                    enigmaMachineDto.Rotor2.InitialDialSetting,
                    enigmaMachineDto.Rotor3.InitialDialSetting);

                enigmaMachine.LeaveWhiteSpace(leaveWhiteSpace);

                string encodedMessage = enigmaMachine.Encode(enigmaMachineDto.Text);

                response = Request.CreateResponse(HttpStatusCode.OK, encodedMessage);
            }
            catch (Exception ex)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }

            return(response);
        }
Esempio n. 4
0
        public static void Encrypt_Decrypt(string fRo, string mRo, string sRo, string Ref, string[] steckers, int fRi, int mRi, int sRi, int fGr, int mGr, int sGr, string text)
        {
            Enigma_Settings = new EnigmaSettings();
            Enigma          = new EnigmaMachine(fRo, mRo, sRo, Ref, Enigma_Settings);

            text = text.Replace(" ", "").ToUpper();

            if (!Regex.IsMatch(text, @"^[a-zA-Z ]+$"))
            {
                EnigmaWindow.setText("You can only enter letters, no numbers, not special tokens. Try again.");
                return;
            }

            if (!steckers[0].Equals(""))
            {
                Enigma.setSteckers(steckers);
            }

            Enigma_Settings.storeRings(fRi, mRi, sRi);
            Enigma_Settings.storeGround(fGr, mGr, sGr);

            Enigma.setSettings(Enigma_Settings.rings, Enigma_Settings.grund);

            printResult(text);

            /*Debugging, make sure that the ring setting is taken correctly.
             * Enigma_Settings.rings[0] = (Char)(sRi + 64);
             *
             * EnigmaWindow.setChar(Enigma_Settings.rings[0]);*/
        }
Esempio n. 5
0
    private void AcceptChar(char chr)
    {
        if (!EnigmaMachine.IsValidKey(chr))
        {
            return;
        }

        PressKey(chr);
        UpdateVisuals();
    }
        static void Main(string[] args)
        {
            EnigmaMachine enigmaMachine = new EnigmaMachine();

            enigmaMachine.SetPlugboardPair('h', 's');
            enigmaMachine.SetPlugboardPair('a', 'e');
            enigmaMachine.SetPlugboardPair('d', 'j');
            enigmaMachine.SetPlugboardPair('p', 'q');
            enigmaMachine.SetPlugboardPair('g', 'm');
            enigmaMachine.SetRotorDials('a', 'a', 'z');
            Console.WriteLine(enigmaMachine.Encode("hello"));
        }
        public void TestInitialize()
        {
            enigmaMachine = new EnigmaMachine();
            enigmaMachine.ChooseRotors(RotorNumber.Rotor1, RotorNumber.Rotor2, RotorNumber.Rotor3);

            enigmaMachine.SetPlugboardPair('h', 's');
            enigmaMachine.SetPlugboardPair('a', 'e');
            enigmaMachine.SetPlugboardPair('d', 'j');
            enigmaMachine.SetPlugboardPair('p', 'q');
            enigmaMachine.SetPlugboardPair('g', 'm');
            enigmaMachine.SetRotorDials('a', 'a', 'z');
        }
Esempio n. 8
0
    private void PressKey(char chr)
    {
        char result = machine.PressKey(chr);

        AppendOutputChar(result);

        int keyIndex = EnigmaMachine.CharToIndex(chr);

        if (keyPressRoutines[keyIndex] == null)
        {
            keyPressRoutines[keyIndex] = StartCoroutine(CoPressKey(keyIndex));
        }

        audioSource.PlayOneShot(clickSound);
    }
Esempio n. 9
0
        /// <summary>
        /// Update, then show the Enigma Selection menu.
        /// </summary>
        public static void EnigmaSelectionMenu()
        {
            Debug.LogMethodStart();
            UpdateEnigmaSelectionMenu();

            Selection.DisplayItems("Enigma Selection Menu", false);
            int           choice = Selection.ItemSelect();
            EnigmaMachine old    = null;

            // using if/else instead of switch, because switch needs constant values
            if (choice == 0) // Choice was new from settings
            {
                string settings = UserInput.GetFilePathFromUser("enigma settings file", new string[] { ".xml" }, true);
                if (settings != null)
                {
                    old = EnigmaMachine.Current;
                    EnigmaMachine.Current = new EnigmaMachine(new FileInput(settings).GetEnigmaSettings());
                }
            }
            else if (choice == 1) // Choice was new from manual input
            {
                old = EnigmaMachine.Current;
                EnigmaMachine.Current = UserInput.ManualEnigmaCreation();
            }
            // (Items.Count - 3) because the last item is always Exit in Menu instances and 2nd to last in this case is To Main Menu
            else if (choice <= Selection.Items.Count - 3 && choice >= 2) // choice was from list of other machines
            {
                old = EnigmaMachine.Current;
                // Using choice - 2 as index because the first 2 choices in the menu are not other machines
                // e.g. to select the first enigma machine in OtherMachines we need index 0, but choice would be 2 here
                EnigmaMachine.Current = EnigmaMachine.OtherMachines[choice - 2];
            }

            // This check and the next is probably a good bit slower than using a hashtable (e.g. System.Collections.Generic.Dictionary)
            // but that shouldn't matter since OtherMachines.Count should be small-ish (i.e. iterating over it for Contains & Any should be fast)
            // I can always change it if necessary.
            if (old != null && !EnigmaMachine.OtherMachines.Contains(old))
            {
                EnigmaMachine.OtherMachines.Add(old);
            }
            if (EnigmaMachine.OtherMachines.Any(em => em == EnigmaMachine.Current))
            {
                EnigmaMachine.OtherMachines.Remove(EnigmaMachine.Current);
            }

            // All choices lead here (the "To Main Menu" choice goes straight here) excluding the Exit choice (which is the final choice in all Menu instances).
            MainMenu(false);
        }
        public void EnigmaMachine_ShouldDecodeWordWithSpaces_WithRotors531()
        {
            // Arrange
            var enigmaMachine = new EnigmaMachine();

            enigmaMachine.ChooseRotors(RotorNumber.Rotor5, RotorNumber.Rotor3, RotorNumber.Rotor1);
            enigmaMachine.SetRotorDials('g', 'j', 'n');
            enigmaMachine.SetPlugboard(plugboardWiring);
            string plainText = "dalliance chatoyant";

            // Act
            string encodedMessage = enigmaMachine.Encode(plainText);

            // Assert
            enigmaMachine.SetRotorDials('g', 'j', 'n');
            Assert.AreEqual("jyssqzldhgqubgkoji", encodedMessage);
            Assert.AreEqual(plainText.Replace(" ", ""), enigmaMachine.Encode(encodedMessage));
        }
        public void EnigmaMachine_ShouldDecodeWordWithSpaces_WithRotors312()
        {
            // Arrange
            var enigmaMachine = new EnigmaMachine();

            enigmaMachine.ChooseRotors(RotorNumber.Rotor3, RotorNumber.Rotor1, RotorNumber.Rotor2);
            enigmaMachine.SetRotorDials('g', 'j', 'n');
            enigmaMachine.SetPlugboard(plugboardWiring);
            string plainText = "forbearance";

            // Act
            string encodedMessage = enigmaMachine.Encode(plainText);

            // Assert
            enigmaMachine.SetRotorDials('g', 'j', 'n');
            Assert.AreEqual("jiekfqfgkxz", encodedMessage);
            Assert.AreEqual(plainText, enigmaMachine.Encode(encodedMessage));
        }
        public void EnigmaMachine_ShouldDecodeWord_WithRotors345()
        {
            // Arrange
            var enigmaMachine = new EnigmaMachine();

            enigmaMachine.ChooseRotors(RotorNumber.Rotor3, RotorNumber.Rotor4, RotorNumber.Rotor5);
            enigmaMachine.SetRotorDials('b', 'c', 'd');
            enigmaMachine.SetPlugboard(plugboardWiring);
            string plainText = "cynosure";

            // Act
            string encodedMessage = enigmaMachine.Encode(plainText);

            // Assert
            enigmaMachine.SetRotorDials('b', 'c', 'd');
            Assert.AreEqual("oswemtyt", encodedMessage);
            Assert.AreEqual(plainText, enigmaMachine.Encode(encodedMessage));
        }
        public void EnigmaMachine_ShouldDecodeWord_WithRotors531()
        {
            // Arrange
            var enigmaMachine = new EnigmaMachine();

            enigmaMachine.ChooseRotors(RotorNumber.Rotor5, RotorNumber.Rotor3, RotorNumber.Rotor1);
            enigmaMachine.SetRotorDials('b', 'j', 'n');
            enigmaMachine.SetPlugboard(plugboardWiring);
            string plainText = "dalliance";

            // Act
            string encodedMessage = enigmaMachine.Encode(plainText);

            // Assert
            enigmaMachine.SetRotorDials('b', 'j', 'n');
            Assert.AreEqual("iymhgqkat", encodedMessage);
            Assert.AreEqual(plainText, enigmaMachine.Encode(encodedMessage));
        }
        public void EnigmaMachine_ShouldDecodeWord_WithRotors234()
        {
            // Arrange
            var enigmaMachine = new EnigmaMachine();

            enigmaMachine.ChooseRotors(RotorNumber.Rotor2, RotorNumber.Rotor3, RotorNumber.Rotor4);
            enigmaMachine.SetRotorDials('a', 'b', 'c');
            enigmaMachine.SetPlugboard(plugboardWiring);
            string plainText = "bungalow";

            // Act
            string encodedMessage = enigmaMachine.Encode(plainText);

            // Assert
            enigmaMachine.SetRotorDials('a', 'b', 'c');
            Assert.AreEqual("noavbjhg", encodedMessage);
            Assert.AreEqual(plainText, enigmaMachine.Encode(encodedMessage));
        }
Esempio n. 15
0
        public void ProcessTest_EnigmaI_I_II_III_RefB_ABDEYZ_AAA()
        {
            var rotors = EnigmaRotor.Rotors
                         .Where(r => r.Series == "Enigma I" &&
                                new[] { "I", "II", "III" }.Contains(r.Number))
                         .ToArray();
            var reflector = EnigmaReflector.Reflectors
                            .First(r => r.Number == "Reflector B");

            var em = new EnigmaMachine(rotors, reflector);

            em.PlugBoard = "AB DE YZ";
            var start = em.Position = "AAA";

            var ret = em.Process("AAAAA");

            Assert.AreEqual("BJLCS", ret);
        }
        public void EnigmaMachine_ShouldDecodeWordWithCapsAndSpaces_WithRotors123()
        {
            // Arrange
            var enigmaMachine = new EnigmaMachine();

            enigmaMachine.ChooseRotors(RotorNumber.Rotor1, RotorNumber.Rotor2, RotorNumber.Rotor3);
            enigmaMachine.SetRotorDials('a', 'a', 'z');
            enigmaMachine.SetPlugboard(plugboardWiring);
            string plainText = "They call Me Mr Tibbs";

            // Act
            string encodedMessage = enigmaMachine.Encode(plainText);

            // Assert
            enigmaMachine.SetRotorDials('a', 'a', 'z');
            Assert.AreEqual("gdjwbtngooygonlym", encodedMessage);
            Assert.AreEqual(plainText.ToLower().Replace(" ", ""), enigmaMachine.Encode(encodedMessage));
        }
Esempio n. 17
0
    private void AcceptString(string input)
    {
        bool changed = false;

        foreach (char chr in input.ToUpper())
        {
            if (!EnigmaMachine.IsValidKey(chr))
            {
                continue;
            }

            PressKey(chr);
            changed = true;
        }

        if (changed)
        {
            UpdateVisuals();
        }
    }
Esempio n. 18
0
    private void Update()
    {
        AcceptString(Input.inputString);

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit) && hit.transform.CompareTag("Key"))
            {
                int index = Array.IndexOf(keys, hit.transform);
                if (index == -1)
                {
                    return;
                }

                char chr = EnigmaMachine.IndexToChar(index);
                if (EnigmaMachine.IsValidKey(chr))
                {
                    AcceptChar(chr);
                }
            }
        }
    }
Esempio n. 19
0
        public ViewModel()
        {
            this.Enigma = new EnigmaMachine();

            One   = new Command(() => { Input = 1; RunEnigma(); }, () => { return(true); });
            Two   = new Command(() => { Input = 2; RunEnigma(); }, () => { return(true); });
            Three = new Command(() => { Input = 3; RunEnigma(); }, () => { return(true); });
            Four  = new Command(() => { Input = 4; RunEnigma(); }, () => { return(true); });
            Five  = new Command(() => { Input = 5; RunEnigma(); }, () => { return(true); });
            Six   = new Command(() => { Input = 6; RunEnigma(); }, () => { return(true); });
            Seven = new Command(() => { Input = 7; RunEnigma(); }, () => { return(true); });
            Eight = new Command(() => { Input = 8; RunEnigma(); }, () => { return(true); });
            Nine  = new Command(() => { Input = 9; RunEnigma(); }, () => { return(true); });

            Rotor3Up   = new Command(() => { Enigma.Rotor3.Rotate(); UpdateRotors(); }, () => { return(true); });
            Rotor3Down = new Command(() => { Enigma.Rotor3.RotateBack(); UpdateRotors(); }, () => { return(true); });
            Rotor2Up   = new Command(() => { Enigma.Rotor2.Rotate(); UpdateRotors(); }, () => { return(true); });
            Rotor2Down = new Command(() => { Enigma.Rotor2.RotateBack(); UpdateRotors(); }, () => { return(true); });
            Rotor1Up   = new Command(() => { Enigma.Rotor1.Rotate(); UpdateRotors(); }, () => { return(true); });
            Rotor1Down = new Command(() => { Enigma.Rotor1.RotateBack(); UpdateRotors(); }, () => { return(true); });

            Clear = new Command(() => { this.Output = ""; }, () => { return(true); });
        }
Esempio n. 20
0
 public void SetUp()
 {
     _enigmaMachine = new EnigmaMachine(new[] {1, 2, 3}, new[] {'M', 'C', 'K'});
 }
Esempio n. 21
0
 private void Form1_Load(object sender, EventArgs e)
 {
     machine = new EnigmaMachine((uint)nudSlow.Value, (uint)nudMedium.Value, (uint)nudFast.Value);
 }
Esempio n. 22
0
        /// <summary>
        /// Update, then show the settings Menu.
        /// </summary>
        public static void SettingsMenu()
        {
            Debug.LogMethodStart();
            UpdateSettingsMenu();

            Settings.DisplayItems("Settings Menu", false);
            int choice = Settings.ItemSelect();

            switch (choice)
            {
            case 0:     // Choice was change folder
                Environment.CurrentDirectory = UserInput.GetFolderFromUser();
                break;

            case 1:     // Choice was change log file
                Debug.LogPath       = UserInput.GetFilePathFromUser("log", new string[] { ".log" }, false);
                Utility.isLoggingOn = true;
                break;

            case 2:     // Choice was change enigma machine
                EnigmaSelectionMenu();
                break;

            case 3:     // Choice was change input
                string input = UserInput.GetFilePathFromUser("text input", new string[] { ".txt", ".html" }, true);
                if (input == null)
                {
                    input = "keyboard";
                }
                EnigmaMachine.Current.InputType = Validation.GetInputExtensionType(input);
                EnigmaMachine.Current.FileIn    = Path.ChangeExtension(input, null);
                break;

            case 4:     // Choice was change output
                EnigmaMachine.Current.FileOut = UserInput.GetFilePathFromUser("text output", new string[] { ".html" }, false);
                // assume that if user sets output that they don't want auto-generated output paths anymore
                shouldGenerateOutputPath = false;
                break;

            case 5:     // Choice was change cipher type
                EnigmaMachine.Current.IsDecrypting = !EnigmaMachine.Current.IsDecrypting;
                break;

            case 6:     // Choice was return to main menu
                MainMenu(false);
                break;

            // Final choice (7) is always exit program
            default:     // Choice was invalid (shouldn't be possible since Menu.ItemSelect includes validation)
                break;
            }

            // Generate a new output path for the current enigma machine, unless user has manually set output path
            if (shouldGenerateOutputPath)
            {
                EnigmaMachine.Current.FileOut = EnigmaMachine.GetOutputPath();
            }

            // Display settings menu again if choice was not main menu
            SettingsMenu();
        }
Esempio n. 23
0
 public void BecauseOf()
 {
     _rotar1 = new Rotar(1, 'A');
     _rotar2 = new Rotar(2, 'B');
     _rotar3 = new Rotar(3, 'C');
     var rotarFactory = new Mock<IRotarFactory>();
     rotarFactory.Setup(x => x.GetRotar(1, 'A')).Returns(_rotar1);
     rotarFactory.Setup(x => x.GetRotar(2, 'B')).Returns(_rotar2);
     rotarFactory.Setup(x => x.GetRotar(3, 'C')).Returns(_rotar3);
     _enigmaMachine = new EnigmaMachine(rotarFactory.Object, new []{ 1, 2, 3 }, new []{ 'A', 'B', 'C' });
 }
Esempio n. 24
0
        static void Main(string[] args)
        {
            enigmaMachine = EnigmaMachine.Create();

            //create reflector disc
            var reflector = new Disc(6);

            //connect the reflector nodes
            Node.Connect(reflector.Nodes[0], reflector.Nodes[3]);
            Node.Connect(reflector.Nodes[1], reflector.Nodes[5]);
            Node.Connect(reflector.Nodes[2], reflector.Nodes[4]);


            //add reflector to machine (must do this before adding rotors)
            enigmaMachine.ReflectorDisc = reflector;

            //create two rotors (could add as many as we like)
            var r1 = new Rotor(6);
            var r2 = new Rotor(6);

            //manually connect rotor nodes
            Node.Connect(r1.LeftDisc.Nodes[0], r1.RightDisc.Nodes[3]);
            Node.Connect(r1.LeftDisc.Nodes[1], r1.RightDisc.Nodes[1]);
            Node.Connect(r1.LeftDisc.Nodes[2], r1.RightDisc.Nodes[2]);
            Node.Connect(r1.LeftDisc.Nodes[3], r1.RightDisc.Nodes[0]);
            Node.Connect(r1.LeftDisc.Nodes[4], r1.RightDisc.Nodes[4]);
            Node.Connect(r1.LeftDisc.Nodes[5], r1.RightDisc.Nodes[5]);

            Node.Connect(r2.LeftDisc.Nodes[0], r2.RightDisc.Nodes[0]);
            Node.Connect(r2.LeftDisc.Nodes[1], r2.RightDisc.Nodes[5]);
            Node.Connect(r2.LeftDisc.Nodes[2], r2.RightDisc.Nodes[4]);
            Node.Connect(r2.LeftDisc.Nodes[3], r2.RightDisc.Nodes[2]);
            Node.Connect(r2.LeftDisc.Nodes[4], r2.RightDisc.Nodes[3]);
            Node.Connect(r2.LeftDisc.Nodes[5], r2.RightDisc.Nodes[1]);

            //create a couple of letter rings and move move them around a bit...
            var lr1 = LetterRing.FromAlphabet("ABCDEF"); lr1.MoveUp().MoveUp();
            var lr2 = LetterRing.FromAlphabet("ABCDEF"); lr2.MoveDown().MoveDown().MoveDown();

            //output when we move the rotor
            lr1.VisibleLetterChanged += letterRing_VisibleLetterChanged;
            lr2.VisibleLetterChanged += letterRing_VisibleLetterChanged;


            //fix the letter rings onto our rotors
            r1.LetterRing = lr1;
            r2.LetterRing = lr1;

            //insert rotors into machine
            enigmaMachine.InsertRotor(r1);
            enigmaMachine.InsertRotor(r2);

            //create a (default node mapping) plugboard and insert into machine
            enigmaMachine.InsertPlugboard(new Plugboard(6));

            //test the letter rings (moving the rotor should change letter rings visible rotors)
            r1.MoveUp().MoveUp().MoveUp().MoveUp().MoveUp();

            //create a keyboard and lampboard - these are not part of the "machine" as such.  Hook up with events
            var keyboard  = Keyboard.FromAlphabet("ABCDEF");
            var lampboard = Lightboard.FromAlphabet("ABCDEF");

            keyboard.KeyPressed += (sender, e) =>
            {
                int pin = (int)sender;
                enigmaMachine.Plugboard.ElectrifyPin(pin);
            };

            enigmaMachine.Plugboard.PinElectrified += (sender, e) =>
            {
                lampboard.LightLamp((int)sender);
            };

            lampboard.LampOn += (sender, e) =>
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(" => {0}", (char)sender);
            };


            Console.WriteLine("Enter a character to be encoded, or a rotor number to move");
            while (1 == 1)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                char inputKey = Console.ReadKey(false).KeyChar;

                int intInput;
                if (int.TryParse(inputKey.ToString(), out intInput))
                {
                    Console.WriteLine("Rotating rotor {0}", intInput);
                    enigmaMachine.Rotors[intInput].MoveDown();
                }
                else
                {
                    keyboard.PressKey(char.ToUpper(inputKey));
                }
            }
        }
Esempio n. 25
0
 public void BecauseOf()
 {
     var rotarFactory = _SetupRotars();
     var enigmaMachine = new EnigmaMachine(rotarFactory.Object, new []{ 1, 2, 3 }, new []{ 'M', 'C', 'K' });
     _result = enigmaMachine.Convert('E');
 }