Exemplo n.º 1
0
 public static Extreme.Mathematics.BigInteger ToUnsignedExtremeMathematics(BigInteger value)
 {
     if (value.Sign < 0)
     {
         throw new ArgumentException("Only non-negative values allowed");
     }
     return(new Extreme.Mathematics.BigInteger(value.ToByteArray()));
 }
Exemplo n.º 2
0
 public static byte[] UnsignedToBytes(BigInteger value)
 {
     if (value.Sign < 0)
     {
         throw new ArgumentException("Only non-negative values allowed");
     }
     byte[] bytes = value.ToByteArray();
     return(ShouldTrimSign(bytes) ? bytes.Take(bytes.Length - 1).ToArray() : bytes);
 }
Exemplo n.º 3
0
        public static BigInt Random(this Random generator, BigInt limit)
        {
            ContractUtils.Requires(limit.Sign > 0, "limit");
            ContractUtils.RequiresNotNull(generator, "generator");

            BigInt res = BigInt.Zero;

            while (true)
            {
                // if we've run out of significant digits, we can return the total
                if (limit == BigInt.Zero)
                {
                    return(res);
                }

                // if we're small enough to fit in an int, do so
                int iLimit;
                if (limit.AsInt32(out iLimit))
                {
                    return(res + generator.Next(iLimit));
                }

                // get the 3 or 4 uppermost bytes that fit into an int
                int    hiData;
                byte[] data  = limit.ToByteArray();
                int    index = data.Length;
                while (data[--index] == 0)
                {
                    ;
                }
                if (data[index] < 0x80)
                {
                    hiData        = data[index] << 24;
                    data[index--] = (byte)0;
                }
                else
                {
                    hiData = 0;
                }
                hiData       |= data[index] << 16;
                data[index--] = (byte)0;
                hiData       |= data[index] << 8;
                data[index--] = (byte)0;
                hiData       |= data[index];
                data[index--] = (byte)0;

                // get a uniform random number for the uppermost portion of the bigint
                byte[] randomData = new byte[index + 2];
                generator.NextBytes(randomData);
                randomData[index + 1] = (byte)0;
                res += new BigInt(randomData);
                res += (BigInt)generator.Next(hiData) << ((index + 1) * 8);

                // sum it with a uniform random number for the remainder of the bigint
                limit = new BigInt(data);
            }
        }
Exemplo n.º 4
0
        private string RandomIntegerBelow(string Nstr)
        {
            System.Numerics.BigInteger N = System.Numerics.BigInteger.Parse(Nstr);
            byte[] bytes = N.ToByteArray();
            System.Numerics.BigInteger R;
            var random = new Random();

            do
            {
                random.NextBytes(bytes);
                bytes[bytes.Length - 1] &= (byte)0x7F;
                R = new System.Numerics.BigInteger(bytes);
            } while (R >= N);
            return(R.ToString());
        }
Exemplo n.º 5
0
            public byte[] ToBytes()
            {
                int get = (bit / 32) + 1;

                System.Numerics.BigInteger sbi = System.Numerics.BigInteger.Zero;

                for (int a = 0; a < get; a++)
                {
                    sbi += new System.Numerics.BigInteger(bi.data[a]) << (a * 32);
                }
                //bi.data

                var data2 = sbi.ToByteArray();

                Array.Resize(ref data2, (bit + 7) / 8);

                return(data2);
            }
Exemplo n.º 6
0
        protected byte[] GetIV(byte[] ivec, TLInt offset)
        {
            var iv = new byte[ivec.Length];

            Buffer.BlockCopy(ivec, 0, iv, 0, ivec.Length);

            Array.Reverse(iv);
            var bi = new System.Numerics.BigInteger(TLUtils.Combine(iv, new byte[] { 0x00 }));

            bi = (bi + offset.Value / 16);
            var biArray = bi.ToByteArray();
            var b       = new byte[16];

            Buffer.BlockCopy(biArray, 0, b, 0, Math.Min(b.Length, biArray.Length));

            Array.Reverse(b);

            return(b);
        }
