Exemplo n.º 1
0
        public override int GetHashCode()
        {
            // stolen from GPNode.  It's a decent algorithm.
            var hash = GetType().GetHashCode();

            return(Trees.Aggregate(hash, (current, t) => (current << 1 | BitShifter.URShift(current, 31)) ^ t.TreeHashCode()));
        }
Exemplo n.º 2
0
        public static void Decrypt(string hexData, out ulong sender, out ulong recipient)
        {
            sender    = 0;
            recipient = 0;

            if (hexData.Length != 64)
            {
                return;
            }

            var key  = Encoding.UTF8.GetBytes(((FusionBotConfig)Globals.Bot.Config).DonationPaymentIdKey);
            var data = hexData.FromByteHex();
            var iv   = data.Take(BLOCK_SIZE).ToArray();

            data = data.Skip(BLOCK_SIZE).ToArray();

            BufferedBlockCipher cipher   = new CtsBlockCipher(new CbcBlockCipher(new AesEngine()));
            ICipherParameters   keyParam = new ParametersWithIV(new KeyParameter(key), iv);

            cipher.Init(false, keyParam);
            var result = cipher.DoFinal(data, 0, data.Length);

            int start = 0;

            sender    = BitShifter.ToULong(result, ref start);
            recipient = BitShifter.ToULong(result, ref start);
        }
        public BinarySerializerData Serialize(List <ushort> value)
        {
            byte[] b = new byte[value.Count * stride];
            for (int i = 0; i < value.Count; i++)
            {
                Buffer.BlockCopy(BitShifter.ToByte(value[i]), 0, b, i * stride, stride);
            }

            return(new BinarySerializerData(FileHelper.Compress(b), value.Count * stride));
        }
Exemplo n.º 4
0
        public override int NodeHashCode()
        {
            // a reasonable hash code
            long l = BitConverter.DoubleToInt64Bits(value);
            // BRS: Java has BigEndianess, so these are reversed for C#
            //      It doesn't matter since we're just adding them together, but.... ;)
            int iLower = (int)(l & 0x00000000FFFFFFFF);
            int iUpper = (int)BitShifter.URShift(l, 32);

            return(this.GetType().GetHashCode() + iUpper + iLower);
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            CommandLineParser cmd = CommandLineParser.Parse(args);

            Log.CreateInstance(true);

            string keyText = null;

            if (cmd["key"] != null)
            {
                keyText = cmd["key"].Value;
            }
            else
            {
                keyText = PasswordPrompt.Get("Please enter the encryption key");
                string keyText2 = PasswordPrompt.Get("Please confirm the encryption key");

                if (keyText != keyText2)
                {
                    Log.Instance.Write(Log_Severity.Fatal, "Keys did not match");
                }
            }

            if (cmd["to"] == null || cmd["from"] == null)
            {
                Log.Instance.Write(Log_Severity.Fatal, "Need arguments 'to' and 'from'");
            }

            ulong sender    = ulong.Parse(cmd["from"].Value);
            ulong recipient = ulong.Parse(cmd["to"].Value);

            var mt  = new MersenneTwister((uint)Guid.NewGuid().GetHashCode());
            var key = Encoding.UTF8.GetBytes(keyText);

            if (sender == 0)
            {
                sender = mt.NextULong();
            }

            if (recipient == 0)
            {
                recipient = mt.NextULong();
            }

            var iv   = mt.NextBytes(BLOCK_SIZE);
            var data = BitShifter.ToByte(sender).Concat(BitShifter.ToByte(recipient)).ToArray();

            BufferedBlockCipher cipher   = new CtsBlockCipher(new CbcBlockCipher(new AesEngine()));
            ICipherParameters   keyParam = new ParametersWithIV(new KeyParameter(key), iv);

            cipher.Init(true, keyParam);
            Log.Instance.Write(iv.Concat(cipher.DoFinal(data, 0, data.Length)).ToArray().ToHex());
        }
        public List <ushort> Deserialize(BinarySerializerData data)
        {
            byte[]   b = FileHelper.Decompress(data.Data, data.Length);
            ushort[] returnValue = new ushort[data.Length / stride];
            int      x = 0, start = 0;

            for (int i = 0; i < data.Length; i += stride)
            {
                returnValue[x++] = BitShifter.ToUShort(b, ref start);
            }

            return(returnValue.ToList());
        }
        public int[] Deserialize(BinarySerializerData data)
        {
            byte[] b = FileHelper.Decompress(data.Data, data.Length);
            int[]  returnValue = new int[data.Length / stride];
            int    x = 0, start = 0;

            for (int i = 0; i < data.Length; i += stride)
            {
                returnValue[x++] = BitShifter.ToInt(b, ref start);
            }

            return(returnValue);
        }
