ToString() public method

public ToString ( ) : string
return string
Ejemplo n.º 1
0
    /*
        Write a method that adds two positive integer numbers represented as
        arrays of digits (each array element arr[i] contains a digit; the last
        digit is kept in arr[0]). Each of the numbers that will be added
        could have up to 10 000 digits.
    */
    static BigInteger AddNumbers(BigInteger num1, BigInteger num2)
    {
        if (num1.ToString().Length < num2.ToString().Length)
        {
            BigInteger tempNum = num1;

            num1 = num2;
            num2 = tempNum;
        }

        char[] longerArr = num1.ToString().ToCharArray();       // Inserting the number in char array
        Array.Reverse(longerArr);

        char[] shorterArr = num2.ToString().ToCharArray();      // Inserting the number in char array
        Array.Reverse(shorterArr);

        byte[] summedNum = new byte[longerArr.Length + 1];

        for (int i = 0; i < shorterArr.Length; i++)
        {
            byte rest = 0;
            byte digitInMind = 0;        // We can have only 0 or 1 in mind because we sum the digits from 0 to 9

            // If the sum of the current digits is bigger than 10, we will
            // have 1 in mind. In the other case we will just sum them.
            if ((Convert.ToInt32(longerArr[i]) +                // Subtract 96 because it sum the ASCII codes and we have two
                Convert.ToInt32(shorterArr[i]) - 96) > 9)       // numbers. They ASCII code of the numbers starts from 48. So 2x48
            {
                digitInMind = 1;
                rest = (byte)((Convert.ToInt32(longerArr[i]) + Convert.ToInt32(shorterArr[i]) - 96) % 10);
            }
            else
            {
                rest = (byte)(Convert.ToInt32(longerArr[i]) + Convert.ToInt32(shorterArr[i] - 96));
            }

            summedNum[i] += rest;                   // Add the result to cell in the summed array
            summedNum[i + 1] += digitInMind;        // Add the "1" in mind to next cell in the summed array
        }

        // Adding the rest digits of the longer num
        // when shorter num has no more digits.
        for (int i = shorterArr.Length; i < longerArr.Length; i++)
        {
            summedNum[i] = (byte)(longerArr[i] - 48);
        }

        Array.Reverse(summedNum);       // Reversing the number to get in the correct order

        string result = "";

        // Putting every digit in 1 string
        for (int i = 0; i < summedNum.Length; i++)
        {
            result += summedNum[i];
        }

        return BigInteger.Parse(result);       // Convert and return the string as number. Also removes the 0 in front.
    }
Ejemplo n.º 2
0
 private static int[] ConvertToArray(BigInteger num)
 {
     int[] digits = new int[num.ToString().Length];
     string number = num.ToString();
     BigInteger currentNumber = num;
     for (int i = number.Length - 1; i >= 0; i--)
     {
         digits[i] = (int)(currentNumber % 10);
         currentNumber /= 10;
     }
     return digits;
 }
    static int[] IntegerRepresentedAsArray(BigInteger number)
    {
        int[] numArray = new int[number.ToString().Length];
        int index = 0;
        foreach (char num in number.ToString())
        {
            numArray[index] = (int)(number % 10);
            number /= 10;
            ++index;
        }

        return numArray;
    }
        public object Convert(object value, Type targetType,
                              object parameter, CultureInfo culture)
        {
            BigInteger buffer = value as BigInteger;

            return(buffer?.ToString());
        }
Ejemplo n.º 5
0
		public void Big()
		{
			BigInteger BigInteger = new BigInteger(int.MaxValue);
			BigInteger += BigInteger += BigInteger += BigInteger;
			long longX = int.MaxValue;
			longX += longX += longX += longX;
			Assert.Equal(BigInteger.ToString(), longX.ToString());
		}
Ejemplo n.º 6
0
 public void DisplayTapValueAt(Vector3 position, BigInteger value)
 {
     GameObject canvas = GameObject.Find("Canvas");
     GameObject text = (GameObject) Instantiate(risingText);
     text.transform.position = position;
     text.transform.SetParent(canvas.transform);
     text.GetComponent<RisingText>().Setup("+" + value.ToString(), 3f, 100f);
 }
Ejemplo n.º 7
0
 static void Main(String[] args)
 {
     BigInteger number = new BigInteger(1);
     int n = int.Parse(Console.ReadLine());
     for (int i = 0; i < n; i++)
     {
         number = BigInteger.Multiply(number, new BigInteger(i + 1));
     }
     Console.WriteLine(number.ToString());
 }
Ejemplo n.º 8
0
 public static void Main()
 {
     BigInteger n = new BigInteger(1);
      	/* Left bit shifting is the same as raising to power of 2 */
     n <<= 1000;
     String s = n.ToString();
     int sum = 0;
     for(int i = 0, j = s.Length; i < j; sum += Int32.Parse(s.Substring(i, 1)), i++)
         ;
     Console.WriteLine(sum);
 }
Ejemplo n.º 9
0
    static void Main(string[] args)
    {
        long value = Basics.getLong ("Ingresa un número: ");

        BigInteger number = new BigInteger (value);
        number = Factorial (number);

        Console.WriteLine (number.ToString ("N0"));

        Console.Read ();
    }
Ejemplo n.º 10
0
 //converts a number to an array where the last digit is at index 0
 static BigInteger[] NumberToArray(BigInteger number)
 {
     string numberString = number.ToString();
     BigInteger[] numberArr = new BigInteger[numberString.Length];
     for (int i = 0; i < numberArr.Length; i++)
     {
         numberArr[i] = number % 10;
         number /= 10;
     }
     return numberArr;
 }
Ejemplo n.º 11
0
 static int[] FillArray(BigInteger number)
 {
     string numberToString = number.ToString();
     int numberLength = numberToString.Length;
     int[] array = new int[numberLength];
     for (int i = numberLength - 1; i >= 0; i--)
     {
         array[i] = (int)number % 10;
         number /= 10;
     }
     return array;
 }
Ejemplo n.º 12
0
 private static int[] InputToArray(BigInteger input)
 {
     int[] arr = new int[input.ToString().Length];
     BigInteger number = input;
     int len = number.ToString().Length;
     for (int i = 0; i < len; i++)
     {
         arr[i] = (int)number % 10;
         number /= 10;
     }
     Array.Reverse(arr);
     return arr;
 }
Ejemplo n.º 13
0
 public string GetN(int n)
 {
     BigInteger n0 = new BigInteger(this.a);
     BigInteger n1 = new BigInteger(this.b);
     BigInteger n2 = new BigInteger(0);
     int i = 2;
     while (i < n)
     {
         n2 = BigInteger.Add(BigInteger.Multiply(n1, n1), n0);
         n0 = n1;
         n1 = n2;
         i++;
     }
     return n1.ToString();
 }
Ejemplo n.º 14
0
        static string GetHashOfPermutation(BigInteger i)
        {
            List<int> numberDigits = new List<int>();
            string s = i.ToString();

            for (int a = 0; a < s.Length; a++)
                numberDigits.Add(System.Convert.ToInt16(s.Substring(a, 1)));

            numberDigits.Sort();
            s = "";

            foreach (int j in numberDigits)
                s += j.ToString();

            // Hash is the number sorted from lowest to highest value
            return s;
        }
Ejemplo n.º 15
0
        private static bool VerifyCtorInt32(Int32 value)
        {
            bool ret = true;
            BigInteger bigInteger;

            bigInteger = new BigInteger(value);

            if (!bigInteger.Equals(value))
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to Int32 {1}", bigInteger, value);
                ret = false;
            }
            if (String.CompareOrdinal(value.ToString(), bigInteger.ToString()) != 0)
            {
                Console.WriteLine("Int32.ToString() and BigInteger.ToString() on {0} and {1} should be equal", value, bigInteger);
                ret = false;
            }
            if (value != (Int32)bigInteger)
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to Int32 {1}", bigInteger, value);
                ret = false;
            }

            if (value != Int32.MaxValue)
            {
                if ((Int32)(value + 1) != (Int32)(bigInteger + 1))
                {
                    Console.WriteLine("Adding 1 to both {0} and {1} should remain equal", value, bigInteger);
                    ret = false;
                }
            }

            if (value != Int32.MinValue)
            {
                if ((Int32)(value - 1) != (Int32)(bigInteger - 1))
                {
                    Console.WriteLine("Subtracting 1 from both {0} and {1} should remain equal", value, bigInteger);
                    ret = false;
                }
            }

            Assert.True(VerifyBigintegerUsingIdentities(bigInteger, 0 == value), " Verification Failed");

            return ret;
        }
Ejemplo n.º 16
0
        private void btnOpen_Click(object sender, EventArgs e)
        {
            string tempKi = "";
            Ki = Sign.BI_Generate_Ki();
            tempKi = Ki.ToString();            

            try
            {
                Ki = new BigInteger(tempKi, 10);
                find = true;
                txtPrivateKey.Text = Ki.ToString();
                
            }
            catch
            {
                MessageBox.Show("Неверный ключ");
            }            

        }
Ejemplo n.º 17
0
    private static ulong ZeroesCounter(BigInteger factorial)
    {
        string factorialToString = factorial.ToString ();
        ulong counter = 0;
        int[] array = new int[factorialToString.Length];
        for (int i = 0; i < factorialToString.Length; i++) {
            array[i]=factorialToString[factorialToString.Length-1 -i] - '0';
        }

        for (int i = 0; i < array.Length-1; i++) {
            if(array[i]==0) {
                counter++;
                if (array[i+1]!=0) {
                    break;
                }
            }
        }
        return counter;
    }