Exemplo n.º 7
0
Arquivo: Utils.cs Projeto: Fart03/lau
        // Note: ivec - big-endian, but BigInterger.ctor and BigInteger.ToByteArray return little-endian
        public static byte[] AES_ctr128_encrypt(byte[] input, IBuffer key, ref byte[] ivec, ref byte[] ecount_buf, ref uint num)
        {
            uint n;
            var  output = new byte[input.Length];

            n = num;

            var provider     = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb);
            var keySymmetric = provider.CreateSymmetricKey(key);

            for (uint i = 0; i < input.Length; i++)
            {
                if (n == 0)
                {
                    var ivecBuffer   = CryptographicBuffer.CreateFromByteArray(ivec);
                    var ecountBuffer = CryptographicEngine.Encrypt(keySymmetric, ivecBuffer, null);

                    CryptographicBuffer.CopyToByteArray(ecountBuffer, out ecount_buf);
                    Array.Reverse(ivec);
                    var bi = new System.Numerics.BigInteger(TLUtils.Combine(ivec, new byte[] { 0x00 }));
                    bi = (bi + 1);
                    var biArray = bi.ToByteArray();
                    var b       = new byte[16];
                    //for (var j = 0; j < biArray.Length && j < b.Length; j++)
                    //{
                    //    b[j] = biArray[j];
                    //}

                    System.Buffer.BlockCopy(biArray, 0, b, 0, Math.Min(biArray.Length, b.Length));

                    //System.Diagnostics.Debug.WriteLine(bi);
                    Array.Reverse(b);
                    ivec = b;
                }

                output[i] = (byte)(input[i] ^ ecount_buf[n]);
                n         = (n + 1) % 16;
            }

            num = n;
            return(output);
        }
Exemplo n.º 8
0
        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            var num = new System.Numerics.BigInteger();

            for (int i = 0; i < charCount; ++i)
            {
                num *= Base;
                var index = Alphabet.IndexOf(chars[charIndex + i]);
                if (index == -1)
                {
                    throw new Exception("Illegal character " + chars[charIndex + i] + " at " + (charIndex + i));
                }
                num += index;
            }

            var numbytes = num.ToByteArray();
            var byteCount = GetMaxByteCount(charCount);
            Array.Copy(numbytes, 0, bytes, byteIndex, Math.Min(byteCount, numbytes.Length));

            return byteCount;
        }
Exemplo n.º 9
0
        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            var num = new System.Numerics.BigInteger();

            for (int i = 0; i < charCount; ++i)
            {
                num *= Base;
                var index = Alphabet.IndexOf(chars[charIndex + i]);
                if (index == -1)
                {
                    throw new Exception("Illegal character " + chars[charIndex + i] + " at " + (charIndex + i));
                }
                num += index;
            }

            var numbytes  = num.ToByteArray();
            var byteCount = GetMaxByteCount(charCount);

            Array.Copy(numbytes, 0, bytes, byteIndex, Math.Min(byteCount, numbytes.Length));

            return(byteCount);
        }
Exemplo n.º 10
0
        public static byte[] Base58CheckDecode(string base58CheckTextToDecode)
        {
            const string base58CheckCodeString = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            var bigInteger = new System.Numerics.BigInteger(0);

            var leadingZeros = 0;

            do
            {
                if (base58CheckTextToDecode[leadingZeros] == base58CheckCodeString[0])
                {
                    ++leadingZeros;
                }
            } while (base58CheckTextToDecode[leadingZeros] == base58CheckCodeString[0] && leadingZeros < base58CheckTextToDecode.Length);

            base58CheckTextToDecode = new string(base58CheckTextToDecode.ToCharArray().Skip(leadingZeros).ToArray());

            for (var i = 0; i < base58CheckTextToDecode.Length; ++i)
            {
                bigInteger *= 58;
                bigInteger += base58CheckCodeString.IndexOf(base58CheckTextToDecode[i]);
            }

            var bigIntegerArray = bigInteger.ToByteArray().Reverse().ToArray();

            bigIntegerArray = bigIntegerArray.SkipWhile(b => b == 0x00).ToArray();

            var leadingZerosArray = new byte[leadingZeros];

            for (var i = 0; i < leadingZeros; i++)
            {
                leadingZerosArray[i] = 0x00;
            }

            return(leadingZerosArray.Concat(bigIntegerArray).ToArray());
        }
