Exemplo n.º 1
0
        public void RotateByLetterWorks()
        {
            var scrambler = new Scrambler();

            Assert.Equal("ecabd", scrambler.Scramble("abdec", new[] { SampleOps.RotateByB }));
            Assert.Equal("decab", scrambler.Scramble("ecabd", new[] { SampleOps.RotateByD }));
        }
Exemplo n.º 2
0
        public void MoveWorks()
        {
            var scrambler = new Scrambler();

            Assert.Equal("bdeac", scrambler.Scramble("bcdea", new[] { SampleOps.Move1To4 }));
            Assert.Equal("abdec", scrambler.Scramble("bdeac", new[] { SampleOps.Move3To0 }));
        }
Exemplo n.º 3
0
        public void EncodedTextEqualsToDecodedNumberWhenPassingOptions()
        {
            Random    random    = new Random();
            Scrambler scrambler = new Scrambler(new ScramblerOptions(
                                                    xor1: 0x2a31eb88,
                                                    shift1: 22,
                                                    xor2: 0x4cde82ed,
                                                    shift2: 5,
                                                    xor3: 0x1bd4f2dc,
                                                    shift3: 16,
                                                    hashXor: 0x6fc70a4d,
                                                    hashShift: 4,
                                                    hashPrefixLength: 3
                                                    ));

            int timesExecuted = 0;

            do
            {
                int originalNumber = random.Next();
                originalNumber &= 0x7fffffff;

                string encodedText   = scrambler.Encode(originalNumber);
                int    decodedNumber = scrambler.Decode(encodedText);

                Assert.Equal(decodedNumber, originalNumber);
            } while (++timesExecuted < NumberOfExecutions);
        }
Exemplo n.º 4
0
        private void FindFailureX10000ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var       stopwatch   = Stopwatch.StartNew();
            const int SearchCount = 10;

            for (int i = 0; i < SearchCount; i++)
            {
                var scramble       = Scrambler.Scamble();
                var solutionFinder = new ShortestSolutionFinder(WellKnownSolvers.Roux);
                var(foundSolution, description, states) = solutionFinder.FindSolution(
                    Rotator.ApplyMoves(Puzzle.Solved, scramble));

                if (!foundSolution)
                {
                    this.txtScrambleMoves.Text = scramble;
                    this.UpdateSolutionUI(description, states);
                    return;
                }
            }
            stopwatch.Stop();

            this.txtScrambleMoves.Text       = string.Empty;
            this.txtSolutionMoves.Text       = string.Empty;
            this.txtSolutionDescription.Text = $"{SearchCount} solutions found in {stopwatch.ElapsedMilliseconds}ms.";
            this.Refresh();
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Scrambler scrambler = new Scrambler();

            Console.WriteLine(scrambler.GetContent());
            Console.ReadLine( );
        }
Exemplo n.º 6
0
        public void RotateWorks()
        {
            var scrambler = new Scrambler();

            Assert.Equal("bcdea", scrambler.Scramble("abcde", new[] { SampleOps.Rotate1Left }));
            Assert.Equal("cdeab", scrambler.Scramble("abcde", new[] { SampleOps.Rotate8Right }));
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            var scrambler = new Scrambler("DESENVOLVIMENTO!").WithKey("ABCDEFGHIJKLMNOP", 4);

            scrambler.Encrypt();
            Console.ReadLine();
        }
Exemplo n.º 8
0
        public string Solve(string[] input)
        {
            var parser    = new OperationParser();
            var steps     = input.Select(line => parser.Parse(line));
            var scrambler = new Scrambler();

            return(scrambler.Scramble(Password, steps));
        }
Exemplo n.º 9
0
        void Save(UserConfig user)
        {
            var bytes      = BytesCrypto.Encrypt(_password, JsonConvert.SerializeObject(user));
            var userFolder = Scrambler.Obfuscate(user.Username, _password);
            var dirPath    = "../sndc";
            var filePath   = $"{dirPath}/{userFolder}".ToLowerInvariant();

            File.WriteAllBytes(filePath, bytes);
        }
