IntValue() public method

public IntValue ( ) : int
return int
Ejemplo n.º 1
0
        private static void CheckNormaliseBaseTenResult(ExpandedDouble orig, NormalisedDecimal result)
        {
            String     sigDigs = result.GetSignificantDecimalDigits();
            BigInteger frac    = orig.GetSignificand();

            while (frac.BitLength() + orig.GetBinaryExponent() < 200)
            {
                frac = frac * (BIG_POW_10);
            }
            int binaryExp = orig.GetBinaryExponent() - orig.GetSignificand().BitLength();

            String origDigs = (frac << (binaryExp + 1)).ToString(10);

            if (!origDigs.StartsWith(sigDigs))
            {
                throw new AssertionException("Expected '" + origDigs + "' but got '" + sigDigs + "'.");
            }

            double     dO       = Double.Parse("0." + origDigs.Substring(sigDigs.Length));
            double     d1       = Double.Parse(result.GetFractionalPart().ToString());
            BigInteger subDigsO = new BigInteger((int)(dO * 32768 + 0.5));
            BigInteger subDigsB = new BigInteger((int)(d1 * 32768 + 0.5));

            if (subDigsO.Equals(subDigsB))
            {
                return;
            }
            BigInteger diff = (subDigsB - subDigsO).Abs();

            if (diff.IntValue() > 100)
            {
                // 100/32768 ~= 0.003
                throw new AssertionException("minor mistake");
            }
        }
Ejemplo n.º 2
0
        protected BigInteger ModKey(BigInteger Key1, BigInteger Key2)
        {
            BigInteger orgKey1 = Key1;

            Key1 += Key2;
            Key1  = equK(Key2, orgKey1, Key1.IntValue());
            return(Key1 + Key2);
        }
Ejemplo n.º 3
0
        protected void HandleServerAuthChallenge(InPacket packet)
        {
            uint one  = packet.ReadUInt32();
            uint seed = packet.ReadUInt32();

            BigInteger seed1 = packet.ReadBytes(16).ToBigInteger();
            BigInteger seed2 = packet.ReadBytes(16).ToBigInteger();

            var rand = System.Security.Cryptography.RandomNumberGenerator.Create();

            byte[] bytes = new byte[4];
            rand.GetBytes(bytes);
            BigInteger ourSeed = bytes.ToBigInteger();

            uint zero = 0;

            byte[] authResponse = HashAlgorithm.SHA1.Hash
                                  (
                Encoding.ASCII.GetBytes(Game.Username.ToUpper()),
                BitConverter.GetBytes(zero),
                BitConverter.GetBytes((uint)ourSeed.IntValue()),
                BitConverter.GetBytes(seed),
                Game.Key.ToCleanByteArray()
                                  );

            OutPacket response = new OutPacket(WorldCommand.ClientAuthSession);

            response.Write((uint)12340);        // client build
            response.Write(zero);
            response.Write(Game.Username.ToUpper().ToCString());
            response.Write(zero);
            response.Write((uint)ourSeed.IntValue());
            response.Write(zero);
            response.Write(zero);
            response.Write(Exchange.CurrentRealm.ID);
            response.Write((ulong)zero);
            response.Write(authResponse);
            response.Write(zero);            // length of addon data

            Send(response);

            // TODO: don't fully initialize here, auth may fail
            // instead, initialize in HandleServerAuthResponse when auth succeeds
            // will require special logic in network code to correctly decrypt/parse packet header
            authenticationCrypto.Initialize(Game.Key.ToCleanByteArray());
        }
Ejemplo n.º 4
0
        public NormalisedDecimal CreateNormalisedDecimal(int pow10)
        {
            // missingUnderBits is (0..3)
            int  missingUnderBits = _binaryExponent - 39;
            int  fracPart         = (_significand.IntValue() << missingUnderBits) & 0xFFFF80;
            long wholePart        = (_significand >> (C_64 - _binaryExponent - 1)).LongValue();

            return(new NormalisedDecimal(wholePart, fracPart, pow10));
        }
