Example #1
0
        public static void EncryptCodeAndAddKey(NewPE PE)
        {
            byte[] pKey = new byte[16];
            Keys.PopulateBuffer(pKey);

            byte[] pRunPE = PE.PeDirectory.RunPEObjectPath.ReadBytes();
            Xor.EncodeDecodeData(pRunPE, pKey);

            if (File.Exists(PE.PeDirectory.RunPEObjectPath))
            {
                File.Delete(PE.PeDirectory.RunPEObjectPath);
            }

            PE.PeDirectory.RunPEObjectPath.WriteFile(pRunPE);

            string KeyInclude = Path.Combine(PE.PeDirectory.IncludeDirectory, "runpe_key.inc");
            string Format     = pKey.ToASMBuffer();

            if (File.Exists(KeyInclude))
            {
                File.Delete(KeyInclude);
            }

            File.WriteAllText(KeyInclude, Format);

            PEFactory.CompileDataSection(PE);
        }
Example #2
0
        public void HexStrings()
        {
            const string x = "4154"; // 65 84
            const string y = "534f"; // 83 79

            Xor.HexStrings(x, y).Should().Be("121b");
        }
Example #3
0
        static void Main(string[] args)
        {
            const char a = ((char) 'a');
            const int z = a + 26;
            var xor = new Xor();
            const string statement = "5\nA\b\bA\0\rA\f";
            var cipherTxt = string.Concat(File
                                              .ReadAllText(@"C:\dev\Kata\Euler\EulerProblem59.App\cipher1.txt")
                                              .Split(new[] {","}, StringSplitOptions.None)
                                              .Select(x => Convert.ToString((char)Convert.ToInt32(x))));
            var matchFound = false;

            for (var i = a; i < z; i++)
            {
                for (var j = a; j < z; j++)
                {
                    for (var k = a; k < z; k++)
                    {
                        var result = xor.Decrypt(cipherTxt, new[] { i, j, k });
                        if (!result.ToLower().Contains("there")) continue;
                        var sum = result.ToCharArray().Sum(x => (int) x);
                        Console.WriteLine("The key is: {0}{1}{2}", i, j, k);
                        Console.WriteLine("The sum of the ascii values are: {0}", sum);
                        Console.WriteLine("The text is as follows:\r\n\r\n{0}\r\n\r\n", result);
                        matchFound = true;
                        break;
                    }
                }
            }

            Console.WriteLine(matchFound ? "Finished." : "No match found.");
            Console.ReadKey();
        }
Example #4
0
        public void Challenge4() // find single-byte XOR ciphertext & brute force
        {
            var cipherTexts = File.ReadAllLines("TestData/Set1/4.txt");

            string xoredCipherText     = null;
            string plainTextValue      = null;
            double currentHighestScore = 0;

            foreach (var cipherText in cipherTexts.ToList())
            {
                var plaintextValues = Xor.BruteForceSingleByte(cipherText);

                foreach (var attempt in plaintextValues)
                {
                    var rating = LetterAnalyzer.EnglishRating(attempt.Value);
                    if (currentHighestScore < rating)
                    {
                        xoredCipherText     = cipherText;
                        plainTextValue      = attempt.Value;
                        currentHighestScore = rating;
                    }
                }
            }

            xoredCipherText.Should().Be("7b5a4215415d544115415d5015455447414c155c46155f4058455c5b523f");
            plainTextValue.Should().Be("Now that the party is jumping\n");
        }
Example #5
0
        public void ByteArrays()
        {
            var x = new byte[] { 65, 84 };
            var y = new byte[] { 83, 79 };

            Xor.ByteArrays(x, y).Should().BeEquivalentTo(new byte[] { 18, 27 });
        }
Example #6
0
        public void Challenge02_FixedXOR()
        {
            var xored = Xor.ApplyFixed(Hex.ToBytes("1c0111001f010100061a024b53535009181c"), Hex.ToBytes("686974207468652062756c6c277320657965"));

            Assert.Equal("746865206b696420646f6e277420706c6179",
                         BitConverter.ToString(xored).Replace("-", "").ToLowerInvariant());
        }