Exemplo n.º 8
0
        public override int GetHashCode()
        {
            // stolen from GPIndividual.  It's a decent algorithm.
            var hash = GetType().GetHashCode();

            hash = (hash << 1 | BitShifter.URShift(hash, 31));
            for (var x = 0; x < genome.Length; x++)
            {
                hash = (hash << 1 | BitShifter.URShift(hash, 31)) ^ genome[x];
            }

            return(hash);
        }
Exemplo n.º 9
0
        public override int GetHashCode()
        {
            // stolen from GPIndividual. It's a decent algorithm.
            var hash = GetType().GetHashCode();

            hash = (hash << 1 | BitShifter.URShift(hash, 31));
            for (var x = 0; x < genome.Length; x++)
            {
                var l = BitConverter.DoubleToInt64Bits(genome[x]);
                hash = (hash << 1 | BitShifter.URShift(hash, 31)) ^ (int)((BitShifter.URShift(l, 16)) & 0xFFFFFFF) ^ (int)(l & 0xFFFF);
            }

            return(hash);
        }
Exemplo n.º 10
0
        private static (int score, ulong board) SlideRowB(Direction direction, int rowIndex, ulong target)
        {
            var rowAsShort = BitShifter.GetRowAsShort(rowIndex, target);

            var(slidRow, score) = direction == Direction.Right || direction == Direction.Down ?
                                  BitShifter.SlideRightB(rowAsShort, direction) : BitShifter.SlideLeftB(rowAsShort, direction);
            int   shiftCount = rowIndex * 16;
            ulong rowMask    = 0xFFFF000000000000 >> shiftCount;
            ulong update     = (ulong)slidRow << (48 - shiftCount);

            //OR in the updated row. (AND ~rowmask clears the old value)
            target = (target & ~rowMask) | update;
            return(score, target);
        }
Exemplo n.º 11
0
        private int TestFollowingMove(ulong board)
        {
            var emptyTiles = BitShifter.IndexSpacesB(board);
            int evTotal    = 0;

            foreach (int index in emptyTiles)
            {
                ulong testBoard = BitShifter.SetNibbleFromIndex(index, 2, board);
                (int score2, _, _) = TestAllPossibleMoves(testBoard);
                int evalA = (int)(0.1 * score2);
                testBoard          = BitShifter.SetNibbleFromIndex(index, 1, board);
                (int score1, _, _) = TestAllPossibleMoves(testBoard);
                int evalB = (int)(0.9 * score1);
                evTotal += evalB + evalA;
            }
            return(evTotal);
        }
Exemplo n.º 12
0
        public static (int points, ulong board) SlideBoard(Direction direction, ulong target)
        {
            ulong testBoard = direction == Direction.Down || direction == Direction.Up ?
                              BitShifter.TransposeRowsToCols(target) : target;
            int moveScore = 0;

            for (int i = 0; i < 4; i++)
            {
                (int score, ulong updatedBoard) = SlideRowB(direction, i, testBoard);
                testBoard  = updatedBoard;
                moveScore += score;
            }
            ulong processedBoard = direction == Direction.Down || direction == Direction.Up ?
                                   BitShifter.TransposeRowsToCols(testBoard) : testBoard;

            return(moveScore, processedBoard);
        }
Exemplo n.º 13
0
        public Direction GetBestMove(ulong board)
        {
            (int score, Direction direction)bestMove = (int.MinValue, Direction.Down);
            foreach (Direction direction in directions)
            {
                ulong clonedBoard = board;

                (int score, ulong nextBoard) = TestPossibleDirection(direction, clonedBoard);
                if (BitShifter.CheckForAWin(nextBoard))
                {
                    return(direction);
                }
                if (nextBoard != clonedBoard)
                {
                    int moveScore = TestFollowingMove(nextBoard);
                    if (moveScore >= bestMove.score)
                    {
                        bestMove = (moveScore, direction);
                    }
                }
            }
            return(bestMove.direction);
        }