Ejemplo n.º 5
0
        void HandleServerAuthChallenge(PacketReader reader)
        {
            uint one  = reader.ReadUInt32();
            uint seed = reader.ReadUInt32();

            BigInteger seed1 = reader.ReadBytes(16).ToBigInteger();
            BigInteger seed2 = reader.ReadBytes(16).ToBigInteger();

            var rand = System.Security.Cryptography.RandomNumberGenerator.Create();

            byte[] bytes = new byte[4];
            rand.GetBytes(bytes);

            BigInteger _seed = bytes.ToBigInteger();

            uint zero = 0;

            byte[] response = HashAlgorithm.SHA1.Hash(Encoding.ASCII.GetBytes(Manager.m_WorldServer.username.ToUpper()),
                                                      BitConverter.GetBytes(zero),
                                                      BitConverter.GetBytes((uint)_seed.IntValue()),
                                                      BitConverter.GetBytes(seed),
                                                      Manager.m_WorldServer.SessionKey.ToCleanByteArray());

            PacketWriter writer = new PacketWriter(Opcodes.ClientAuthSession);

            writer.Write((uint)12340); // Build
            writer.Write(zero);        // LoginServerID
            writer.Write(Manager.m_WorldServer.username.ToUpper().ToCString());
            writer.Write(zero);        // Loginservertype
            writer.Write((uint)_seed.IntValue());
            writer.Write(zero);
            writer.Write(zero);
            writer.Write((uint)1); // RealmID
            writer.Write((ulong)zero);
            writer.Write(response);
            writer.Write(zero);

            Send(writer);

            AuthenticationCrypto.Initialize(Manager.m_WorldServer.SessionKey.ToCleanByteArray());
        }
Ejemplo n.º 6
0
        public BigGF Mul(BigGF b)
        {
            var first  = _poly;
            var second = b._poly;
            var res    = new SortedDictionary <int, int>();

            foreach (var pair1 in first)
            {
                foreach (var pair2 in second)
                {
                    int key   = pair1.Key + pair2.Key;
                    int value = pair1.Value * pair2.Value;
                    if (value == 1)
                    {
                        if (!res.ContainsKey(key))
                        {
                            res.Add(key, 1);
                        }
                        else
                        {
                            res.Remove(key);
                        }
                    }
                }
            }
            var result = new BigGF(_pow.IntValue(), res);

            if (Math.Pow(2, result.GetMaxPow()) < _pow.IntValue())
            {
                return(result);
            }
            else
            {
                double aaa = _pow.IntValue();
                int    ttt = (int)Math.Log(aaa, 2);
                var    tmp = new BigGF(_pow, irreducible_polynomials[ttt - 1]);

                return(result.Div(tmp));
            }
        }