Ejemplo n.º 18
0
        public Task <DryRunResults> DryRunTransactionsAsync(List <Dictionary <AccountParameter, object> > accounts, BigInteger?block, List <UnsignedTx> unsignedTransactions, CancellationToken token = default(CancellationToken))
        {
            DryRunInput body = new DryRunInput();

            if (accounts == null || accounts.Count == 0)
            {
                throw new ArgumentException($"Invalid Parameter accounts: {Validation.NO_ENTRIES}");
            }
            if (unsignedTransactions == null || unsignedTransactions.Count == 0)
            {
                throw new ArgumentException($"Invalid Parameter unsignedTransactions: {Validation.NO_ENTRIES}");
            }
            if (accounts.Count != unsignedTransactions.Count)
            {
                throw new ArgumentException($"Invalid Parameter unsignedTransactions: {Validation.LIST_NOT_SAME_SIZE}");
            }
            List <DryRunAccount> dryRunAccounts = new List <DryRunAccount>();

            foreach (Dictionary <AccountParameter, object> txParams in accounts)
            {
                DryRunAccount currAccount = new DryRunAccount();
                if (txParams.Count == 0)
                {
                    throw new ArgumentException($"Invalid Parameter accounts.Dictionary: {Validation.NO_ENTRIES}");
                }
                if (!txParams.ContainsKey(AccountParameter.PUBLIC_KEY))
                {
                    throw new ArgumentException($"Invalid Parameter accounts.Dictionary missing value: {string.Format(Validation.MAP_MISSING_VALUE, AccountParameter.PUBLIC_KEY)}");
                }
                currAccount.PublicKey = txParams[AccountParameter.PUBLIC_KEY].ToString();
                currAccount.Amount    = txParams.ContainsKey(AccountParameter.AMOUNT) ? BigInteger.Parse(txParams[AccountParameter.AMOUNT].ToString()) : BigInteger.Zero;
                dryRunAccounts.Add(currAccount);
            }

            body.Accounts = dryRunAccounts;
            body.Top      = block?.ToString();
            unsignedTransactions.ForEach(item => body.TXs.Add(new DryRunInputItem {
                CallReq = null, TX = item.TX
            }));
            _logger.LogDebug("Calling dry run on block {0} with body {1}", block, body);
            return(_apiClient.DryRunTxsAsync(body, token));
        }
Ejemplo n.º 19
0
        private static void VerifyCtorInt32(Int32 value)
        {
            BigInteger bigInteger = new BigInteger(value);

            Assert.Equal(value, bigInteger);
            Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString()));
            Assert.Equal(value, (Int32)bigInteger);

            if (value != Int32.MaxValue)
            {
                Assert.Equal((Int32)(value + 1), (Int32)(bigInteger + 1));
            }

            if (value != Int32.MinValue)
            {
                Assert.Equal((Int32)(value - 1), (Int32)(bigInteger - 1));
            }

            VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
        }
Ejemplo n.º 20
0
    // waaaaaaay too much parameters, should be less than 3
    public void DisplayTapValueAt(Vector2 position, BigInteger value, bool special)
    {
        GameObject canvas = GameObject.Find("Canvas");
        GameObject text = (GameObject) Instantiate(risingText);
        text.transform.position = position;
        text.transform.SetParent(canvas.transform);

        RisingText rising = text.GetComponent<RisingText>();
        rising.Text = "+" + value.ToString();
        rising.Duration = 3f;
        rising.UpSpeed = 100f;

        if (special) {
            rising.Color = Color.yellow;
            rising.FontSize = 20;
        } else
        {
            rising.Color = Color.white;
            rising.FontSize = 16;
        }

        rising.Init();
    }
Ejemplo n.º 21
0
    static void Main()
    {
        BigInteger number = BigInteger.Parse(Console.ReadLine());

        BigInteger result = 1;

        int counter = 0;

        while (number > 1)
        {
            counter = 1;
            number  = number / 10;

            string currentnumber = number.ToString();

            BigInteger currentEvenSum = 0;

            for (int i = 0; i < currentnumber.Length; i++)
            {
                if (i % 2 == 0)
                {
                    currentEvenSum += currentnumber[i] - '0';
                }
            }
            if (currentEvenSum != 0)
            {
                result *= currentEvenSum;
            }
        }

        while (result > 10)
        {
            counter++;

            if (counter > 10)
            {
                break;
            }

            number = result;
            result = 1;

            while (number > 1)
            {
                number = number / 10;

                string currentnumber = number.ToString();

                BigInteger currentEvenSum = 0;

                for (int i = 0; i < currentnumber.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        currentEvenSum += currentnumber[i] - '0';
                    }
                }
                if (currentEvenSum != 0)
                {
                    result *= currentEvenSum;
                }
            }
        }

        if (counter < 10)
        {
            Console.WriteLine(counter);
            Console.WriteLine(result);
        }
        else
        {
            Console.WriteLine(result);
        }
    }
Ejemplo n.º 22
0
        public static void Main(string[] args)
        {
                // Known problem -> these two pseudoprimes passes my implementation of
                // primality test but failed in JDK's isProbablePrime test.

                byte[] pseudoPrime1 = { (byte)0x00,
                        (byte)0x85, (byte)0x84, (byte)0x64, (byte)0xFD, (byte)0x70, (byte)0x6A,
                        (byte)0x9F, (byte)0xF0, (byte)0x94, (byte)0x0C, (byte)0x3E, (byte)0x2C,
                        (byte)0x74, (byte)0x34, (byte)0x05, (byte)0xC9, (byte)0x55, (byte)0xB3,
                        (byte)0x85, (byte)0x32, (byte)0x98, (byte)0x71, (byte)0xF9, (byte)0x41,
                        (byte)0x21, (byte)0x5F, (byte)0x02, (byte)0x9E, (byte)0xEA, (byte)0x56,
                        (byte)0x8D, (byte)0x8C, (byte)0x44, (byte)0xCC, (byte)0xEE, (byte)0xEE,
                        (byte)0x3D, (byte)0x2C, (byte)0x9D, (byte)0x2C, (byte)0x12, (byte)0x41,
                        (byte)0x1E, (byte)0xF1, (byte)0xC5, (byte)0x32, (byte)0xC3, (byte)0xAA,
                        (byte)0x31, (byte)0x4A, (byte)0x52, (byte)0xD8, (byte)0xE8, (byte)0xAF,
                        (byte)0x42, (byte)0xF4, (byte)0x72, (byte)0xA1, (byte)0x2A, (byte)0x0D,
                        (byte)0x97, (byte)0xB1, (byte)0x31, (byte)0xB3,
                };

                byte[] pseudoPrime2 = { (byte)0x00,
                        (byte)0x99, (byte)0x98, (byte)0xCA, (byte)0xB8, (byte)0x5E, (byte)0xD7,
                        (byte)0xE5, (byte)0xDC, (byte)0x28, (byte)0x5C, (byte)0x6F, (byte)0x0E,
                        (byte)0x15, (byte)0x09, (byte)0x59, (byte)0x6E, (byte)0x84, (byte)0xF3,
                        (byte)0x81, (byte)0xCD, (byte)0xDE, (byte)0x42, (byte)0xDC, (byte)0x93,
                        (byte)0xC2, (byte)0x7A, (byte)0x62, (byte)0xAC, (byte)0x6C, (byte)0xAF,
                        (byte)0xDE, (byte)0x74, (byte)0xE3, (byte)0xCB, (byte)0x60, (byte)0x20,
                        (byte)0x38, (byte)0x9C, (byte)0x21, (byte)0xC3, (byte)0xDC, (byte)0xC8,
                        (byte)0xA2, (byte)0x4D, (byte)0xC6, (byte)0x2A, (byte)0x35, (byte)0x7F,
                        (byte)0xF3, (byte)0xA9, (byte)0xE8, (byte)0x1D, (byte)0x7B, (byte)0x2C,
                        (byte)0x78, (byte)0xFA, (byte)0xB8, (byte)0x02, (byte)0x55, (byte)0x80,
                        (byte)0x9B, (byte)0xC2, (byte)0xA5, (byte)0xCB,
                };

                Console.WriteLine("List of primes < 2000\n---------------------");
                int limit = 100, count = 0;
                for(int i = 0; i < 2000; i++)
                {
                        if(i >= limit)
                        {
                                Console.WriteLine();
                                limit += 100;
                        }

                        BigInteger p = new BigInteger(-i);

                        if(p.isProbablePrime())
                        {
                                Console.Write(i + ", ");
                                count++;
                        }
                }
                Console.WriteLine("\nCount = " + count);


                BigInteger bi1 = new BigInteger(pseudoPrime1);
                Console.WriteLine("\n\nPrimality testing for\n" + bi1.ToString() + "\n");
                Console.WriteLine("SolovayStrassenTest(5) = " + bi1.SolovayStrassenTest(5));
                Console.WriteLine("RabinMillerTest(5) = " + bi1.RabinMillerTest(5));
                Console.WriteLine("FermatLittleTest(5) = " + bi1.FermatLittleTest(5));
                Console.WriteLine("isProbablePrime() = " + bi1.isProbablePrime());

                Console.Write("\nGenerating 512-bits random pseudoprime. . .");
                Random rand = new Random();
                BigInteger prime = BigInteger.genPseudoPrime(512, 5, rand);
                Console.WriteLine("\n" + prime);

                //int dwStart = System.Environment.TickCount;
                //BigInteger.MulDivTest(100000);
                //BigInteger.RSATest(10);
                //BigInteger.RSATest2(10);
                //Console.WriteLine(System.Environment.TickCount - dwStart);

        }
Ejemplo n.º 23
0
 /// <summary>
 ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
 ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
 ///     any release. You should only use it directly in your code with extreme caution and knowing that
 ///     doing so can result in application failures when updating to a new Entity Framework Core release.
 /// </summary>
 public virtual string Literal(BigInteger value)
 => $"BigInteger.Parse(\"{value.ToString(NumberFormatInfo.InvariantInfo)}\", NumberFormatInfo.InvariantInfo)";