Exemplo n.º 10
0
            public int GetByte()
            {
                var x = (ulong)this.GetInt();

                if (Scrambler.IsNeg(x))
                {
                    x = Scrambler.Negate(x);
                }
                return((int)(x % 256));
            }
Exemplo n.º 11
0
            private static ulong RShift(ulong num, ulong n)
            {
                var highbits = (ulong)0;

                if ((num & Scrambler.Pow(2, 31)) != 0)
                {
                    highbits = (Scrambler.Pow(2, n) - 1) * Scrambler.Pow(2, 32 - n);
                }
                return((num / Scrambler.Pow(2, n)) | highbits);
            }
Exemplo n.º 12
0
        public void Scramble_ReturnsCorrectString_BasedOnContainedRules()
        {
            var input    = "abcde";
            var expected = "decab";

            var sut = new Scrambler();

            var actual = sut.Scramble(input, instructions);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 13
0
 private static string ScrambleNonce(ulong clientSeed, byte[] serverNonce)
 {
     var scrambler = new Scrambler(clientSeed);
     var byte100 = 0;
     for (int i = 0; i < 100; i++)
         byte100 = scrambler.GetByte();
     var scrambled = string.Empty;
     for (int i = 0; i < serverNonce.Length; i++)
         scrambled += (char)(serverNonce[i] ^ (scrambler.GetByte() & byte100));
     return scrambled;
 }
Exemplo n.º 14
0
        private bool ValidationUser(string email, string password)
        {
            var logUser = _userService.GetUserByEmail(email);

            if (logUser != null)
            {
                MainWindowData.CurrentUser = logUser;
            }

            return(MainWindowData.CurrentUser.PasswordHash.Equals(Scrambler.GetPassHash(password)));
        }
        public override string Scramble()
        {
            if (!int.TryParse(TwistedCornersInput.Text, out int twistedCorners))
            {
                MessageBox.Show("Enter the number of twisted corners in the box", "Invalid number of twisted corners", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(null);
            }
            if (twistedCorners < 0 || twistedCorners > 7)
            {
                MessageBox.Show("Number of twisted corners must be between 0 and 7", "Invalid number of twisted corners", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(null);
            }
            if (twistedCorners == 0 && FloatingInput.SelectedItem.Equals(No))
            {
                MessageBox.Show("0-twists must be floating", "Invalid corners", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(null);
            }
            if (twistedCorners == 1 && FloatingInput.SelectedItem.Equals(Yes))
            {
                MessageBox.Show("1-twists must not be floating", "Invalid corners", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(null);
            }

            var canBeGreater = CardinalityBox.SelectedItem.Equals(EqualOrGreater);

            bool?            isFloatingTwist;
            List <FinalLeaf> baseLeaves;

            switch ((string)FloatingInput.SelectedItem)
            {
            case Yes:
                isFloatingTwist = true;
                baseLeaves      = floatingLeaves;
                break;

            case No:
                isFloatingTwist = false;
                baseLeaves      = nonFloatingLeaves;
                break;

            default:
                isFloatingTwist = null;
                baseLeaves      = cornerLeaves;
                break;
            }

            var possibleLeaves = canBeGreater ? baseLeaves.Where(x => x.NumTwisted >= twistedCorners).ToList() : cornerLeaves.Where(x => x.NumTwisted == twistedCorners).ToList();
            var cornerNode     = new Node(possibleLeaves, 0);

            var scramble = Scrambler.GetScramble(edgeNode, cornerNode, rand, isFloatingTwist);

            return(scramble);
        }
Exemplo n.º 16
0
            private int GetInt()
            {
                if (this.IX == 0)
                {
                    this.MixBuffer();
                }
                var val = this.Buffer[this.IX];

                this.IX = (this.IX + 1) % 624;
                val    ^= Scrambler.RShift(val, 11) ^ Scrambler.LShift(val ^ Scrambler.RShift(val, 11), 7) & 0x9D2C5680;
                return((int)(Scrambler.RShift(val ^ Scrambler.LShift(val, 15L) & 0xEFC60000, 18L) ^ val ^ Scrambler.LShift(val, 15L) & 0xEFC60000));
            }
Exemplo n.º 17
0
            private static ulong[] SeedBuffer(ulong seed)
            {
                var buffer = new ulong[624];

                for (int i = 0; i < 624; i++)
                {
                    buffer[i] = seed;
                    seed      = (1812433253 * ((seed ^ Scrambler.RShift(seed, 30)) + 1)) & 0xFFFFFFFF;
                }

                return(buffer);
            }
Exemplo n.º 18
0
        public bool DeleteUser()
        {
            var userFolder = Scrambler.Obfuscate(_username, _password);
            var dirPath    = "../sndc";
            var filePath   = $"{dirPath}/{userFolder}".ToLowerInvariant();

            if (!File.Exists(filePath))
            {
                return(false);
            }
            File.Delete(filePath);
            return(true);
        }
Exemplo n.º 19
0
        public static void Problem21()
        {
            var instructions         = FileStringReader.Read("P21.txt");
            var reversedInstructions = instructions.Reverse();

            var take = 3;

            var scrambler = new Scrambler();

            var scrambled = new Scrambler().Scramble("abcdefgh", instructions);

            var descrambled = new Scrambler().Descramble("fbgdceah", instructions.Reverse());
        }
Exemplo n.º 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tokensVector"></param>
        /// <returns></returns>
        private bool initElements(List <String> tokensVector)
        {
            String attribute, valueStr;
            bool   isSuccess = true;
            int    j;

            for (j = 0; j < tokensVector.Count; j += 2)
            {
                attribute = ((String)tokensVector[j]);
                valueStr  = ((String)tokensVector[j + 1]);

                switch (attribute)
                {
                case ConstInterface.MG_TAG_USERNAME:
                    UserName = valueStr;
                    break;

                case ConstInterface.MG_ATTR_USERID:
                    UserID = valueStr;
                    ClientManager.Instance.setUsername(UserID);
                    break;

                case ConstInterface.MG_ATTR_USERINFO:
                    UserInfo = valueStr;
                    break;

                case ConstInterface.MG_TAG_PASSWORD:
                    Password = valueStr;
                    byte[] passwordDecoded   = Base64.decodeToByte(Password);
                    string encryptedPassword = Encoding.UTF8.GetString(passwordDecoded, 0, passwordDecoded.Length);
                    string decryptedPassword = Scrambler.UnScramble(encryptedPassword, 0, encryptedPassword.Length - 1);
                    // At server side spaces are added at the end if the length of password is less than 4 characters.
                    // Remove these extra spaces before setting the password.
                    decryptedPassword = StrUtil.rtrim(decryptedPassword);
                    // if the password is empty set a password containing one " ", as for userId, where if no userId
                    // then a " " set to userId.
                    if (String.IsNullOrEmpty(decryptedPassword))
                    {
                        decryptedPassword = "******";
                    }
                    ClientManager.Instance.setPassword(decryptedPassword);
                    break;

                default:
                    Logger.Instance.WriteExceptionToLog("in UserDetails.initElements(): unknown attribute: " + attribute);
                    isSuccess = false;
                    break;
                }
            }
            return(isSuccess);
        }
Exemplo n.º 21
0
        public void CryptEncryptScrambler()
        {
            const int scramblerValue = 321;
            const int startedKey = 1232423;
            var scrambler = new Scrambler(scramblerValue, startedKey);
            var deScrambler = new Scrambler(scramblerValue, startedKey);

            const byte data = 123;
            var cryptedData = scrambler.Encrypt(data);
            Assert.AreNotEqual(data, cryptedData);

            var deCryptedData = deScrambler.Encrypt(cryptedData);
            Assert.AreEqual(data, deCryptedData);
        }
Exemplo n.º 22
0
        private void FindAlgorithmSolutionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.txtScrambleMoves.Text       = string.Empty;
            this.txtSolutionMoves.Text       = string.Empty;
            this.txtSolutionDescription.Text = string.Empty;
            this.Refresh();

            var    solver      = WellKnownSolvers.Roux;
            var    algorithm   = solver.Algorithms["PairToRightFront.RightBackUp"];
            var    stopwatch1  = Stopwatch.StartNew();
            Puzzle foundPuzzle = null;

            for (int i = 0; i < 10000; i++)
            {
                var initialPuzzle = Rotator.ApplyMoves(Puzzle.Solved, Scrambler.Scamble());
                foundPuzzle = new AlgorithmUsageFinder(WellKnownSolvers.Roux, algorithm).FindUsage(initialPuzzle);
                if (foundPuzzle != null)
                {
                    break;
                }
            }
            stopwatch1.Stop();

            if (foundPuzzle == null)
            {
                this.txtSolutionDescription.Text = "No usage of this algorithm in this puzzle.";
                return;
            }

            this.txtSolutionDescription.Text = $"Found puzzle for algorithm in {stopwatch1.ElapsedMilliseconds.ToString()}ms";

            var stopwatch2 = Stopwatch.StartNew();
            var solutions  = new SolutionSearch(4, SolutionSearch.AllRouxMoves, algorithm.FinishedState)
                             .Search(foundPuzzle);

            stopwatch2.Stop();

            var shortestLength = solutions.Min(value => value.Count());

            var message = this.txtSolutionDescription.Text + Environment.NewLine
                          + $"Found solutions in {stopwatch2.ElapsedMilliseconds.ToString()}ms\r\n"
                          + string.Join(
                ", ",
                from solution in solutions
                where solution.Count() == shortestLength
                select NotationParser.FormatMoves(solution));

            this.txtSolutionDescription.Text = message;
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            var x = Scrambler.Encode(new string[] { "123", "321" }, "321");

            foreach (var item in x)
            {
                Console.WriteLine(item);
            }
            var z = Scrambler.Decode(x, "321");

            foreach (var item in z)
            {
                Console.WriteLine(item);
            }
        }
Exemplo n.º 24
0
        public void SetSessionKey(String pubKeyString, String scrambler = null)
        {
            BigInteger pubKey = BigIntegerExtension.Create(pubKeyString, 16);

            if (scrambler == null) // Server SessionKey
            {
                // (Av^u) ^ b   (mod N)
                SessionKey = pubKey.multiply(verifier.modPow(Scrambler, Modulus)).modPow(PrivateKey, Modulus);
            }
            else // Client SessionKey
            {
                Scrambler = BigIntegerExtension.Create(scrambler, 16);
                BigInteger temp = PrivateKey.add(Scrambler.multiply(SaltedIdentityHash));
                SessionKey = pubKey.subtract((Generator.modPow(SaltedIdentityHash, Modulus)).multiply(Multiplier)).modPow(temp, Modulus);
            }
        }
Exemplo n.º 25
0
        public void CryptEncryptScrambler()
        {
            const int scramblerValue = 321;
            const int startedKey     = 1232423;
            var       scrambler      = new Scrambler(scramblerValue, startedKey);
            var       deScrambler    = new Scrambler(scramblerValue, startedKey);

            const byte data        = 123;
            var        cryptedData = scrambler.Encrypt(data);

            Assert.AreNotEqual(data, cryptedData);

            var deCryptedData = deScrambler.Encrypt(cryptedData);

            Assert.AreEqual(data, deCryptedData);
        }
Exemplo n.º 26
0
        public override string Scramble()
        {
            if (!int.TryParse(NumAlgsInput.Text, out int numAlgs))
            {
                MessageBox.Show("Enter the number of algs in the box", "Invalid number of algs", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(null);
            }
            if (numAlgs < 1 || numAlgs > 14)
            {
                MessageBox.Show("Number of algs must be between 1 and 14", "Invalid number of algs", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(null);
            }
            var combinationNode = combinationNodes.Single(x => x.NumAlgs == numAlgs);
            var scramble        = Scrambler.GetScramble(edgeNodes, cornerNodes, combinationNode, rand);

            return(scramble);
        }
Exemplo n.º 27
0
        public void EncodedTextEqualsToDecodedNumber()
        {
            Random    random    = new Random();
            Scrambler scrambler = new Scrambler();

            int timesExecuted = 0;

            do
            {
                int originalNumber = random.Next();
                originalNumber &= 0x7fffffff;

                string encodedText   = scrambler.Encode(originalNumber);
                int    decodedNumber = scrambler.Decode(encodedText);

                Assert.Equal(decodedNumber, originalNumber);
            } while (++timesExecuted < NumberOfExecutions);
        }
Exemplo n.º 28
0
        public void Scrambler_ShouldReturnUnsolvedCube()
        {
            var cube      = new Cube();
            var scrambler = new Scrambler();
            var result    = scrambler.ScrambleCube();

            foreach (var(turn, clockwise, count) in result.Turns)
            {
                cube.Move(turn, clockwise, count);
            }

            cube.Left.Should().BeEquivalentTo(result.Cube.Left);
            cube.Front.Should().BeEquivalentTo(result.Cube.Front);
            cube.Up.Should().BeEquivalentTo(result.Cube.Up);
            cube.Right.Should().BeEquivalentTo(result.Cube.Right);
            cube.Down.Should().BeEquivalentTo(result.Cube.Down);
            cube.Back.Should().BeEquivalentTo(result.Cube.Back);
        }
Exemplo n.º 29
0
        /// <summary>
        ///  Initializes the encryptor that handles encryption/decryption of cached content (this functionality is currently embedded in the PersistentOnlyCacheManager..)
        /// </summary>
        internal void InitializeEncryptor()
        {
            // retrieve the required encryption state (enabled/disabled) and key:
            bool   disableEncryption = GetLastOfflineExecutionPropertyBool(ConstInterface.DISABLE_ENCRYPTION);
            string encryptionKeyStr  = LastOfflineExecutionProperties.getProperty(ConstInterface.ENCRYPTION_KEY);

            byte[] encryptionKey = null;

            if (!String.IsNullOrEmpty(encryptionKeyStr))
            {
                // TODO: Scrambling the encryption key in the execution.properties_LastOffline file is not secured enough!
                encryptionKeyStr = Scrambler.UnScramble(encryptionKeyStr, 0, encryptionKeyStr.Length - 1);
                encryptionKey    = Encoding.Default.GetBytes(encryptionKeyStr);
            }

            // initialize the encryptor:
            IEncryptor encryptor = PersistentOnlyCacheManager.CreateInstance(disableEncryption, encryptionKey);
        }
Exemplo n.º 30
0
            private void MixBuffer()
            {
                var i = 0;
                var j = 0;

                while (i < 624)
                {
                    i += 1;
                    var v4 = (this.Buffer[i % 624] & 0x7FFFFFFF) + (this.Buffer[j] & 0x80000000);
                    var v6 = Scrambler.RShift(v4, 1) ^ this.Buffer[(i + 396) % 624];
                    if ((v4 & 1) != 0)
                    {
                        v6 ^= 0x9908B0DF;
                    }
                    this.Buffer[j] = v6;
                    j += 1;
                }
            }
        public override string Scramble()
        {
            if (!int.TryParse(FlippedEdgesInput.Text, out int flippedEdges))
            {
                MessageBox.Show("Enter the number of flipped edges in the box", "Invalid number of flipped edges", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(null);
            }
            if (flippedEdges < 0 || flippedEdges > 11)
            {
                MessageBox.Show("Number of flipped edges must be between 0 and 11", "Invalid number of flipped edges", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(null);
            }
            var canBeGreater   = CardinalityBox.SelectedItem.Equals(EqualOrGreater);
            var possibleLeaves = canBeGreater ? edgeLeaves.Where(x => x.NumTwisted >= flippedEdges).ToList() : edgeLeaves.Where(x => x.NumTwisted == flippedEdges).ToList();
            var edgeNode       = new Node(possibleLeaves, 0);
            var scramble       = Scrambler.GetScramble(edgeNode, cornerNode, rand, null);

            return(scramble);
        }
Exemplo n.º 32
0
 private static string ScrambleNonce(ulong clientSeed, byte[] serverNonce)
 {
     var scrambler = new Scrambler(clientSeed);
     var byte100 = 0;
     for (int i = 0; i < 100; i++)
         byte100 = scrambler.GetByte();
     var scrambled = string.Empty;
     for (int i = 0; i < serverNonce.Length; i++)
         scrambled += (char)(serverNonce[i] ^ (scrambler.GetByte() & byte100));
     return scrambled;
 }