Exemplo n.º 14
0
        public static string Encrypt(ulong sender, ulong recipient)
        {
            var mt  = new MersenneTwister((uint)Guid.NewGuid().GetHashCode());
            var key = Encoding.UTF8.GetBytes(((FusionBotConfig)Globals.Bot.Config).DonationPaymentIdKey);

            if (sender == 0)
            {
                sender = mt.NextULong();
            }

            if (recipient == 0)
            {
                recipient = mt.NextULong();
            }

            var iv   = mt.NextBytes(BLOCK_SIZE);
            var data = BitShifter.ToByte(sender).Concat(BitShifter.ToByte(recipient)).ToArray();

            BufferedBlockCipher cipher   = new CtsBlockCipher(new CbcBlockCipher(new AesEngine()));
            ICipherParameters   keyParam = new ParametersWithIV(new KeyParameter(key), iv);

            cipher.Init(true, keyParam);
            return(iv.Concat(cipher.DoFinal(data, 0, data.Length)).ToArray().ToHex());
        }
Exemplo n.º 15
0
 /// <summary>
 /// Serves as the default hash function.
 /// </summary>
 /// <returns>A hash code for the current object.</returns>
 public override int GetHashCode()
 {
     return(BitShifter.ShiftAndWrap(this.SourceStep.GetHashCode(), 3)
            ^ this.TargetStep.GetHashCode());
 }
Exemplo n.º 16
0
 /// <summary>
 /// Serves as the default hash function.
 /// </summary>
 /// <returns>A hash code for the current object.</returns>
 public override int GetHashCode()
 {
     return(BitShifter.ShiftAndWrap(this.Identifier.GetHashCode(), 3)
            ^ this.Step.GetHashCode());
 }
Exemplo n.º 17
0
 public void ShiftMinusOneOneLeft()
 {
     Assert.AreEqual(-1, BitShifter.ShiftAndWrap(-1, 1));
 }
Exemplo n.º 18
0
 public void ShiftOneOneLeft()
 {
     Assert.AreEqual(2, BitShifter.ShiftAndWrap(1, 1));
 }
Exemplo n.º 19
0
 /// <summary>
 /// Serves as the default hash function.
 /// </summary>
 /// <returns>A hash code for the current object.</returns>
 public override int GetHashCode()
 {
     return(BitShifter.ShiftAndWrap(this.StepDescription?.GetHashCode() ?? 0, 3)
            ^ this.Identifier.GetHashCode());
 }
Exemplo n.º 20
0
 /// <summary>
 /// Serves as the default hash function.
 /// </summary>
 /// <returns>A hash code for the current object.</returns>
 public override int GetHashCode()
 {
     return(BitShifter.ShiftAndWrap(this.ConditionText?.GetHashCode() ?? 0, 3)
            ^ this.ConditionState.GetHashCode());
 }
Exemplo n.º 21
0
 /// <summary>
 /// Serves as the default hash function.
 /// </summary>
 /// <returns>A hash code for the current object.</returns>
 public override int GetHashCode()
 {
     return(BitShifter.ShiftAndWrap(this.Id, 4)
            ^ this.Type.GetHashCode());
 }
Exemplo n.º 22
0
        private static string GetIpFromInteger(uint ipInt)
        {
            var b = BitShifter.ToByte(ipInt);

            return($"{b[0]}.{b[1]}.{b[2]}.{b[3]}");
        }