Ejemplo n.º 24
0
    private static string RenderFormat(PrintfFormat format, Variable arg)
    {
        int n;

        if (format.directive == PrintfDirective.String)
        {
            return(arg.Fetch().mo.mro_raw_Str.Get(arg));
        }

        if (format.directive == PrintfDirective.CodePoint)
        {
            n = (int)arg.Fetch().mo.mro_raw_Numeric.Get(arg);
            return("" + (char)n);
        }

        bool add_minus_sign = false;

        if (format.directive == PrintfDirective.Int)
        {
            P6any    o1 = arg.Fetch();
            int      r1;
            P6any    n1 = GetNumber(arg, o1, out r1);
            Variable arg2;

            if (r1 != NR_BIGINT && r1 != NR_FIXINT)
            {
                arg2 = Builtins.InvokeMethod("Int", arg);
                o1   = arg2.Fetch();
                n1   = GetNumber(arg2, o1, out r1);
            }

            BigInteger value = PromoteToBigInt(r1, n1);
            if (value < 0)
            {
                add_minus_sign = true;
                value          = -value;
            }

            String number;
            if (format.radix == 16)
            {
                number = RemoveInitialZero(value.ToString(format.radix, null)).ToLower();
            }
            else
            {
                number = value.ToString(format.radix, null);
            }

            if (format.upper)
            {
                number = number.ToUpper();
            }

            if (add_minus_sign)
            {
                if (format.rightJustifyZeroes)
                {
                    return("-" + number.PadLeft(format.minimumWidth - 1, '0'));
                }
                else
                {
                    return("-" + number);
                }
            }

            return(number);
        }
        else
        {
            double f = arg.Fetch().mo.mro_raw_Numeric.Get(arg);

            if (f < 0.0)
            {
                add_minus_sign = true;
                f = -f;
            }

            int precision = format.precision > 0 ? format.precision : 6;

            String number = "??";
            switch (format.directive)
            {
            case PrintfDirective.FloatFixedDecimal:
                number = f.ToString("F" + precision);
                break;

            case PrintfDirective.FloatScientific:
                number = f.ToString("e" + precision);
                break;

            case PrintfDirective.FloatEF:
                number = f.ToString("g" + precision);
                break;
            }

            if (format.upper)
            {
                number = number.ToUpper();
            }

            if (add_minus_sign)
            {
                if (format.rightJustifyZeroes)
                {
                    return("-" + number.PadLeft(format.minimumWidth - 1, '0'));
                }
                else
                {
                    return("-" + number);
                }
            }

            return(number);
        }
    }
Ejemplo n.º 25
0
        protected override async Task OnUpdate()
        {
            _dbContext.DetachEverything();

            // get events
            var log = await _ethereumReader.GatherPoolFreezerEvents(_lastBlock - 1, _lastBlock + _blocksPerRound, _confirmationsRequired);

            _lastBlock = log.ToBlock;

            Logger.Debug(
                (log.Events.Length > 0
                                        ? $"{log.Events.Length} request(s) found"
                                        : "Nothing found"
                ) + $" in blocks [{log.FromBlock} - {log.ToBlock}]"
                );

            if (IsCancelled())
            {
                return;
            }

            foreach (var v in log.Events)
            {
                if (IsCancelled())
                {
                    return;
                }
                Logger.Debug($"Trying to enqueue pool-freezer event with tx {v.TransactionId}");

                try {
                    var model = new DAL.Models.PoolFreezeRequest()
                    {
                        Status         = EmissionRequestStatus.Initial,
                        EthAddress     = v.Address,
                        EthTransaction = v.TransactionId,
                        Amount         = v.Amount.FromSumus(),
                        SumAddress     = v.SumusAddress,
                        SumTransaction = null,
                        TimeCreated    = DateTime.UtcNow,
                        TimeCompleted  = null,
                    };
                    _dbContext.PoolFreezeRequest.Add(model);
                    await _dbContext.SaveChangesAsync();

                    Logger.Information(
                        $"Pool-freezer event enqueued for tx {v.TransactionId}"
                        );
                } catch (Exception e) {
                    if (!ExceptionExtension.IsMySqlDuplicateException(e))
                    {
                        Logger.Error(e, $"Pool-freezer event failed with tx {v.TransactionId}");
                    }
                }

                ++_statProcessed;
            }

            // save last index to settings
            if (_lastSavedBlock != _lastBlock)
            {
                if (await _dbContext.SaveDbSetting(DbSetting.PoolFreezerHarvLastBlock, _lastBlock.ToString()))
                {
                    _lastSavedBlock = _lastBlock;
                    Logger.Debug($"Last block #{_lastBlock} saved to DB");
                }
            }
        }
Ejemplo n.º 26
0
        private BigInteger ReverseNumber(BigInteger number)
        {
            string reversedNumberString = new string(number.ToString().Reverse().ToArray());

            return(BigInteger.Parse(reversedNumberString));
        }
Ejemplo n.º 27
0
 public static BigDecimal InducedFrom(RubyContext /*!*/ context, RubyClass /*!*/ self, [NotNull] BigInteger /*!*/ value)
 {
     return(BigDecimal.Create(GetConfig(context), value.ToString(CultureInfo.InvariantCulture)));
 }
Ejemplo n.º 28
0
 public static string __repr__([NotNull] BigInteger /*!*/ self)
 {
     return(self.ToString());
 }
Ejemplo n.º 29
0
 public override string ToString()
 {
     return(value.ToString());
 }
Ejemplo n.º 30
0
        public static string /*!*/ __format__(CodeContext /*!*/ context, BigInteger /*!*/ self, [NotNull] string /*!*/ formatSpec)
        {
            StringFormatSpec spec = StringFormatSpec.FromString(formatSpec);

            if (spec.Precision != null)
            {
                throw PythonOps.ValueError("Precision not allowed in integer format specifier");
            }

            BigInteger val = self;

            if (self < 0)
            {
                val = -self;
            }
            string digits;

            switch (spec.Type)
            {
            case 'n':
                CultureInfo culture = context.LanguageContext.NumericCulture;

                if (culture == CultureInfo.InvariantCulture)
                {
                    // invariant culture maps to CPython's C culture, which doesn't
                    // include any formatting info.
                    goto case 'd';
                }

                digits = FormattingHelper.ToCultureString(val, context.LanguageContext.NumericCulture.NumberFormat, spec);
                break;

            case null:
            case 'd':
                if (spec.ThousandsComma)
                {
                    var width = spec.Width ?? 0;
                    // If we're inserting commas, and we're padding with leading zeros.
                    // AlignNumericText won't know where to place the commas,
                    // so force .Net to help us out here.
                    if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1)
                    {
                        digits = val.ToString(FormattingHelper.ToCultureString(self, FormattingHelper.InvariantCommaNumberInfo, spec));
                    }
                    else
                    {
                        digits = val.ToString("#,0", CultureInfo.InvariantCulture);
                    }
                }
                else
                {
                    digits = val.ToString("D", CultureInfo.InvariantCulture);
                }
                break;

            case '%':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000%", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000%", CultureInfo.InvariantCulture);
                }
                break;

            case 'e':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000e+00", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000e+00", CultureInfo.InvariantCulture);
                }
                break;

            case 'E':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000E+00", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000E+00", CultureInfo.InvariantCulture);
                }
                break;

            case 'f':
            case 'F':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,########0.000000", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("#########0.000000", CultureInfo.InvariantCulture);
                }
                break;

            case 'g':
                if (val >= 1000000)
                {
                    digits = val.ToString("0.#####e+00", CultureInfo.InvariantCulture);
                }
                else if (spec.ThousandsComma)
                {
                    goto case 'd';
                }
                else
                {
                    digits = val.ToString(CultureInfo.InvariantCulture);
                }
                break;

            case 'G':
                if (val >= 1000000)
                {
                    digits = val.ToString("0.#####E+00", CultureInfo.InvariantCulture);
                }
                else if (spec.ThousandsComma)
                {
                    goto case 'd';
                }
                else
                {
                    digits = val.ToString(CultureInfo.InvariantCulture);
                }
                break;

            case 'X':
                digits = AbsToHex(val, false);
                break;

            case 'x':
                digits = AbsToHex(val, true);
                break;

            case 'o':     // octal
                digits = ToOctal(val, true);
                break;

            case 'b':     // binary
                digits = ToBinary(val, false, true);
                break;

            case 'c':     // single char
                int iVal;
                if (spec.Sign != null)
                {
                    throw PythonOps.ValueError("Sign not allowed with integer format specifier 'c'");
                }
                else if (!self.AsInt32(out iVal))
                {
                    throw PythonOps.OverflowError("long int too large to convert to int");
                }
                else if (iVal < 0 || iVal > 0x10ffff)
                {
                    throw PythonOps.OverflowError("%c arg not in range(0x110000)");
                }

                digits = (iVal > char.MaxValue) ? char.ConvertFromUtf32(iVal) : ScriptingRuntimeHelpers.CharToString((char)iVal);
                break;

            default:
                throw PythonOps.ValueError("Unknown format code '{0}' for object of type 'int'", spec.TypeRepr);
            }

            Debug.Assert(digits[0] != '-');

            return(spec.AlignNumericText(digits, self.IsZero(), self.IsPositive()));
        }