Example #7
0
        static void XOR()
        {
            //begin XOR problem
            //4 inputs of 1 or so
            // 0 0 = 0
            // 0 1 = 1
            // 1 0 = 1
            // 1 1 = 0

            Console.WriteLine("Executing");

            int    numberOfTests = 500000;
            var    testList      = new List <Xor>();
            Random rnd           = new Random();

            for (int i = 0; i < numberOfTests; i++)
            {
                testList.Add(new Xor(rnd));
            }

            LMMCNet lMMCNet = new LMMCNet(2, 3, new int[] { 10, 10, 2 }, 1, rnd);
            LMMCNet net     = new LMMCNet(2, 3, new int[] { 10, 10, 2 }, 1, rnd);

            foreach (Xor x in testList)
            {
                lMMCNet.Train(new double[] { x.a, x.b }, x.Expected);
            }

            int    worked = 0;
            int    failed = 0;
            double result = 0;
            Random random = new Random();
            int    count  = 0;

            while (count < 5000000)
            {
                Xor x = new Xor(random);
                Console.WriteLine(count);
                lMMCNet.Train(new double[] { x.a, x.b }, x.Expected);
                result = lMMCNet.Net[lMMCNet.Net.Count() - 1][0].OutValue;
                Console.WriteLine("result is {0}, expected is {1}", (result), x.Expected[0]);

                if (result.ToString() == "0.8" && x.Expected[0].ToString() == "0.8" || result.ToString() == "0.2" && x.Expected[0].ToString() == "0.2")
                {
                    worked++;
                }
                else
                {
                    failed++;
                }

                Hessian(lMMCNet.Net);
                count++;
            }

            Console.WriteLine("{0} sucesses, {1} fails", worked, failed);
            Console.WriteLine("Compiled successfully");
            Thread.Sleep(5000);
            Console.ReadLine();
        }
Example #8
0
        public void XorShouldReturnCorrectResult()
        {
            var func   = new Xor();
            var args   = FunctionsHelper.CreateArgs(true, false);
            var result = func.Execute(args, ParsingContext.Create());

            Assert.IsTrue((bool)result.Result);

            args   = FunctionsHelper.CreateArgs(false, false);
            result = func.Execute(args, ParsingContext.Create());
            Assert.IsFalse((bool)result.Result);

            args   = FunctionsHelper.CreateArgs(true, true);
            result = func.Execute(args, ParsingContext.Create());
            Assert.IsFalse((bool)result.Result);

            using (var package = new ExcelPackage())
            {
                var sheet = package.Workbook.Worksheets.Add("test");
                sheet.Cells["A1"].Value   = true;
                sheet.Cells["A2"].Value   = 0;
                sheet.Cells["A3"].Formula = "XOR(A1:A2,DATE(2020,12,10))";
                sheet.Calculate();
                Assert.IsFalse((bool)sheet.Cells["A3"].Value);
            }
        }
Example #9
0
        public void TestRobBase64Decryption()
        {
            var b64     = Base64.Encode("If this text is readable then the test has succeeded!");
            var encoded = Xor.Cipher(b64, key);

            Assert.AreEqual("If this text is readable then the test has succeeded!", RobBase64.Decode(encoded, key), "No u");
        }
Example #10
0
        /// <summary>
        /// Apply the optimization.
        /// </summary>
        /// <param name="instructions">Instructions.</param>
        public override void Apply(List <Assembler.Instruction> instructions)
        {
            // Iterate over the instructions
            for (int index = 0; index < instructions.Count; index++)
            {
                var instr = instructions [index] as Mov;

                // Continue if the instruction is not a 'MOV' instruction.
                if (instr == null)
                {
                    continue;
                }

                // Test if all requirements are met
                if (instr.DestinationReg.HasValue &&
                    !instr.DestinationIndirect &&
                    instr.SourceRef == "0x0")
                {
                    // Replace 'MOV' by faster 'XOR'
                    instructions [index] = new Xor {
                        SourceReg      = instr.DestinationReg,
                        DestinationReg = instr.DestinationReg,
                        Size           = instr.Size
                    };
                }
            }
        }
Example #11
0
        static void BinaryNetXOR()
        {
            //begin XOR problem
            //4 inputs of 1 or so
            // 0 0 = 0
            // 0 1 = 1
            // 1 0 = 1
            // 1 1 = 0

            Console.WriteLine("Executing");

            int    numberOfTests = 500000;
            var    testList      = new List <Xor>();
            Random rnd           = new Random();

            for (int i = 0; i < numberOfTests; i++)
            {
                testList.Add(new Xor(rnd));
            }

            var factory = new BinaryNetFactory(new double[] { 0.1, 0.9 },
                                               2, new int[] { 10, 10, 2 }, rnd);

            foreach (Xor x in testList)
            {
                factory.Train(new double[] { x.a, x.b }, x.Expected[0]);
            }

            int    worked = 0;
            int    failed = 0;
            double result = 0;
            Random random = new Random();
            int    count  = 0;

            while (count < 500000)
            {
                Xor x = new Xor(random);
                Console.WriteLine(count);
                factory.Train(new double[] { x.a, x.b }, x.Expected[0]);
                result = factory.Predict(new double[] { x.a, x.b })[0];
                Console.WriteLine("result is {0}, expected is {1}", (result), x.Expected[0]);

                if (result.ToString() == x.Expected[0].ToString())
                {
                    worked++;
                }
                else
                {
                    failed++;
                }

                count++;
            }

            Console.WriteLine("{0} sucesses, {1} fails", worked, failed);
            Console.WriteLine("Compiled successfully");
            Thread.Sleep(5000);
            Console.ReadLine();
        }