Exemplo n.º 11
0
        public static byte[] AES_ctr128_encrypt2(byte[] input, byte[] key, ref byte[] ivec, ref byte[] ecount_buf, ref uint num)
        {
            uint n;
            var  output = new byte[input.Length];

            n = num;

            var cipher = CipherUtilities.GetCipher("AES/ECB/NOPADDING");
            var param  = new KeyParameter(key);

            cipher.Init(true, param);

            for (uint i = 0; i < input.Length; i++)
            {
                if (n == 0)
                {
                    ecount_buf = cipher.DoFinal(ivec);
                    Array.Reverse(ivec);
                    var bi = new System.Numerics.BigInteger(TLUtils.Combine(ivec, new byte[] { 0x00 }));
                    bi = (bi + 1);
                    var biArray = bi.ToByteArray();
                    var b       = new byte[16];
                    Buffer.BlockCopy(biArray, 0, b, 0, Math.Min(b.Length, biArray.Length));

                    //System.Diagnostics.Debug.WriteLine(bi);
                    Array.Reverse(b);
                    ivec = b;
                }

                output[i] = (byte)(input[i] ^ ecount_buf[n]);
                n         = (n + 1) % 16;
            }

            num = n;
            return(output);
        }
Exemplo n.º 12
0
        public void ToArray_Performance()
        {
            const int loopCount = 100000000;
            var bigInteger = new BigInteger(huge_a);

            var stopWatch = new Stopwatch();

            GC.Collect();
            GC.WaitForFullGCComplete();

            stopWatch.Start();

            for (var i = 0; i < loopCount; i++)
            {
                bigInteger.ToByteArray();
            }

            GC.Collect();
            GC.WaitForFullGCComplete();

            stopWatch.Stop();

            Console.WriteLine(stopWatch.ElapsedMilliseconds);
        }
Exemplo n.º 13
0
 public int IntValue()
 {
     return(sign * bi.ToByteArray()[0]);
 }
Exemplo n.º 14
0
 /// <summary>
 /// Возвращает случайное число, не превышающее MaxValue.
 /// </summary>
 /// <param name="MaxValue">Верхний исключённый предел.</param>
 /// <returns>Случайное число, не превышающее MaxValue.</returns>
 public BigInt Next_BigInt(BigInt MaxValue)
 {
     return(GetBigInt(MaxValue.ToByteArray()));
 }
Exemplo n.º 15
0
        public void LongCtorRoundTrip()
        {
            long[] values =
            {
                0L, long.MinValue, long.MaxValue, -1, 1L + int.MaxValue, -1L + int.MinValue, 0x1234, 0xFFFFFFFFL,
                0x1FFFFFFFFL, -0xFFFFFFFFL, -0x1FFFFFFFFL, 0x100000000L, -0x100000000L, 0x100000001L, -0x100000001L,
                4294967295L, -4294967295L, 4294967296L, -4294967296L
            };

            foreach (var val in values)
            {
                try
                {
                    var a = new BigInteger(val);
                    var b = new BigInteger(a.ToByteArray());

                    Assert.AreEqual(val, (long) a, "#a_" + val);
                    Assert.AreEqual(val, (long) b, "#b_" + val);
                    Assert.AreEqual(a, b, "#a  == #b (" + val + ")");
                }
                catch (Exception e)
                {
                    Assert.Fail("Failed to roundtrip {0}: {1}", val, e);
                }
            }
        }
Exemplo n.º 16
0
        public void IntCtorRoundTrip()
        {
            int[] values =
            {
                int.MinValue, -0x2F33BB, -0x1F33, -0x33, 0, 0x33,
                0x80, 0x8190, 0xFF0011, 0x1234, 0x11BB99, 0x44BB22CC,
                int.MaxValue
            };

            foreach (var val in values)
            {
                var a = new BigInteger(val);
                var b = new BigInteger(a.ToByteArray());

                Assert.AreEqual(val, (int)a, "#a_" + val);
                Assert.AreEqual(val, (int)b, "#b_" + val);
            }
        }
Exemplo n.º 17
0
        public static BigInt Random(this Random generator, BigInt limit) {
            ContractUtils.Requires(limit.Sign > 0, "limit");
            ContractUtils.RequiresNotNull(generator, "generator");

            BigInt res = BigInt.Zero;

            while (true) {
                // if we've run out of significant digits, we can return the total
                if (limit == BigInt.Zero) {
                    return res;
                }

                // if we're small enough to fit in an int, do so
                int iLimit;
                if (limit.AsInt32(out iLimit)) {
                    return res + generator.Next(iLimit);
                }

                // get the 3 or 4 uppermost bytes that fit into an int
                int hiData;
                byte[] data = limit.ToByteArray();
                int index = data.Length;
                while (data[--index] == 0) ;
                if (data[index] < 0x80) {
                    hiData = data[index] << 24;
                    data[index--] = (byte)0;
                } else {
                    hiData = 0;
                }
                hiData |= data[index] << 16;
                data[index--] = (byte)0;
                hiData |= data[index] << 8;
                data[index--] = (byte)0;
                hiData |= data[index];
                data[index--] = (byte)0;

                // get a uniform random number for the uppermost portion of the bigint
                byte[] randomData = new byte[index + 2];
                generator.NextBytes(randomData);
                randomData[index + 1] = (byte)0;
                res += new BigInt(randomData);
                res += (BigInt)generator.Next(hiData) << ((index + 1) * 8);

                // sum it with a uniform random number for the remainder of the bigint
                limit = new BigInt(data);
            }
        }