Ejemplo n.º 31
0
        private static string /*!*/ ToExponent(BigInteger /*!*/ self, bool lower, int minPrecision, int maxPrecision)
        {
            Debug.Assert(minPrecision <= maxPrecision);

            // get all the digits
            string digits = self.ToString();

            StringBuilder tmp = new StringBuilder();

            tmp.Append(digits[0]);

            for (int i = 1; i < maxPrecision && i < digits.Length; i++)
            {
                // append if we have a significant digit or if we are forcing a minimum precision
                if (digits[i] != '0' || i <= minPrecision)
                {
                    if (tmp.Length == 1)
                    {
                        // first time we've appended, add the decimal point now
                        tmp.Append('.');
                    }

                    while (i > tmp.Length - 1)
                    {
                        // add any digits that we skipped before
                        tmp.Append('0');
                    }

                    // round up last digit if necessary
                    if (i == maxPrecision - 1 && i != digits.Length - 1 && digits[i + 1] >= '5')
                    {
                        tmp.Append((char)(digits[i] + 1));
                    }
                    else
                    {
                        tmp.Append(digits[i]);
                    }
                }
            }

            if (digits.Length <= minPrecision)
            {
                if (tmp.Length == 1)
                {
                    // first time we've appended, add the decimal point now
                    tmp.Append('.');
                }

                while (minPrecision >= tmp.Length - 1)
                {
                    tmp.Append('0');
                }
            }

            tmp.Append(lower ? "e+" : "E+");
            int digitCnt = digits.Length - 1;

            if (digitCnt < 10)
            {
                tmp.Append('0');
                tmp.Append((char)('0' + digitCnt));
            }
            else
            {
                tmp.Append(digitCnt.ToString());
            }

            digits = tmp.ToString();
            return(digits);
        }
        public void OnPost()
        {
            String          ID              = HttpContext.Session.GetString("ID");
            String          Exception       = "";
            Boolean         CheckConnection = MyOwnMySQLConnectionClass.LoadConnection(ref Exception);
            MySqlCommand    MySQLQuery      = new MySqlCommand();
            MySqlDataReader PublicKeyDBReader;
            int             Checker           = 0;
            DateTime        MyUTCDateTime     = DateTime.UtcNow.AddHours(8);
            String          PrivateKeyString  = Request.Form["SK_Diffie_Hellman"].ToString();
            String          Current_User      = HttpContext.Session.GetString("User_Name");
            String          PublicKeyStringDB = "";
            BigInteger      PrivateKey        = BigInteger.Parse(PrivateKeyString);
            BigInteger      PublicKey         = 0;

            Byte[] PrivateKeyBytes = new Byte[] { };
            Byte[] PublicKeyBytes  = new Byte[] { };
            PrivateKeyBytes        = PrivateKey.ToByteArray();
            PublicKeyBytes         = ScalarMult.Base(PrivateKeyBytes);
            PublicKey              = new BigInteger(PublicKeyBytes);
            MySQLQuery.CommandText = "SELECT COUNT(*) FROM `DF_Public_Key` WHERE `Requestor_1`=@Current_User AND `ID`=@ID";
            MySQLQuery.Parameters.Add("@Current_User", MySqlDbType.Text).Value = Current_User;
            MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value           = ID;
            MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection;
            MySQLQuery.Prepare();
            Checker = int.Parse(MySQLQuery.ExecuteScalar().ToString());
            if (Checker == 1)
            {
                MySQLQuery             = new MySqlCommand();
                MySQLQuery.CommandText = "SELECT `Requestor_1_PK` FROM `DF_Public_Key` WHERE `ID`=@ID";
                MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID;
                MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection;
                MySQLQuery.Prepare();
                PublicKeyDBReader = MySQLQuery.ExecuteReader();
                while (PublicKeyDBReader.Read())
                {
                    PublicKeyStringDB = PublicKeyDBReader.GetValue(0).ToString();
                }
                MyOwnMySQLConnectionClass.MyMySQLConnection.Close();
                CheckConnection        = MyOwnMySQLConnectionClass.LoadConnection(ref Exception);
                MySQLQuery             = new MySqlCommand();
                MySQLQuery.CommandText = "UPDATE `DF_Public_Key` SET `Last_Checked_Date_R1`=@Last_Checked_Date_R1,`Requestor_1_PK`=@Requestor_1_PK WHERE `ID`=@ID";
                MySQLQuery.Parameters.Add("@Last_Checked_Date_R1", MySqlDbType.DateTime).Value = MyUTCDateTime;
                MySQLQuery.Parameters.Add("@Requestor_1_PK", MySqlDbType.Text).Value           = PublicKey.ToString();
                MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID;
                MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection;
                MySQLQuery.Prepare();
                MySQLQuery.ExecuteNonQuery();
            }
            else
            {
                MySQLQuery             = new MySqlCommand();
                MySQLQuery.CommandText = "SELECT `Requestor_2_PK` FROM `DF_Public_Key` WHERE `ID`=@ID";
                MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID;
                MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection;
                MySQLQuery.Prepare();
                PublicKeyDBReader = MySQLQuery.ExecuteReader();
                while (PublicKeyDBReader.Read())
                {
                    PublicKeyStringDB = PublicKeyDBReader.GetValue(0).ToString();
                }
                MyOwnMySQLConnectionClass.MyMySQLConnection.Close();
                CheckConnection        = MyOwnMySQLConnectionClass.LoadConnection(ref Exception);
                MySQLQuery             = new MySqlCommand();
                MySQLQuery.CommandText = "UPDATE `DF_Public_Key` SET `Last_Checked_Date_R2`=@Last_Checked_Date_R2,`Requestor_2_PK`=@Requestor_2_PK WHERE `ID`=@ID";
                MySQLQuery.Parameters.Add("@Last_Checked_Date_R2", MySqlDbType.DateTime).Value = MyUTCDateTime;
                MySQLQuery.Parameters.Add("@Requestor_2_PK", MySqlDbType.Text).Value           = PublicKey.ToString();
                MySQLQuery.Parameters.Add("@ID", MySqlDbType.Text).Value = ID;
                MySQLQuery.Connection = MyOwnMySQLConnectionClass.MyMySQLConnection;
                MySQLQuery.Prepare();
                MySQLQuery.ExecuteNonQuery();
            }
            if (PublicKeyStringDB.CompareTo(PublicKey.ToString()) == 0)
            {
                ViewData["Result"] = "Your public key value hasn't been tampered with..";
            }
            else
            {
                ViewData["Result"] = "You better watch out someone has modified ur public key value..";
            }
            HttpContext.Session.Remove("ID");
        }
Ejemplo n.º 33
0
 private static string ToStringInternal(BigInteger value)
 {
     return(value.ToString(null, CultureInfo.InvariantCulture));
 }
Ejemplo n.º 34
0
 private static string writeHex(BigInteger value)
 {
     return(value.ToString("x").TrimStart('0'));
 }
Ejemplo n.º 35
0
 private int GetEthUnitValueLength(BigInteger unitValue)
 {
     return(unitValue.ToString().Length - 1);
 }
Ejemplo n.º 36
0
 public string ToString(int radix)
 {
     return(_value.ToString(radix));
 }
Ejemplo n.º 37
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings)
        {
            if (certificateCreationSettings == null)
            {
                if (isAuthority)
                {
                    certificateCreationSettings = new CertificateCreationSettings();
                }
                else
                {
                    throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false");
                }
            }

            // Set to default cert creation settings if not set
            if (certificateCreationSettings.ValidityNotBefore == default(DateTime))
            {
                certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore;
            }
            if (certificateCreationSettings.ValidityNotAfter == default(DateTime))
            {
                certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter;
            }

            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }
            string subject = certificateCreationSettings.Subject;

            // If certificateCreationSettings.SubjectAlternativeNames == null, then we should add exactly one SubjectAlternativeName == Subject
            // so that the default certificate generated is compatible with mainline scenarios
            // However, if certificateCreationSettings.SubjectAlternativeNames == string[0], then allow this as this is a legit scenario we want to test out
            if (certificateCreationSettings.SubjectAlternativeNames == null)
            {
                certificateCreationSettings.SubjectAlternativeNames = new string[1] {
                    subject
                };
            }

            string[] subjectAlternativeNames = certificateCreationSettings.SubjectAlternativeNames;

            if (!isAuthority && string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subject");
            }

            EnsureInitialized();

            _certGenerator.Reset();
            _certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName);
            var      serialNum         = new BigInteger(64 /*sizeInBits*/, _random).Abs();

            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();

            if (isAuthority)
            {
                _certGenerator.SetIssuerDN(authorityX509Name);
                _certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    serialNum);

                _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);
                _certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));
            }
            else
            {
                X509Name subjectName = CreateX509Name(subject);
                _certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                _certGenerator.SetSubjectDN(subjectName);

                _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                _certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));
            }

            _certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            _certGenerator.SetSerialNumber(serialNum);
            _certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore);
            _certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter);
            _certGenerator.SetPublicKey(keyPair.Public);

            _certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            _certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List <Asn1Encodable> subjectAlternativeNamesAsAsn1EncodableList = new List <Asn1Encodable>();

                    // All endpoints should also be in the Subject Alt Names
                    for (int i = 0; i < subjectAlternativeNames.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNamesAsAsn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternativeNames[i]));
                        }
                    }

                    _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList.ToArray()));
                }
                else
                {
                    if (subjectAlternativeNames.Length > 1)
                    {
                        var subjectAlternativeNamesAsAsn1EncodableList = new Asn1EncodableVector();

                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjectAlternativeNames.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjectAlternativeNames[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNamesAsAsn1EncodableList.Add(genName);
                            }
                        }
                        _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList));
                    }
                }
            }

            // Our CRL Distribution Point has the serial number in the query string to fool Windows into doing a fresh query
            // rather than using a cached copy of the CRL in the case where the CRL has been previously accessed before
            var crlDistributionPoints = new DistributionPoint[2] {
                new DistributionPoint(new DistributionPointName(
                                          new GeneralNames(new GeneralName(
                                                               GeneralName.UniformResourceIdentifier, string.Format("{0}?serialNum={1}", _crlUri, serialNum.ToString(radix: 16))))),
                                      null,
                                      null),
                new DistributionPoint(new DistributionPointName(
                                          new GeneralNames(new GeneralName(
                                                               GeneralName.UniformResourceIdentifier, string.Format("{0}?serialNum={1}", _crlUri, serialNum.ToString(radix: 16))))),
                                      null,
                                      new GeneralNames(new GeneralName(authorityX509Name)))
            };
            var revocationListExtension = new CrlDistPoint(crlDistributionPoints);

            _certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);

            X509Certificate cert = _certGenerator.Generate(_authorityKeyPair.Private, _random);

            switch (certificateCreationSettings.ValidityType)
            {
            case CertificateValidityType.Revoked:
                RevokeCertificateBySerialNumber(serialNum.ToString(radix: 16));
                break;

            case CertificateValidityType.Expired:
                break;

            default:
                EnsureCertificateIsValid(cert);
                break;
            }

            // For now, given that we don't know what format to return it in, preserve the formats so we have
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer();

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry(
                certificateCreationSettings.FriendlyName != null ? certificateCreationSettings.FriendlyName : string.Empty,
                new AsymmetricKeyEntry(keyPair.Private),
                chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray();
            }

            X509Certificate2 outputCert;

            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded());
            }
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject             = subject;
            container.InternalCertificate = cert;
            container.Certificate         = outputCert;
            container.Thumbprint          = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subject));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject Alt names ", string.Join(", ", subjectAlternativeNames)));
                Trace.WriteLine(string.Format("    {0} = {1}", "Friendly Name ", certificateCreationSettings.FriendlyName));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));
            Trace.WriteLine(string.Format("    {0} = {1}", "CertificateValidityType", certificateCreationSettings.ValidityType));

            return(container);
        }
