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); }
public void HexStrings() { const string x = "4154"; // 65 84 const string y = "534f"; // 83 79 Xor.HexStrings(x, y).Should().Be("121b"); }
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(); }
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"); }
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 }); }
public void Challenge02_FixedXOR() { var xored = Xor.ApplyFixed(Hex.ToBytes("1c0111001f010100061a024b53535009181c"), Hex.ToBytes("686974207468652062756c6c277320657965")); Assert.Equal("746865206b696420646f6e277420706c6179", BitConverter.ToString(xored).Replace("-", "").ToLowerInvariant()); }
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(); }
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); } }
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"); }
/// <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 }; } } }
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(); }
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); }
public void Challenge2() // XOR { const string hex1 = "1c0111001f010100061a024b53535009181c"; const string hex2 = "686974207468652062756c6c277320657965"; const string expected = "746865206b696420646f6e277420706c6179"; Xor.HexStrings(hex1, hex2).Should().Be(expected); }
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); }
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); }
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..."); }
public void XorHandlesNull() { string aString = "aString"; string nullString = null; string xorWithNull = Xor.XorString(aString, nullString); Assert.AreEqual(aString, xorWithNull); }
public string Visit(Xor node) { var result = ""; result += Visit((dynamic)node[0]) + Visit((dynamic)node[1]) + "\txor\n"; return(result); }
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("{}"); }
public override LogicElementViewModel Clone() { var model = new Xor(); model.CopyValues(GetModel()); return(new XorViewModel(model, _globalCommands) { Caption = this.Caption }); }
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(); }
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); }
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); }
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)); }
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(); }
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); }
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); }
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); }
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)); }
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); }
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)
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)); }