Exemplo n.º 18
0
        public static bool IsProbablyPrime(this BigInteger value, int witnesses = 10)
        {
            if (value <= 1 || value.IsEven)
            {
                return(false);
            }

            if (witnesses <= 0)
            {
                witnesses = 10;
            }

            BigInteger d = value - 1;
            int        s = 0;

            while (d % 2 == 0)
            {
                d /= 2;
                s += 1;
            }

            Byte[]     bytes = new Byte[value.ToByteArray().LongLength];
            BigInteger a;

            for (int i = 0; i < witnesses; i++)
            {
                do
                {
                    Rng.GetBytes(bytes);

                    a = new BigInteger(bytes);
                } while (a < 2 || a >= value - 2);

                BigInteger x = BigInteger.ModPow(a, d, value);
                if (x == 1 || x == value - 1)
                {
                    continue;
                }

                for (int r = 1; r < s; r++)
                {
                    x = BigInteger.ModPow(x, 2, value);

                    if (x == 1)
                    {
                        return(false);
                    }
                    if (x == value - 1)
                    {
                        break;
                    }
                }

                if (x != value - 1)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Return the value of this BigInteger as a little-endian twos-complement
 /// byte array, using the fewest number of bytes possible. If the value is zero,
 /// return an array of one byte whose element is 0x00.
 /// </summary>
 public byte[] ToByteArray()
 {
     return(Value.ToByteArray());
 }
Exemplo n.º 20
0
        public override string /*!*/ ToString()
        {
            Contract.Ensures(Contract.Result <string>() != null);
            if (value == "")
            {
                byte[]        sigBytes = significand.ToByteArray();
                StringBuilder binSig   = new StringBuilder();

                if (exponent == 0)
                {
                    binSig.Append('0');
                }
                else
                {
                    binSig.Append('1'); //hidden bit
                }

                for (int i = significandSize - 2; i >= 0; --i)
                {
                    //little endian
                    if (i / 8 < sigBytes.Length)
                    {
                        binSig.Append((char)('0' + ((sigBytes[i / 8] >> (i % 8)) & 1)));
                    }
                    else
                    {
                        binSig.Append('0');
                    }
                }

                BIM bias = BIM.Pow(2, exponentSize - 1) - 1;
                if (exponent == 0)
                {
                    --bias;
                }

                int moveDec  = ((int)((exponent - bias) % 4) + 4) % 4;
                BIM finalExp = (exponent - bias - moveDec) / 4;

                string leftBinSig  = binSig.ToString().Substring(0, moveDec + 1);
                string rightBinSig = binSig.ToString().Substring(moveDec + 1);

                leftBinSig  = new string('0', 4 - leftBinSig.Length % 4) + leftBinSig;
                rightBinSig = rightBinSig + new string('0', 4 - rightBinSig.Length % 4);

                StringBuilder leftHexSig  = new StringBuilder();
                StringBuilder rightHexSig = new StringBuilder();

                for (int i = 0; i < leftBinSig.Length / 4; ++i)
                {
                    leftHexSig.AppendFormat("{0:X}", Convert.ToByte(leftBinSig.Substring(i * 4, 4), 2));
                }

                for (int i = 0; i < rightBinSig.Length / 4; ++i)
                {
                    rightHexSig.AppendFormat("{0:X}", Convert.ToByte(rightBinSig.Substring(i * 4, 4), 2));
                }

                return(String.Format("{0}0x{1}.{2}e{3}f{4}e{5}", isSignBitSet ? "-" : "", leftHexSig, rightHexSig, finalExp,
                                     significandSize, exponentSize));
            }

            return(String.Format("0{0}{1}e{2}", value, significandSize, exponentSize));
        }