Ejemplo n.º 38
0
        private static bool VerifyCtorDecimal(Decimal value)
        {
            bool ret = true;
            Decimal expectedValue;
            BigInteger bigInteger;

            if (value < 0)
            {
                expectedValue = Math.Ceiling(value);
            }
            else
            {
                expectedValue = Math.Floor(value);
            }

            bigInteger = new BigInteger(value);

            if (!expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Decimal.ToString() and BigInteger.ToString()");
                ret = false;
            }
            if (expectedValue != (Decimal)bigInteger)
            {
                Console.WriteLine("Round tripped Decimal");
                ret = false;
            }

            if (expectedValue != Math.Floor(Decimal.MaxValue))
            {
                if ((Decimal)(expectedValue + 1) != (Decimal)(bigInteger + 1))
                {
                    Console.WriteLine("BigInteger added to 1");
                    ret = false;
                }
            }

            if (expectedValue != Math.Ceiling(Decimal.MinValue))
            {
                if ((Decimal)(expectedValue - 1) != (Decimal)(bigInteger - 1))
                {
                    Console.WriteLine("BigInteger subtracted by 1");
                    ret = false;
                }
            }

            Assert.True(VerifyBigintegerUsingIdentities(bigInteger, 0 == expectedValue), " Verification Failed");
            return ret;
        }
Ejemplo n.º 39
0
 public static string ToHex(this BigInteger i)
 {
     return(i.ToString("X"));
 }
Ejemplo n.º 40
0
        private static void VerifyComparison(BigInteger x, UInt64 y, int expectedResult)
        {
            bool expectedEquals = 0 == expectedResult;
            bool expectedLessThan = expectedResult < 0;
            bool expectedGreaterThan = expectedResult > 0;

            Assert.Equal(expectedEquals, x == y);
            Assert.Equal(expectedEquals, y == x);

            Assert.Equal(!expectedEquals, x != y);
            Assert.Equal(!expectedEquals, y != x);

            Assert.Equal(expectedEquals, x.Equals(y));

            VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");

            if (expectedEquals)
            {
                Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
                Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
            }

            Assert.Equal(x.GetHashCode(), x.GetHashCode());
            Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());

            Assert.Equal(expectedLessThan, x < y);
            Assert.Equal(expectedGreaterThan, y < x);

            Assert.Equal(expectedGreaterThan, x > y);
            Assert.Equal(expectedLessThan, y > x);

            Assert.Equal(expectedLessThan || expectedEquals, x <= y);
            Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);

            Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
            Assert.Equal(expectedLessThan || expectedEquals, y >= x);
        }
        /// <summary>
        /// Prompts the user for information for a new transaction, and
        /// then submits the transaction to the network.
        /// </summary>
        /// <param name="wallet">The wallet from which the transaction will be sent.</param>
        /// <param name="log">Logger.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        internal static async Task SendTransaction(Wallet wallet, ILogger log)
        {
            string  recipient   = ConsoleEx.PromptForAddress("Recipient (hex notation)");
            decimal amountInEth = ConsoleEx.PromptForDecimal("Amount (in ETH)");

            BigInteger gasPriceInGwei = new BigInteger(40);

            gasPriceInGwei = ConsoleEx.PromptForBigInteger(
                string.Format("Gas price (in Gwei) [{0}]", gasPriceInGwei),
                gasPriceInGwei);

            BigInteger gasAllowance = new BigInteger(21000);

            BigInteger?nonceOverride = ConsoleEx.PromptForOptionalBigInteger(
                "Nonce override (empty == automatic) []",
                null);

            var maxFeeInWei = gasAllowance * gasPriceInGwei;
            var maxFeeInEth = maxFeeInWei.WeiToEth();

            var sendChoice = "Send";
            var choice     = await Menu(
                () =>
            {
                Console.WriteLine();
                Console.WriteLine("Do you want to send this transaction?");
                Console.WriteLine("\tFrom: {0}", wallet.Address);
                Console.WriteLine("\tTo: {0}", recipient);
                Console.WriteLine("\tAmount: {0} ETH", amountInEth);
                Console.WriteLine("\tMax fee: {0} ETH", maxFeeInEth);
                Console.WriteLine("\tNonce: {0}", nonceOverride?.ToString() ?? "<automatic>");
                Console.WriteLine();
            },
                new[] { sendChoice, "Cancel" });

            if (choice == sendChoice)
            {
                Console.WriteLine("Wait a second, I'll check if we can afford this transaction... ");
                Console.WriteLine();

                var amountInWei         = amountInEth.EthToWei();
                var maxExpenditureInWei = maxFeeInWei + amountInWei;
                var knownBalanceInWei   = await wallet.FetchBalanceAsOfLastProcessedBlock();

                if (maxExpenditureInWei > knownBalanceInWei)
                {
                    Console.WriteLine("\tSORRY! I can not send this transaction:");
                    Console.WriteLine();
                    Console.WriteLine("\tThis transaction may require more ETH than you have.");
                    Console.WriteLine("\tIf you think this is an error, try re-synchronizing the wallet.");
                    return;
                }

                Console.Write("Sending... ");
                try
                {
                    var hash = await wallet.SendTransaction(
                        recipient,
                        amountInWei,
                        gasPriceInGwei.GweiToWei(),
                        gasAllowance,
                        nonceOverride);

                    Console.WriteLine("done.");
                    Console.WriteLine();
                    Console.WriteLine("You can see your transaction status at:");
                    Console.WriteLine("\thttps://rinkeby.etherscan.io/tx/{0}", hash);
                    Console.WriteLine();
                }
                catch (Exception e)
                {
                    Console.WriteLine("FAILED: {0}", e.Message);
                    log.Error(e, "Failed to send transaction");
                }
            }
            else
            {
                Console.WriteLine("Transaction cancelled");
            }
        }
Ejemplo n.º 42
0
 public static Mono.Math.BigInteger ToMonoBigInteger(BigInteger value)
 {
     return Mono.Math.BigInteger.Parse(value.ToString(10));
 }
Ejemplo n.º 43
0
        static string AnyToAny(int inputBase, string number, int outputBase)
        {
            BigInteger resultDec = 0;

            foreach (char digit in number)
            {
                int digitValue;
                if (char.IsDigit(digit))
                {
                    digitValue = digit - '0';
                }
                else
                {
                    digitValue = digit - 'A' + 10;
                }

                resultDec = resultDec * inputBase + digitValue;
            }

            string result = "";

            do
            {
                BigInteger leftoverNum = 0;

                if ((resultDec % outputBase) % 1 == 0)
                {
                    leftoverNum = resultDec % outputBase;
                }
                else
                {
                    leftoverNum = (resultDec % outputBase) * outputBase;
                }

                string leftover = leftoverNum.ToString();

                switch (leftover)
                {
                case "0": result = "0" + result; break;

                case "1": result = "1" + result; break;

                case "2": result = "2" + result; break;

                case "3": result = "3" + result; break;

                case "4": result = "4" + result; break;

                case "5": result = "5" + result; break;

                case "6": result = "6" + result; break;

                case "7": result = "7" + result; break;

                case "8": result = "8" + result; break;

                case "9": result = "9" + result; break;

                case "10": result = "A" + result; break;

                case "11": result = "B" + result; break;

                case "12": result = "C" + result; break;

                case "13": result = "D" + result; break;

                case "14": result = "E" + result; break;

                case "15": result = "F" + result; break;
                }

                resultDec /= outputBase;
            } while (resultDec != 0);

            return(result);
        }