Exemplo n.º 23
0
 public void ShiftOneThirtyTwoLeft()
 {
     Assert.AreEqual(1, BitShifter.ShiftAndWrap(1, 32));
 }
        protected void GetMember(object objectToSerialize, string name, Type type, object value, XElement e, bool preferBinarySerialization)
        {
            //this happens when the type of the member is different to the type of the value assigned to it
            //for example a member might be declared as a base class or interface and have a derived class assigned to it
            Type valType;

            if (value != null && (valType = value.GetType()) != type)
            {
                type = valType;
            }

            Ns ns = Lookup(type);

            Object_Type ot = ns.ObjectType;

            switch (ot)
            {
            case Object_Type.Struct:
            case Object_Type.Class:
            {
                bool isShared = Attribute.IsDefined(ns.Type, typeof(SerializeAsSharedObject), true);
                if (isShared)
                {
                    //first thing we do is create an element that links this value to the shared object
                    XElement assetObjectElement = XHelper.CreateElement(e, ns.Name, name);

                    if (value == null)
                    {
                        XHelper.CreateAttribute(assetObjectElement, "ID", "null");
                        return;
                    }

                    byte[] hash = MD5.Create().ComputeHash(BitShifter.ToByte(value.GetHashCode()));
                    //prefix with an X to make sure first character is a letter in accordance with XML standard
                    string s = "X" + string.Concat(hash.Select(x => x.ToString("X2")));

                    XHelper.CreateAttribute(assetObjectElement, "ID", s);

                    //then we actually create the shared object if it has not already been created
                    if (!checksums.Contains(s))
                    {
                        checksums.Add(s);

                        XElement sharedObjectElement = XHelper.CreateElement(sharedElement, ns.Name, s);

                        if (!Serializer.HasSerializer(type, preferBinarySerialization))
                        {
                            if (value != null)
                            {
                                GetMembers(value, sharedObjectElement);
                            }
                            else
                            {
                                CreateValue(sharedObjectElement, type, value, false);
                            }
                        }
                        else
                        {
                            CreateValue(sharedObjectElement, type, value, preferBinarySerialization);
                        }
                    }
                }
                else
                {
                    //if this class has a serializer, use it, otherwise we recurse through the objects members and serialize the items individually
                    if (!Serializer.HasSerializer(type, preferBinarySerialization))
                    {
                        if (value != null)
                        {
                            GetMembers(value, XHelper.CreateElement(e, ns.Name, name));
                        }
                        else
                        {
                            CreateValue(XHelper.CreateElement(e, ns.Name, name), type, value, false);
                        }
                    }
                    else
                    {
                        CreateValue(XHelper.CreateElement(e, ns.Name, name), type, value, preferBinarySerialization);
                    }
                }
            }
            break;

            case Object_Type.Primitive:
            {
                //any types that are Object_Type.Primitive have a built in serializer. so we know they can always be serialized
                CreateValue(XHelper.CreateElement(e, ns.Name, name), type, value, preferBinarySerialization);
            }
            break;

            case Object_Type.Enum:
            {
                //any types that are Object_Type.Enum use the built in IntSerializer. so we know they can always be serialized
                CreateValue(XHelper.CreateElement(e, ns.Name, name), ns.Type, value, preferBinarySerialization);
            }
            break;

            case Object_Type.List:
            case Object_Type.Dictionary:
            case Object_Type.Array:
            {
                //for collections. we need to iterate through the items and serialize each one
                //but we need to set this up recursively, in case the items in a collection are themselves collections
                if (value != null)
                {
                    if (!Serializer.HasSerializer(type, preferBinarySerialization))
                    {
                        SerializeCollection(objectToSerialize, e, name, type, value, preferBinarySerialization);
                    }
                    else
                    {
                        CreateValue(XHelper.CreateElement(e, ns.Name, name), type, value, preferBinarySerialization);
                    }
                }
                else
                {
                    CreateValue(XHelper.CreateElement(e, ns.Name, name), type, value, preferBinarySerialization);
                }
            }
            break;

            default:
                CreateValue(XHelper.CreateElement(e, ns.Name, name), type, null, preferBinarySerialization);     //if we can't determine the object type, just serialize it as null
                break;
            }
        }
Exemplo n.º 25
0
 public void ShiftIntMinOneLeft()
 {
     Assert.AreEqual(1, BitShifter.ShiftAndWrap(Int32.MinValue, 1));
 }
Exemplo n.º 26
0
        public override int GetHashCode()
        {
            var hash = GetType().GetHashCode();

            return(Rulesets.Aggregate(hash, (current, t) => (current << 1 | BitShifter.URShift(current, 31)) ^ t.GetHashCode()));
        }