Ejemplo n.º 7
0
        /**
         * Performs modulo inverse
         *
         */
        private int modInverse(int num, int prime)
        {
            if (num == -1)
            {
                return(prime - 1);
            }

            BigInteger n      = new BigInteger(num);
            BigInteger p      = new BigInteger(prime);
            BigInteger result = n.modInverse(p);

            return(result.IntValue());
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the next available address in this address pool.
        /// </summary>
        /// <returns>the next available address</returns>
        public IPAddress GetNextAvailableAddress()
        {
            Monitor.Enter(_lock);
            try
            {
                if (freeList != null)
                {
                    BigInteger next = freeList.GetNextFree();
                    if (next.IntValue() != 0)
                    {
                        try
                        {
                            IPAddress ip = new IPAddress(next.GetBytes());
                            int       pingCheckTimeout = DhcpServerPolicies.GlobalPolicyAsInt(Property.V4_PINGCHECK_TIMEOUT);
                            if (pingCheckTimeout > 0)
                            {
                                try
                                {
                                    if (CheckIPIsUsed(ip, pingCheckTimeout))
                                    {
                                        log.Warn("Next free address answered ping check: " + ip.ToString());

                                        SetUsed(ip);
                                        return(GetNextAvailableAddress());   // try again
                                    }
                                    log.InfoFormat("Assign IPv4 Address : {0}", ip.ToString());
                                }
                                catch (IOException ex)
                                {
                                    log.Error("Failed to perform v4 ping check: " + ex);
                                }
                            }
                            return(ip);
                        }
                        catch (Exception ex)
                        {
                            log.Error("Unable to build IPv4 address from next free: " + ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Unable to build IPv4 address from next free: " + ex);
            }
            finally
            {
                Monitor.Exit(_lock);
            }
            return(null);
        }
Ejemplo n.º 9
0
        public Stream RecalculatePrivateKey(Stream PrivateKeyData)
        {
            if (!PrivateKeyData.CanSeek || !PrivateKeyData.CanWrite)
            {
                throw new Exception("Unable to write to the stream");
            }

            BigInteger InversedInt = 0;

            try
            {
                InversedInt = PrivateSalt.modInverse(this.Username);
            }
            catch (Exception ex)
            {
                SysLogger.Log(ex.Message, SysLogType.Error);

                //no inverse could be found
                InversedInt = PrivateSalt + this.Username;
            }

            PatchKey(ref InversedInt); //patch the key to randomize the 0xFF bytes
            byte[] inverseData = InversedInt.getBytes();

            int temp = InversedInt.IntValue();

            for (int j = 0; j <= 1; j++)
            {
                for (int i = 4 * j; i < PrivateKeyData.Length; i += 8)
                {
                    byte[] tempData = new byte[4];
                    int    read     = 0;

                    PrivateKeyData.Position = i;
                    if ((read = PrivateKeyData.Read(tempData, 0, tempData.Length)) <= 0)
                    {
                        break;
                    }

                    int TempKey = BitConverter.ToInt32(tempData, 0) ^ temp;

                    PrivateKeyData.Position -= read;
                    PrivateKeyData.Write(BitConverter.GetBytes(TempKey), 0, read);

                    temp = TempKey;
                }
            }
            return(PrivateKeyData);
        }
        /// <summary>
        /// Gets the next available address in this address pool.
        /// </summary>
        /// <returns>the next available address</returns>
        public IPAddress GetNextAvailableAddress()
        {
            Debug.Assert(CheckIPIsUsed != null, "V6AddressBindingPool --GetNextAvailableAddress-- CheckIPIsUsed = null");
            if (freeList != null)
            {
                BigInteger next = freeList.GetNextFree();
                if (next.IntValue() != 0)
                {
                    try
                    {
                        byte[]    nextByte         = next.GetBytes();
                        IPAddress ip               = new IPAddress(next.GetBytes());
                        int       pingCheckTimeout = DhcpServerPolicies.GlobalPolicyAsInt(Property.V4_PINGCHECK_TIMEOUT);
                        if (pingCheckTimeout > 0)
                        {
                            try
                            {
                                if (CheckIPIsUsed(ip, pingCheckTimeout))
                                {
                                    log.Warn("Next free address answered ping check: " + ip.ToString());

                                    SetUsed(ip);
                                    return(GetNextAvailableAddress());   // try again
                                }
                                log.InfoFormat("Assign IPv6 Address : {0}", ip.ToString());
                            }
                            catch (IOException ex)
                            {
                                log.Error("Failed to perform v4 ping check: " + ex);
                            }
                        }
                        return(ip);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Unable to build IPv6 address from next free: " + ex);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 11
0
    public bool isProbablePrime(int confidence)
    {
        BigInteger thisVal;

        if ((this.data[maxLength - 1] & 0x80000000) != 0)        // negative
        {
            thisVal = -this;
        }
        else
        {
            thisVal = this;
        }

        // test for divisibility by primes < 2000
        for (int p = 0; p < primesBelow2000.Length; p++)
        {
            BigInteger divisor = primesBelow2000[p];

            if (divisor >= thisVal)
            {
                break;
            }

            BigInteger resultNum = thisVal % divisor;
            if (resultNum.IntValue() == 0)
            {
                return(false);
            }
        }

        if (thisVal.RabinMillerTest(confidence))
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Ejemplo n.º 12
0
        /**
         * When the connectiontable changes, we re-estimate
         * the size of the network:
         */
        protected void EstimateSize(object contab, System.EventArgs args)
        {
            try {
                //Estimate the new size:
                int            net_size      = -1;
                BigInteger     least_dist    = null;
                BigInteger     greatest_dist = null;
                int            shorts        = 0;
                ConnectionList structs       = ((ConnectionEventArgs)args).CList;

                if (structs.MainType == ConnectionType.Structured)
                {
                    /*
                     * We know we are in the network, so the network
                     * has size at least 1.  And all our connections
                     * plus us is certainly a lower bound.
                     */

                    if (structs.Count + 1 > net_size)
                    {
                        net_size = structs.Count + 1;
                    }

                    /*
                     * We estimate the density of nodes in the address space,
                     * and since we know the size of the whole address space,
                     * we can use the density to estimate the number of nodes.
                     */
                    AHAddress local = (AHAddress)_local_add;
                    foreach (Connection c in structs)
                    {
                        if (c.ConType == "structured.near")
                        {
                            BigInteger dist = local.DistanceTo((AHAddress)c.Address);
                            if (shorts == 0)
                            {
                                //This is the first one
                                least_dist    = dist;
                                greatest_dist = dist;
                            }
                            else
                            {
                                if (dist > greatest_dist)
                                {
                                    greatest_dist = dist;
                                }
                                if (dist < least_dist)
                                {
                                    least_dist = dist;
                                }
                            }
                            shorts++;
                        }
                    }

                    /*
                     * Now we have the distance between the range of our neighbors
                     */
                    if (shorts > 0)
                    {
                        if (greatest_dist > least_dist)
                        {
                            BigInteger width = greatest_dist - least_dist;
                            //Here is our estimate of the inverse density:
                            BigInteger inv_density = width / (shorts);
                            //The density times the full address space is the number
                            BigInteger total     = Address.Full / inv_density;
                            int        total_int = total.IntValue();
                            if (total_int > net_size)
                            {
                                net_size = total_int;
                            }
                        }
                    }
                    //Now we have our estimate:
                    lock ( _sync ) {
                        _netsize = net_size;
                    }
                }

                if (ProtocolLog.NodeLog.Enabled)
                {
                    ProtocolLog.Write(ProtocolLog.NodeLog, String.Format(
                                          "Network size: {0} at {1}", _netsize,
                                          DateTime.UtcNow.ToString()));
                }
            }
            catch (Exception x) {
                if (ProtocolLog.Exceptions.Enabled)
                {
                    ProtocolLog.Write(ProtocolLog.Exceptions, x.ToString());
                }
            }
        }
Ejemplo n.º 13
0
        /**
         * Reads an Integer (32 bit integer) from the byte stream.
         * @return an {@link Integer}
         */
        public int ReadInteger(DataBuffer rawInput)
        {
            BigInteger intBits = ReadBigInteger(rawInput, 4);

            return(intBits.IntValue());
        }
Ejemplo n.º 14
0
        public override MazeErrorCode onReceiveData(byte[] Data, ref byte[] ResponseData)
        {
            ResponseData = new byte[0];
            switch (base.Step)
            {
            case 1:
            {
                if (Data.Length != 32)
                {
                    SysLogger.Log("[MazeHandShake][Server] Receive Length missmatch", SysLogType.Debug);
                    return(MazeErrorCode.Error);
                }

                wopEx = base.GetWopEncryption();
                wopEx.Decrypt(Data, 0, Data.Length);

                BigInteger server_prime = new BigInteger(Data);
                if (server_prime.isProbablePrime())
                {
                    //verify the prime from the server
                    BigInteger server_Prime_test = BigInteger.genPseudoPrime(256, 50, new Random(BitConverter.ToInt32(wopEx.Key, 0)));

                    if (server_prime != server_Prime_test)
                    {
                        //Attacker detected ?
                        SysLogger.Log("[MazeHandShake][Server] Man-In-The-Middle detected", SysLogType.Debug);
                        return(MazeErrorCode.Error);
                    }

                    //successful
                    //generate another prime and send it back
                    BigInteger client_Prime = BigInteger.genPseudoPrime(256, 50, new Random(server_prime.IntValue()));

                    byte[] primeData = client_Prime.getBytes();
                    wopEx.Encrypt(primeData, 0, primeData.Length);
                    ResponseData = primeData;

                    BigInteger key = base.ModKey(server_prime, client_Prime);
                    //apply key to encryption
                    ApplyKey(wopEx, key);

                    base.FinalKey  = wopEx.Key;
                    base.FinalSalt = wopEx.Salt;

                    Step++;
                    return(MazeErrorCode.Finished);
                }
                else
                {
                    //connection failed, using old keys ?
                    SysLogger.Log("[MazeHandShake][Server] Invalid received data", SysLogType.Debug);
                    return(MazeErrorCode.Error);
                }
            }
            }

            return(MazeErrorCode.Success);
        }