Example #12
0
        public void Challenge03_SingleByteBreakXOR()
        {
            var bytes     = Hex.ToBytes("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
            var bestMatch = Xor.XorBestMatch(bytes).First();
            var plainText = Encoding.UTF8.GetString(Xor.ApplyRepeating(bytes, new [] { bestMatch.key }));

            Assert.Equal("Cooking MC's like a pound of bacon", plainText);
        }
Example #13
0
        public void Challenge2() // XOR
        {
            const string hex1     = "1c0111001f010100061a024b53535009181c";
            const string hex2     = "686974207468652062756c6c277320657965";
            const string expected = "746865206b696420646f6e277420706c6179";

            Xor.HexStrings(hex1, hex2).Should().Be(expected);
        }
Example #14
0
        public void EncryptTest()
        {
            Xor xor = new Xor(0xab);

            Assert.AreEqual <byte>(xor.Encrypt(new byte[] { 0xba, 0xda, 0xff })[0], 0x11);
            Assert.AreEqual <byte>(xor.Encrypt(new byte[] { 0xba, 0xda, 0xff })[1], 0x71);
            Assert.AreEqual <byte>(xor.Encrypt(new byte[] { 0xba, 0xda, 0xff })[2], 0x54);
        }
Example #15
0
        public void DecryptTest()
        {
            Xor xor = new Xor(0xab);

            Assert.AreEqual <byte>(xor.Decrypt(new byte[] { 0x11, 0x71, 0x54 })[0], 0xba);
            Assert.AreEqual <byte>(xor.Decrypt(new byte[] { 0x11, 0x71, 0x54 })[1], 0xda);
            Assert.AreEqual <byte>(xor.Decrypt(new byte[] { 0x11, 0x71, 0x54 })[2], 0xff);
        }
Example #16
0
        public void LoadUserData()
        {
            var foundData = false;

#if (UNITY_IOS || UNITY_ANDROID)
            var stringFromPlayerPrefs = PlayerPrefs.GetString(PlayerPrefsKey, "");
            if (!string.IsNullOrEmpty(stringFromPlayerPrefs))
            {
                var jsonFromEncode = stringFromPlayerPrefs;
#else
            GetSavePath();
            if (File.Exists(_savePath + userSaveFileName))
            {
                var jsonFromEncode = File.ReadAllText(_savePath + userSaveFileName);
#endif
                var jsonDecoded = jsonFromEncode;

#if (!UNITY_IOS && !UNITY_ANDROID)
                if (encryptFiles)
                {
                    jsonDecoded = new Xor().Decrypt(jsonDecoded, GameDataSaveLoadManager.Instance.EncryptKey);
                }
#endif

                if (!String.IsNullOrEmpty(jsonFromEncode))
                {
                    foundData = true;
                    try
                    {
                        var loadedUserSave = JsonConvert.DeserializeObject <UserSave>(jsonDecoded,
                                                                                      new JsonSerializerSettings
                        {
                            TypeNameHandling =
                                TypeNameHandling.
                                Objects,
                            ObjectCreationHandling
                                =
                                    ObjectCreationHandling
                                    .Replace
                        });

                        GameMaster.Instance.UserSave = loadedUserSave;
                    }
                    catch (Exception e)
                    {
                        foundData = false;
                    }
                }
            }

            if (!foundData)
            {
                Debug.Log("No user save found. Creating user save.");
                NewData();
            }

            //Debug.Log("[EDITOR] Loaded user save...");
        }
Example #17
0
        public void XorHandlesNull()
        {
            string aString    = "aString";
            string nullString = null;

            string xorWithNull = Xor.XorString(aString, nullString);

            Assert.AreEqual(aString, xorWithNull);
        }
Example #18
0
        public string Visit(Xor node)
        {
            var result = "";

            result += Visit((dynamic)node[0])
                      + Visit((dynamic)node[1])
                      + "\txor\n";
            return(result);
        }
Example #19
0
        private string SendCommand(string domain, string command, string payload = "")
        {
            Program.WriteLine("Try to Connect to Powersocket on " + address, false, true);
            if (address.Length == 0)
            {
                return("");
            }


            Ping      p     = new Ping();
            PingReply reply = p.Send(address);

            Program.WriteLine("Ping send", false, true);
            if (reply.Status == IPStatus.Success)
            {
                Program.WriteLine("Ping Success", false, true);
                byte[] bytes     = new byte[4096];
                Socket sender    = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                bool   connected = false;
                Program.WriteLine("Try Establish Socket Connection", false, true);
                try
                {
                    sender.Connect(address, port);
                    connected = true;
                }
                catch (Exception)
                {
                    Program.WriteLine("...failed", false, true);
                    connected = false;
                }

                if (connected)
                {
                    Program.WriteLine("...connected", false, true);
                    if (payload.Length < 2)
                    {
                        payload = "{}";
                    }

                    string msg       = "{\"" + domain + "\":{\"" + command + "\":" + payload + "}}";
                    byte[] byteMsg   = Xor.TPEncrypt(msg);
                    int    bytesSent = sender.Send(byteMsg);
                    int    bytesRec  = sender.Receive(bytes);
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    Program.WriteLine("data Received", false, true);
                    if (bytesRec > 2)
                    {
                        Program.WriteLine("parse data", false, true);
                        return(Xor.TPDecrypt(bytes, bytesRec));
                    }
                }
            }

            return("{}");
        }
Example #20
0
        public override LogicElementViewModel Clone()
        {
            var model = new Xor();

            model.CopyValues(GetModel());
            return(new XorViewModel(model, _globalCommands)
            {
                Caption = this.Caption
            });
        }
Example #21
0
 private void button3_Click_1(object sender, EventArgs e)
 {
     Xor[] ouExc = new Xor[4];
     ouExc[0]       = new Xor();
     ouExc[1]       = new Xor();
     ouExc[2]       = new Xor();
     ouExc[3]       = new Xor();
     textBox3.Text  = ouExc[0].EXclusiveOr(false, false).ToString();
     textBox3.Text += (ouExc[1].EXclusiveOr(false, true).ToString() + ouExc[2].EXclusiveOr(true, false).ToString() + ouExc[3].EXclusiveOr(true, true)).ToString();
 }
Example #22
0
        public void Xor_WithTrueTrue_ReturnsFalse()
        {
            var left  = new Constant(true);
            var right = new Constant(true);

            var operation = new Xor(left, right);
            var actual    = (bool)operation.GetExpression(null).Calculate();

            Assert.AreEqual(false, actual);
        }
Example #23
0
        public void TestXorDecryption()
        {
            const string original = "If this text is readable then the test has succeeded!";

            var xor    = Xor.Cipher(original, key);
            var cipher = Xor.Cipher(xor, key);

            Console.WriteLine(xor);
            Assert.AreEqual(original, cipher);
        }
Example #24
0
        public void FailWithNullData()
        {
            byte[] key     = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            byte[] iv      = Encoding.Default.GetBytes("12345678");
            byte[] message = Encoding.UTF8.GetBytes("message");

            Assert.Throws <ArgumentNullException>(() => Xor.Encode(null, iv, message, SBlockTypes.GOST));
            Assert.Throws <ArgumentNullException>(() => Xor.Encode(key, null, null, SBlockTypes.GOST));
            Assert.Throws <ArgumentNullException>(() => Xor.Encode(key, null, message, SBlockTypes.GOST));
            Assert.Throws <ArgumentNullException>(() => Xor.Encode((byte[])null, null, null, SBlockTypes.GOST));
        }
Example #25
0
        public void Save(PlayerSave playerToCreate, bool firstSave)
        {
            //playerToCreate.Initialize();
            if (!firstSave)
            {
                playerToCreate.Character.FullUpdateStats();
            }
            playerToCreate.LastSaved = DateTime.Now;
            var timePlayed = (Time.time - TimeLastSaved);

            playerToCreate.TimePlayed = playerToCreate.TimePlayed.Add(new TimeSpan(0, 0, (int)timePlayed));
            //Debug.Log("Total Time played:" + playerToCreate.TimePlayed.ToString());
            TimeLastSaved = Time.time;

            //todo: playerToCreate.currentScene = SceneHandler.getSceneName();
            //Debug.Log("Saving ...");
            var fileName = playerToCreate.SaveName.Replace(" ", "_") + "_" +
                           playerToCreate.SaveID.Substring(playerToCreate.SaveID.Length - 16, 12) + ".saveFile";

            playerToCreate.SavePath = _savePath + fileName;

            var saveFile = JsonConvert.SerializeObject(playerToCreate, new JsonSerializerSettings
            {
                TypeNameHandling       = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
                ObjectCreationHandling = ObjectCreationHandling.Replace
            });

#if (!UNITY_IOS && !UNITY_ANDROID)
            var saveFileEncoded = saveFile;

            if (encryptFiles)
            {
                saveFileEncoded = new Xor().Encrypt(saveFileEncoded, GameDataSaveLoadManager.Instance.EncryptKey);
            }



            Directory.CreateDirectory(_savePath);

            File.WriteAllText(_savePath + fileName, saveFileEncoded);

            SaveSavableGameObjects(playerToCreate, fileName);

            //Set last saved
            PlayerPrefs.SetString(LastSavedGameKey, _savePath + fileName);
#else
            PlayerPrefs.SetString(PlayerPrefsSavePrefix + playerToCreate.SaveID, saveFile);
            PlayerPrefs.SetString(LastSavePPrefIDKey, PlayerPrefsSavePrefix + playerToCreate.SaveID);
#endif

            //Debug.Log("Saved file with ID " + playerToCreate.SaveID);
            UserSaveLoadManager.Instance.SaveUserData();
        }
Example #26
0
        public void PassWithStrings()
        {
            var encoded = Xor.Encode("12345678901234567890123456789012", "12345678", "message", SBlockTypes.GOST);
            var decoded = Xor.Decode("12345678901234567890123456789012", "12345678", "message", SBlockTypes.GOST);

            Assert.IsNotNull(encoded);
            Assert.IsNotNull(decoded);
            Assert.IsNotEmpty(encoded);
            Assert.IsNotEmpty(decoded);
            Assert.AreEqual(decoded, encoded);
        }
Example #27
0
        public void XorWitEmptyIsSameAsOriginal()
        {
            string emptyString    = string.Empty;
            string nonEmptyString = "non empty string";

            string xorWithEmpty = Xor.XorString(emptyString, nonEmptyString);

            Console.Out.WriteLine(xorWithEmpty);

            Assert.AreEqual(nonEmptyString, xorWithEmpty);
        }
Example #28
0
        public void Challenge2_Solution()
        {
            var input1ByteArray = Converter.FromHexStringToByteArray(_hexStringInput1);
            var input2ByteArray = Converter.FromHexStringToByteArray(_hexStringInput2);

            var xorResult = Xor.Apply(input1ByteArray, input2ByteArray);

            var hexOutput = Converter.FromByteArrayToHexString(xorResult);

            Assert.AreEqual(_expectedHexOutput, hexOutput, true);
        }
Example #29
0
        public void FailWithEmptyData()
        {
            byte[] key     = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            byte[] iv      = Encoding.Default.GetBytes("12345678");
            byte[] message = Encoding.UTF8.GetBytes("message");

            Assert.Throws <ArgumentException>(() => Xor.Encode(new byte[] { }, iv, message, SBlockTypes.GOST));
            Assert.Throws <ArgumentException>(() => Xor.Encode(key, new byte[] { }, new byte[] { }, SBlockTypes.GOST));
            Assert.Throws <ArgumentException>(() => Xor.Encode(key, new byte[] { }, message, SBlockTypes.GOST));
            Assert.Throws <ArgumentException>(() => Xor.Encode(new byte[] { }, new byte[] { }, new byte[] { }, SBlockTypes.GOST));
        }
Example #30
0
        public void FailWithNotEqualsIvs()
        {
            var encoded = Xor.Encode("12345678901234567890123456789012", "12345678", "message", SBlockTypes.GOST);
            var decoded = Xor.Decode("12345678901234567890123456789012", "00000000", "message", SBlockTypes.GOST);

            Assert.IsNotNull(encoded);
            Assert.IsNotNull(decoded);
            Assert.IsNotEmpty(encoded);
            Assert.IsNotEmpty(decoded);
            Assert.AreNotEqual(decoded, encoded);
        }
Example #31
0
        public void ShouldReturnFalseForFalseFalse()
        {
            //Arrange
            Bool subject = new Xor(Bool.False, Bool.False);

            //Act
            bool actual = subject;

            //Assert
            actual.Should().BeFalse();
        }
 DEFINE_STANDARD_OP(Xor, XOR)
Example #33
0
 public void Xor_RegisterOperands_ResultIsCorrect()
 {
     var prev = new MutableState().Set(Register.A, 6).Set(Register.B, 5);
     var state = new Xor(new Reg(Register.A), new Reg(Register.B)).Apply(prev);
     Assert.AreEqual(0x3, state.Get(Register.A));
 }