Ejemplo n.º 44
0
        public RSAParameters ParseRSAPrivateKey()
        {
            RSAParameters parameters = new RSAParameters();

            // Current value
            byte[] value = null;

            // Checkpoint
            int position = _parser.CurrentPosition();

            // Sanity Check
            int length = 0;

            // Ignore Sequence - PrivateKeyInfo
            length = _parser.NextSequence();
            if (length != _parser.RemainingBytes())
            {
                StringBuilder sb = new StringBuilder("Incorrect Sequence Size. ");
                sb.AppendFormat("Specified: {0}, Remaining: {1}",
                                length.ToString(CultureInfo.InvariantCulture), _parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
                throw new BerDecodeException(sb.ToString(), position);
            }

            // Checkpoint
            position = _parser.CurrentPosition();
            // Version
            value = _parser.NextInteger();
            if (0x00 != value[0])
            {
                StringBuilder sb = new StringBuilder("Incorrect PrivateKeyInfo Version. ");
                BigInteger    v  = new BigInteger(value);
                sb.AppendFormat("Expected: 0, Specified: {0}", v.ToString(10));
                throw new BerDecodeException(sb.ToString(), position);
            }

            // Checkpoint
            position = _parser.CurrentPosition();

            // Ignore Sequence - AlgorithmIdentifier
            length = _parser.NextSequence();
            if (length > _parser.RemainingBytes())
            {
                StringBuilder sb = new StringBuilder("Incorrect AlgorithmIdentifier Size. ");
                sb.AppendFormat("Specified: {0}, Remaining: {1}",
                                length.ToString(CultureInfo.InvariantCulture),
                                _parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
                throw new BerDecodeException(sb.ToString(), position);
            }

            // Checkpoint
            position = _parser.CurrentPosition();

            // Grab the OID
            value = _parser.NextOID();
            byte[] oid = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
            if (!EqualOid(value, oid))
            {
                throw new BerDecodeException("Expected OID 1.2.840.113549.1.1.1", position);
            }

            // Optional Parameters
            if (_parser.IsNextNull())
            {
                _parser.NextNull();
                // Also OK: value = parser.Next();
            }
            else
            {
                // Gracefully skip the optional data
                value = _parser.Next();
            }

            // Checkpoint
            position = _parser.CurrentPosition();

            // Ignore OctetString - PrivateKey
            length = _parser.NextOctetString();
            if (length > _parser.RemainingBytes())
            {
                StringBuilder sb = new StringBuilder("Incorrect PrivateKey Size. ");
                sb.AppendFormat("Specified: {0}, Remaining: {1}",
                                length.ToString(CultureInfo.InvariantCulture),
                                _parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
                throw new BerDecodeException(sb.ToString(), position);
            }

            // Checkpoint
            position = _parser.CurrentPosition();

            // Ignore Sequence - RSAPrivateKey
            length = _parser.NextSequence();
            if (length < _parser.RemainingBytes())
            {
                StringBuilder sb = new StringBuilder("Incorrect RSAPrivateKey Size. ");
                sb.AppendFormat("Specified: {0}, Remaining: {1}",
                                length.ToString(CultureInfo.InvariantCulture),
                                _parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
                throw new BerDecodeException(sb.ToString(), position);
            }

            // Checkpoint
            position = _parser.CurrentPosition();
            // Version
            value = _parser.NextInteger();
            if (0x00 != value[0])
            {
                StringBuilder sb = new StringBuilder("Incorrect RSAPrivateKey Version. ");
                BigInteger    v  = new BigInteger(value);
                sb.AppendFormat("Expected: 0, Specified: {0}", v.ToString(10));
                throw new BerDecodeException(sb.ToString(), position);
            }

            parameters.Modulus  = TrimLeadingZero(_parser.NextInteger());
            parameters.Exponent = TrimLeadingZero(_parser.NextInteger());
            parameters.D        = TrimLeadingZero(_parser.NextInteger());
            parameters.P        = TrimLeadingZero(_parser.NextInteger());
            parameters.Q        = TrimLeadingZero(_parser.NextInteger());
            parameters.DP       = TrimLeadingZero(_parser.NextInteger());
            parameters.DQ       = TrimLeadingZero(_parser.NextInteger());
            parameters.InverseQ = TrimLeadingZero(_parser.NextInteger());

            Debug.Assert(0 == _parser.RemainingBytes());

            return(parameters);
        }
Ejemplo n.º 45
0
 /// <summary>
 /// Converts a <see cref="BigInteger"/> to a hexadecimal string.
 /// </summary>
 /// <param name="bigint">A <see cref="BigInteger"/>.</param>
 /// <returns>
 /// A <see cref="System.String"/> containing a hexadecimal
 /// representation of the supplied <see cref="BigInteger"/>.
 /// </returns>
 public static string ToHexadecimalString(this BigInteger bigint)
 {
     return(bigint.ToString("X"));
 }
Ejemplo n.º 46
0
        public void TestDivideAndRemainder()
        {
            // TODO More basic tests

            var n = new BigInteger(48, Rnd);
            BigInteger[] qr = n.DivideAndRemainder(One);
            Assert.AreEqual(n, qr[0]);
            Assert.AreEqual(Zero, qr[1]);

            for (int rep = 0; rep < 10; ++rep)
            {
                var a = new BigInteger(100 - rep, 0, Rnd);
                var b = new BigInteger(100 + rep, 0, Rnd);
                var c = new BigInteger(10 + rep, 0, Rnd);
                BigInteger d = a.Multiply(b).Add(c);
                BigInteger[] es = d.DivideAndRemainder(a);

                Assert.AreEqual(b, es[0]);
                Assert.AreEqual(c, es[1]);
            }

            // Special tests for power of two since uses different code path internally
            for (int i = 0; i < 100; ++i)
            {
                int shift = Rnd.Next(64);
                BigInteger a = One.ShiftLeft(shift);
                var b = new BigInteger(64 + Rnd.Next(64), Rnd);
                BigInteger bShift = b.ShiftRight(shift);
                BigInteger bMod = b.And(a.Subtract(One));

                string data = "shift=" + shift + ", b=" + b.ToString(16);

                qr = b.DivideAndRemainder(a);
                Assert.AreEqual(bShift, qr[0], data);
                Assert.AreEqual(bMod, qr[1], data);

                qr = b.DivideAndRemainder(a.Negate());
                Assert.AreEqual(bShift.Negate(), qr[0], data);
                Assert.AreEqual(bMod, qr[1], data);

                qr = b.Negate().DivideAndRemainder(a);
                Assert.AreEqual(bShift.Negate(), qr[0], data);
                Assert.AreEqual(bMod.Negate(), qr[1], data);

                qr = b.Negate().DivideAndRemainder(a.Negate());
                Assert.AreEqual(bShift, qr[0], data);
                Assert.AreEqual(bMod.Negate(), qr[1], data);
            }
        }
Ejemplo n.º 47
0
        private static bool VerifyCtorDouble(Double value)
        {
            bool ret = true;
            BigInteger bigInteger;
            Double expectedValue;

            if (value < 0)
            {
                expectedValue = (Double)Math.Ceiling(value);
            }
            else
            {
                expectedValue = (Double)Math.Floor(value);
            }

            bigInteger = new BigInteger(value);

            if (expectedValue != (Double)bigInteger)
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to Double {1}", bigInteger, expectedValue);
                ret = false;
            }

            // Single can only accurately represent integers between -16777216 and 16777216 exclusive.
            // ToString starts to become inaccurate at this point.
            if (expectedValue < 9007199254740992 && -9007199254740992 < expectedValue)
            {
                if (!expectedValue.ToString("G17").Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("Single.ToString() and BigInteger.ToString() not equal");
                    ret = false;
                }
            }

            Assert.True(VerifyBigintegerUsingIdentities(bigInteger, 0 == expectedValue), " Verification Failed");
            return ret;
        }
Ejemplo n.º 48
0
		public RSAParameters ParseRSAPrivateKey()
		{
			var parameters = new RSAParameters();

			// Current value
			byte[] value = null;

			// Checkpoint
			int position = parser.CurrentPosition();

			// Sanity Check
			int length = 0;

			// Ignore Sequence - PrivateKeyInfo
			length = parser.NextSequence();
			if (length != parser.RemainingBytes())
			{
				var sb = new StringBuilder("Incorrect Sequence Size. ");
				sb.AppendFormat("Specified: {0}, Remaining: {1}",
				                length.ToString(CultureInfo.InvariantCulture),
				                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
				throw new BerDecodeException(sb.ToString(), position);
			}

			// Checkpoint
			position = parser.CurrentPosition();
			// Version
			value = parser.NextInteger();
			if (0x00 != value[0])
			{
				var sb = new StringBuilder("Incorrect PrivateKeyInfo Version. ");
				var v = new BigInteger(value);
				sb.AppendFormat("Expected: 0, Specified: {0}", v.ToString(10));
				throw new BerDecodeException(sb.ToString(), position);
			}

			// Checkpoint
			position = parser.CurrentPosition();

			// Ignore Sequence - AlgorithmIdentifier
			length = parser.NextSequence();
			if (length > parser.RemainingBytes())
			{
				var sb = new StringBuilder("Incorrect AlgorithmIdentifier Size. ");
				sb.AppendFormat("Specified: {0}, Remaining: {1}",
				                length.ToString(CultureInfo.InvariantCulture),
				                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
				throw new BerDecodeException(sb.ToString(), position);
			}

			// Checkpoint
			position = parser.CurrentPosition();

			// Grab the OID
			value = parser.NextOID();
			byte[] oid = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01};
			if (!EqualOid(value, oid))
			{
				throw new BerDecodeException("Expected OID 1.2.840.113549.1.1.1", position);
			}

			// Optional Parameters
			if (parser.IsNextNull())
			{
				parser.NextNull();
				// Also OK: value = parser.Next();
			}
			else
			{
				// Gracefully skip the optional data
				value = parser.Next();
			}

			// Checkpoint
			position = parser.CurrentPosition();

			// Ignore OctetString - PrivateKey
			length = parser.NextOctetString();
			if (length > parser.RemainingBytes())
			{
				var sb = new StringBuilder("Incorrect PrivateKey Size. ");
				sb.AppendFormat("Specified: {0}, Remaining: {1}",
				                length.ToString(CultureInfo.InvariantCulture),
				                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
				throw new BerDecodeException(sb.ToString(), position);
			}

			// Checkpoint
			position = parser.CurrentPosition();

			// Ignore Sequence - RSAPrivateKey
			length = parser.NextSequence();
			if (length < parser.RemainingBytes())
			{
				var sb = new StringBuilder("Incorrect RSAPrivateKey Size. ");
				sb.AppendFormat("Specified: {0}, Remaining: {1}",
				                length.ToString(CultureInfo.InvariantCulture),
				                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
				throw new BerDecodeException(sb.ToString(), position);
			}

			// Checkpoint
			position = parser.CurrentPosition();
			// Version
			value = parser.NextInteger();
			if (0x00 != value[0])
			{
				var sb = new StringBuilder("Incorrect RSAPrivateKey Version. ");
				var v = new BigInteger(value);
				sb.AppendFormat("Expected: 0, Specified: {0}", v.ToString(10));
				throw new BerDecodeException(sb.ToString(), position);
			}

			parameters.Modulus = TrimLeadingZero(parser.NextInteger());
			parameters.Exponent = TrimLeadingZero(parser.NextInteger());
			parameters.D = TrimLeadingZero(parser.NextInteger());
			parameters.P = TrimLeadingZero(parser.NextInteger());
			parameters.Q = TrimLeadingZero(parser.NextInteger());
			parameters.DP = TrimLeadingZero(parser.NextInteger());
			parameters.DQ = TrimLeadingZero(parser.NextInteger());
			parameters.InverseQ = TrimLeadingZero(parser.NextInteger());

			Debug.Assert(0 == parser.RemainingBytes());

			return parameters;
		}
Ejemplo n.º 49
0
 public void Keygen(BigInteger p, BigInteger q)
 {
     BigInteger n = p * q;
     BigInteger fi = (p - BigInteger.One) * (q - BigInteger.One);
     var rng = new RNGCryptoServiceProvider();
     byte[] bytes = new byte[fi.ToByteArray().Length - 1];
     BigInteger e;
     do {
         rng.GetBytes(bytes);
         e = new BigInteger(bytes);
     } while (!(e > 1 && e < fi && BigInteger.One == BigInteger.GreatestCommonDivisor(e, fi)));
     BigInteger d = Util.GetModularInverse(e, fi);
     byte [] content = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(d.ToString() + "," + n.ToString())));
     publicFile.Write(content, 0, content.Length);
     content = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(e.ToString() + "," + n.ToString())));
     privateFile.Write(content, 0, content.Length);
 }
Ejemplo n.º 50
0
        public override string P1()
        {
            Parse(Process(Input[0]));

            return(versionSum.ToString());
        }
Ejemplo n.º 51
0
        private static void VerifyComparison(BigInteger x, bool IsXNegative, BigInteger y, bool IsYNegative, int expectedResult)
        {
            bool expectedEquals = 0 == expectedResult;
            bool expectedLessThan = expectedResult < 0;
            bool expectedGreaterThan = expectedResult > 0;

            if (IsXNegative == true)
            {
                x = x * -1;
            }
            if (IsYNegative == true)
            {
                y = y * -1;
            }

            Assert.Equal(expectedEquals, x == y);
            Assert.Equal(expectedEquals, y == x);

            Assert.Equal(!expectedEquals, x != y);
            Assert.Equal(!expectedEquals, y != x);

            Assert.Equal(expectedEquals, x.Equals(y));
            Assert.Equal(expectedEquals, y.Equals(x));

            Assert.Equal(expectedEquals, x.Equals((Object)y));
            Assert.Equal(expectedEquals, y.Equals((Object)x));

            VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
            VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");

            if (expectedEquals)
            {
                Assert.Equal(x.GetHashCode(), y.GetHashCode());
                Assert.Equal(x.ToString(), y.ToString());
            }

            Assert.Equal(x.GetHashCode(), x.GetHashCode());
            Assert.Equal(y.GetHashCode(), y.GetHashCode());

            Assert.Equal(expectedLessThan, x < y);
            Assert.Equal(expectedGreaterThan, y < x);

            Assert.Equal(expectedGreaterThan, x > y);
            Assert.Equal(expectedLessThan, y > x);

            Assert.Equal(expectedLessThan || expectedEquals, x <= y);
            Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);

            Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
            Assert.Equal(expectedLessThan || expectedEquals, y >= x);
        }
Ejemplo n.º 52
0
        static void Main()
        {
            Queue <string> INPUT = new Queue <string>();

            while (!INPUT.Contains("END"))
            {
                INPUT.Enqueue(Console.ReadLine().ToUpper());
            }

            BigInteger resultFirstTen = 1;
            BigInteger resultOthers   = 1;

            int counter = 0; //first 10 elements or less

            while (INPUT.Count > 1)
            {
                if (counter % 2 == 0)
                {
                    foreach (char digit in INPUT.Dequeue().ToString())
                    {
                        resultFirstTen *= (digit - '0');
                    }
                }
                else
                {
                    INPUT.Dequeue();
                }

                counter++;
                if (counter == 10)
                {
                    break;
                }
            }

            while (INPUT.Count > 1)
            {
                if (counter % 2 == 0)
                {
                    foreach (char digit in INPUT.Dequeue().ToString())
                    {
                        resultOthers *= (digit - '0');
                    }
                }
                else
                {
                    INPUT.Dequeue();
                }

                counter++;
            }

            if (counter <= 10)
            {
                Console.WriteLine(resultFirstTen.ToString());
            }
            else
            {
                Console.WriteLine(resultFirstTen.ToString());
                Console.WriteLine(resultOthers.ToString());
            }
        }
Ejemplo n.º 53
0
        //***********************************************************************
        // Tests the correct implementation of the modulo exponential function
        // using RSA encryption and decryption (using pre-computed encryption and
        // decryption keys).
        //***********************************************************************

        public static void RSATest(int rounds)
        {
                Random rand = new Random(1);
	        byte[] val = new byte[64];

	        // private and public key
                BigInteger bi_e = new BigInteger("a932b948feed4fb2b692609bd22164fc9edb59fae7880cc1eaff7b3c9626b7e5b241c27a974833b2622ebe09beb451917663d47232488f23a117fc97720f1e7", 16);
                BigInteger bi_d = new BigInteger("4adf2f7a89da93248509347d2ae506d683dd3a16357e859a980c4f77a4e2f7a01fae289f13a851df6e9db5adaa60bfd2b162bbbe31f7c8f828261a6839311929d2cef4f864dde65e556ce43c89bbbf9f1ac5511315847ce9cc8dc92470a747b8792d6a83b0092d2e5ebaf852c85cacf34278efa99160f2f8aa7ee7214de07b7", 16);
                BigInteger bi_n = new BigInteger("e8e77781f36a7b3188d711c2190b560f205a52391b3479cdb99fa010745cbeba5f2adc08e1de6bf38398a0487c4a73610d94ec36f17f3f46ad75e17bc1adfec99839589f45f95ccc94cb2a5c500b477eb3323d8cfab0c8458c96f0147a45d27e45a4d11d54d77684f65d48f15fafcc1ba208e71e921b9bd9017c16a5231af7f", 16);

                Console.WriteLine("e =\n" + bi_e.ToString(10));
                Console.WriteLine("\nd =\n" + bi_d.ToString(10));
                Console.WriteLine("\nn =\n" + bi_n.ToString(10) + "\n");

	        for(int count = 0; count < rounds; count++)
	        {
	                // generate data of random length
		        int t1 = 0;
		        while(t1 == 0)
			        t1 = (int)(rand.NextDouble() * 65);

		        bool done = false;
		        while(!done)
		        {
			        for(int i = 0; i < 64; i++)
			        {
				        if(i < t1)
					        val[i] = (byte)(rand.NextDouble() * 256);
				        else
					        val[i] = 0;

				        if(val[i] != 0)
					        done = true;
			        }
		        }

		        while(val[0] == 0)
		                val[0] = (byte)(rand.NextDouble() * 256);

                        Console.Write("Round = " + count);

                        // encrypt and decrypt data
		        BigInteger bi_data = new BigInteger(val, t1);
                        BigInteger bi_encrypted = bi_data.modPow(bi_e, bi_n);
                        BigInteger bi_decrypted = bi_encrypted.modPow(bi_d, bi_n);

                        // compare
                        if(bi_decrypted != bi_data)
	        	{
		        	Console.WriteLine("\nError at round " + count);
                                Console.WriteLine(bi_data + "\n");
			        return;
		        }
		        Console.WriteLine(" <PASSED>.");
	        }

        }
Ejemplo n.º 54
0
        private void button3_Click(object sender, EventArgs e)
        {
            BigInteger P = BigInteger.Parse(textBox3.Text), E = 0, Q = BigInteger.Parse(textBox2.Text);
            BigInteger N = 0, Z = 0;
            BigInteger ost = 0, ost_2 = 0, mul = 0, a1 = 0, b1 = 0;

            N             = P * Q;
            textBox7.Text = N.ToString();
            Z             = (P - 1) * (Q - 1);
            textBox8.Text = Z.ToString();

            // нахождение простого числа E
            // bool check = false;
            //   E = Z - 1;
            E = Z;

            //for (BigInteger i = E - 1; i >= 2; i--)
            //{
            //    if (check)
            //    {
            //        E = i + 1;
            //        break;
            //    }
            //    check = true;
            //    for (int j = 2; j <= (i / 2); j++)
            //    {
            //        if (i % j == 0)
            //            check = false;
            //    }
            //}

            bool[]            table;
            List <BigInteger> primearray;

            if (Z < 3000000)
            {
                table      = new bool[(ulong)Z];
                primearray = new List <BigInteger>();
                for (BigInteger i = 0; i < Z; i++)
                {
                    table[(ulong)i] = true;
                }
                for (BigInteger i = 2; i *i < Z; i++)
                {
                    if (table[(ulong)i])
                    {
                        for (var j = 2 * i; j < Z; j += i)
                        {
                            table[(ulong)j] = false;
                        }
                    }
                }
                for (BigInteger i = 1; i < Z; i++)
                {
                    if (table[(ulong)i])
                    {
                        primearray.Add(i);
                    }
                }
            }
            else
            {
                table      = new bool[(ulong)3000000];
                primearray = new List <BigInteger>();
                for (BigInteger i = 0; i < 3000000; i++)
                {
                    table[(ulong)i] = true;
                }
                for (BigInteger i = 2; i *i < 3000000; i++)
                {
                    if (table[(ulong)i])
                    {
                        for (var j = 2 * i; j < 3000000; j += i)
                        {
                            table[(ulong)j] = false;
                        }
                    }
                }
                for (BigInteger i = 1; i < 3000000; i++)
                {
                    if (table[(ulong)i])
                    {
                        primearray.Add(i);
                    }
                }
            }

            //проверка на взаимную простоту
            BigInteger[] U_1 = new BigInteger[3];
            BigInteger[] V_1 = new BigInteger[3];
            BigInteger[] T_1 = new BigInteger[3];
            do
            {
                Random rnd = new Random();

                int value = rnd.Next(0, primearray.Count);
                E = primearray[value];

                U_1[0] = Z;
                U_1[1] = 1;
                U_1[2] = 0;
                V_1[0] = E;
                V_1[1] = 0;
                V_1[2] = 1;
                ost    = Z; ost_2 = 0; mul = 1; a1 = Z; b1 = E;
                BigInteger q_1 = 0;
                while (V_1[0] != 0)
                {
                    q_1    = U_1[0] / V_1[0];
                    T_1[0] = U_1[0] % V_1[0];
                    T_1[1] = U_1[1] - q_1 * V_1[1];
                    T_1[2] = U_1[2] - q_1 * V_1[2];
                    U_1[0] = V_1[0];
                    U_1[1] = V_1[1];
                    U_1[2] = V_1[2];
                    V_1[0] = T_1[0];
                    V_1[1] = T_1[1];
                    V_1[2] = T_1[1];
                }
                textBox1.Text = E.ToString();
            } while (U_1[0] != 1);


            // вычисление D
            BigInteger[] U = new BigInteger[2];
            BigInteger[] V = new BigInteger[2];
            BigInteger[] T = new BigInteger[2];

            U[0] = Z;
            U[1] = 0;
            V[0] = E;
            V[1] = 1;
            //    ost = Z; ost_2 = 0; mul = 1; a1 = Z; b1 = E;
            BigInteger D = 0, q = 0;

            while (V[0] != 0)
            {
                D    = T[1];
                q    = U[0] / V[0];
                T[0] = U[0] % V[0];
                T[1] = U[1] - q * V[1];
                U[0] = V[0];
                U[1] = V[1];
                V[0] = T[0];
                V[1] = T[1];
            }
            if (D < 0)
            {
                D += a1;
            }
            if (D == E)
            {
                D = D + Z;
            }
            textBox4.Text = D.ToString();
        }
Ejemplo n.º 55
0
        public void TestDivide()
        {
            for (int i = -5; i <= 5; ++i)
            {
                try
                {
                    Val(i).Divide(Zero);
                    Assert.Fail("expected ArithmeticException");
                }
                catch (ArithmeticException)
                {
                }
            }

            const int product = 1*2*3*4*5*6*7*8*9;
            const int productPlus = product + 1;

            BigInteger bigProduct = Val(product);
            BigInteger bigProductPlus = Val(productPlus);

            for (int divisor = 1; divisor < 10; ++divisor)
            {
                // Exact division
                BigInteger expected = Val(product/divisor);

                Assert.AreEqual(expected, bigProduct.Divide(Val(divisor)));
                Assert.AreEqual(expected.Negate(), bigProduct.Negate().Divide(Val(divisor)));
                Assert.AreEqual(expected.Negate(), bigProduct.Divide(Val(divisor).Negate()));
                Assert.AreEqual(expected, bigProduct.Negate().Divide(Val(divisor).Negate()));

                expected = Val((product + 1)/divisor);

                Assert.AreEqual(expected, bigProductPlus.Divide(Val(divisor)));
                Assert.AreEqual(expected.Negate(), bigProductPlus.Negate().Divide(Val(divisor)));
                Assert.AreEqual(expected.Negate(), bigProductPlus.Divide(Val(divisor).Negate()));
                Assert.AreEqual(expected, bigProductPlus.Negate().Divide(Val(divisor).Negate()));
            }

            for (int rep = 0; rep < 10; ++rep)
            {
                var a = new BigInteger(100 - rep, 0, Rnd);
                var b = new BigInteger(100 + rep, 0, Rnd);
                var c = new BigInteger(10 + rep, 0, Rnd);
                BigInteger d = a.Multiply(b).Add(c);
                BigInteger e = d.Divide(a);

                Assert.AreEqual(b, e);
            }

            // Special tests for power of two since uses different code path internally
            for (int i = 0; i < 100; ++i)
            {
                int shift = Rnd.Next(64);
                BigInteger a = One.ShiftLeft(shift);
                var b = new BigInteger(64 + Rnd.Next(64), Rnd);
                BigInteger bShift = b.ShiftRight(shift);

                string data = "shift=" + shift + ", b=" + b.ToString(16);

                Assert.AreEqual(bShift, b.Divide(a), data);
                Assert.AreEqual(bShift.Negate(), b.Divide(a.Negate()), data);
                Assert.AreEqual(bShift.Negate(), b.Negate().Divide(a), data);
                Assert.AreEqual(bShift, b.Negate().Divide(a.Negate()), data);
            }

            // Regression
            {
                int shift = 63;
                BigInteger a = One.ShiftLeft(shift);
                var b = new BigInteger(1, "2504b470dc188499".HexToBytes());
                BigInteger bShift = b.ShiftRight(shift);

                string data = "shift=" + shift + ", b=" + b.ToString(16);

                Assert.AreEqual(bShift, b.Divide(a), data);
                Assert.AreEqual(bShift.Negate(), b.Divide(a.Negate()), data);
                //				Assert.AreEqual(bShift.Negate(), b.Negate().Divide(a), data);
                Assert.AreEqual(bShift, b.Negate().Divide(a.Negate()), data);
            }
        }
Ejemplo n.º 56
0
 private static void SetText(TextMeshProUGUI textField, TextMeshProUGUI submitField, bool isEnough, BigInteger cost)
 {
     textField.text   = cost.ToString(CultureInfo.InvariantCulture);
     submitField.text = textField.text;
     SetTextColor(textField, submitField, isEnough);
 }
Ejemplo n.º 57
0
        public void TestToString()
        {
            string s = "12345667890987654321";

            Assert.AreEqual(s, new BigInteger(s).ToString());
            Assert.AreEqual(s, new BigInteger(s, 10).ToString(10));
            Assert.AreEqual(s, new BigInteger(s, 16).ToString(16));

            for (int i = 0; i < 100; ++i)
            {
                var n = new BigInteger(i, Rnd);

                Assert.AreEqual(n, new BigInteger(n.ToString(2), 2));
                Assert.AreEqual(n, new BigInteger(n.ToString(10), 10));
                Assert.AreEqual(n, new BigInteger(n.ToString(16), 16));
            }
        }
Ejemplo n.º 58
0
 public ECKey(BigInteger privateKey, ECPoint publicPoint)
 {
     _privateKey = new ECPrivateKeyParameters(new BigInteger(privateKey.ToString()), Curve);
     Pub         = publicPoint;
 }
Ejemplo n.º 59
0
        /// <inheritdoc/>
        public override object Solve()
        {
            BigInteger result = base.ReadResourceLines().Select(x => BigInteger.Parse(x)).Sum();

            return(new string(result.ToString().Take(10).ToArray()));
        }
Ejemplo n.º 60
0
        public async Task Execute()
        {
            IList <Erc20Token> erc20Tokens = null;

            try
            {
                var tradeableAssets = await _assetsService.AssetGetAllAsync();

                var supportedTokenAssets = tradeableAssets.Where(asset =>
                                                                 asset.Type == Lykke.Service.Assets.Client.Models.AssetType.Erc20Token && asset.IsTradable);
                var assetIds       = supportedTokenAssets.Select(x => x.Id);
                var tradableTokens = await _assetsService.Erc20TokenGetBySpecificationAsync(new Lykke.Service.Assets.Client.Models.Erc20TokenSpecification()
                {
                    Ids = assetIds.ToList(),
                });

                erc20Tokens = tradableTokens?.Items;
            }
            catch (Exception exc)
            {
                await _logger.WriteErrorAsync(nameof(Erc20DepositMonitoringContracts),
                                              nameof(Execute),
                                              "Assets Service unavailable",
                                              exc,
                                              DateTime.UtcNow);

                return;
            }

            if (erc20Tokens != null && !erc20Tokens.Any())
            {
                await _logger.WriteWarningAsync(nameof(Erc20DepositMonitoringContracts),
                                                nameof(Execute),
                                                "",
                                                "No tokens available for trade",
                                                DateTime.UtcNow);

                return;
            }

            await _erc20DepositContractService.ProcessAllAsync(async (item) =>
            {
                try
                {
                    //Check that deposit contract assigned to user
                    if (!string.IsNullOrEmpty(item.UserAddress))
                    {
                        // null - means we ask for all balances on current address
                        var tokenBalances = await _erc20BalanceService.GetBalancesForAddress(item.ContractAddress, new string[0]);

                        if (tokenBalances != null)
                        {
                            foreach (var tokenBalance in tokenBalances)
                            {
                                string tokenAddress     = tokenBalance.Erc20TokenAddress?.ToLower();
                                string formattedAddress =
                                    _userTransferWalletRepository.FormatAddressForErc20(item.ContractAddress, tokenAddress);
                                IUserTransferWallet wallet =
                                    await _userTransferWalletRepository.GetUserContractAsync(item.UserAddress, formattedAddress);
                                if (wallet == null ||
                                    string.IsNullOrEmpty(wallet.LastBalance) ||
                                    wallet.LastBalance == "0")
                                {
                                    BigInteger balance =
                                        await _ercInterfaceService.GetBalanceForExternalTokenAsync(item.ContractAddress, tokenAddress);

                                    if (balance > 0)
                                    {
                                        await _userTransferWalletRepository.ReplaceAsync(new UserTransferWallet()
                                        {
                                            LastBalance             = balance.ToString(),
                                            TransferContractAddress = formattedAddress,
                                            UserAddress             = item.UserAddress,
                                            UpdateDate = DateTime.UtcNow
                                        });

                                        await _erc20DepositTransactionService.PutContractTransferTransaction(new Erc20DepositContractTransaction()
                                        {
                                            Amount          = balance.ToString(),
                                            UserAddress     = item.UserAddress,
                                            TokenAddress    = tokenAddress,
                                            ContractAddress = item.ContractAddress,
                                            CreateDt        = DateTime.UtcNow,
                                        });

                                        await _logger.WriteInfoAsync(nameof(Erc20DepositMonitoringContracts),
                                                                     nameof(Execute), "", $"Balance on transfer address - {item.ContractAddress} is {balance} (Tokens of {tokenBalance.Erc20TokenAddress})" +
                                                                     $" transfer belongs to user {item.UserAddress}", DateTime.UtcNow);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //TODO
                        //Notify That deposit contract does not have a user;
                    }
                }
                catch (Exception e)
                {
                    await _logger.WriteErrorAsync(nameof(Erc20DepositMonitoringContracts),
                                                  nameof(Execute), "", e, DateTime.UtcNow);
                }
            });
        }