Exemple #1
0
        public SRP6Client(
            HashAlgorithm hashAlgorithm, BigInteger n, BigInteger g, BigInteger b,
            BigInteger salt, byte[] account, byte[] passwordMd5Hex)
        {
            this.smallA = BigIntegerHelper.RandUnsignedBigInteger(19);

            this.hashAlgorithm = hashAlgorithm;
            this.n             = n;
            this.g             = g;
            this.b             = b;
            this.salt          = salt;
            this.account       = account;
            this.p             = hashAlgorithm.ComputeHash(new byte[0]
                                                           .Concat(account)
                                                           .Concat(new[] { (byte)':' })
                                                           .Concat(passwordMd5Hex)
                                                           .ToArray());

            this.a = this.CalculateA();              // A = g ^ a % N
            this.x = this.CalculateX();              // X = H(s, P)
            this.u = this.CalculateU();              // U = H(A, B)
            this.s = this.CalculateS();              // S = (B - (k * g.ModExp(x, N))).ModExp(a + (u * x), N)
            this.k = this.CalculateK();
            this.m = this.CalculateM();              // H(H(N) ^ H(g), H(P), s, A, B, K)
        }
Exemple #2
0
        public void Execute()
        {
            ProgressChanged(0, 1);

            if (NumberOfNumbers <= 0)
            {
                GuiLogMessage("The number of numbers must be greater than 0.", NotificationLevel.Error);
                return;
            }

            if (Maximum <= 0)
            {
                GuiLogMessage("The maximum value must be greater than 0.", NotificationLevel.Error);
                return;
            }

            List = new BigInteger[NumberOfNumbers];

            for (int i = 0; i < NumberOfNumbers; i++)
            {
                List[i] = BigIntegerHelper.RandomIntLimit(Maximum);
            }

            OnPropertyChanged("List");

            ProgressChanged(1, 1);
        }
Exemple #3
0
        public void Execute()
        {
            ProgressChanged(0, 1);

            if (AmountOfOptions <= 0)
            {
                GuiLogMessage("AmountOfOptions must be a positive integer.", NotificationLevel.Error);
                return;
            }

            if (settings.Secret)
            {
                // If the prover knows the secret, he can generate any requested number.
                // This is represented by him simply forwarding the requested number 'Input' to the 'Output'.
                Output = Input;
            }
            else
            {
                // If the prover doesn't know he secret, he doesn't know how to produce the requested number.
                // He can only hope his random guess equals the requested number.
                // The more rounds and the more choices there are, it will become more and more unlikely that he always guesses right.
                Output = BigIntegerHelper.RandomIntLimit(AmountOfOptions);
            }

            OnPropertyChanged("Output");

            ProgressChanged(1, 1);
        }
Exemple #4
0
        /*
         * Encryption ( g^m * r^n = (1 + m*n) * r^n mod n^2 )
         * Hint: g^m = (n+1)^m = sum(k=0,m)((m over k)*n^k) = 1+m*n (mod n^2)
         */
        //private BigInteger encrypt(BigInteger m, bool useRandom=true )
        private BigInteger encrypt(BigInteger m)
        {
            if (m >= n)
            {
                GuiLogMessage("Message is bigger than N - this will produce a wrong result!", NotificationLevel.Warning);
            }

            BigInteger r;
            Boolean    useRandom = true;

            if (useRandom)
            {
                while (true)
                {
                    r = BigIntegerHelper.RandomIntLimit(n) % n;
                    if (BigInteger.GreatestCommonDivisor(r, n) == 1)
                    {
                        break;
                    }
                    GuiLogMessage("GCD <> 1, retrying...", NotificationLevel.Warning);
                }
                r = BigInteger.ModPow(r, n, n_square);
                //r = cipherMul(r,n);
            }
            else
            {
                r = 1;
            }

            return((((n * m + 1) % n_square) * r) % n_square);
            //return cipherAdd( (n * m + 1) % n_square, r );
        }
Exemple #5
0
        public void Execute()
        {
            if (currentAttempt == 0)
            {
                RateOfSuccess = Math.Pow(settings._AmountOfOptions, -settings.AmountOfAttempts);
                OnPropertyChanged("RateOfSuccess");
            }

            if (currentAttempt > 0 && OutputRandom != Input)
            {
                Success = false;
            }

            if (currentAttempt >= settings.AmountOfAttempts || !Success)
            {
                OnPropertyChanged("Success");
                ProgressChanged(1, 1);
                return;
            }

            OutputRandom = BigIntegerHelper.RandomIntLimit(settings._AmountOfOptions);
            OnPropertyChanged("AmountOfOptions");
            OnPropertyChanged("OutputRandom");

            currentAttempt++;
            ProgressChanged(currentAttempt, settings.AmountOfAttempts);
        }
Exemple #6
0
        public void Execute()
        {
            if (!checkParameters())
            {
                return;
            }

            ProgressChanged(0, 100);

            switch (m_Settings.Mode)
            {
            case 0:   // create prime with m_Input bits
                OutputString = this.RandomPrimeBits((int)n);
                break;

            case 1:   // create prime with m_Input bits, MSB set
                OutputString = this.RandomPrimeMSBSet((int)n);
                break;

            case 2:   // create prime <= m_Input
                OutputString = BigIntegerHelper.RandomPrimeLimit(n + 1);
                break;

            case 3:   // search biggest prime < m_Input
                OutputString = this.PreviousProbablePrime(n - 1);
                break;

            case 4:   // search smallest prime > m_Input
                OutputString = this.NextProbablePrime(n + 1);
                break;
            }

            ProgressChanged(100, 100);
        }
Exemple #7
0
        private void ExecuteRandomThread()
        {
            FireEventExecuteTest();

            int i = 1;

            for (; i <= m_Rounds; i++)
            {
                BigInteger k = BigIntegerHelper.Max(2, BigIntegerHelper.RandomIntLimit(BigInteger.Parse(m_RandomBaseTo.ToString())));
                if (ExecuteWitness(i, new PrimesBigInteger(k.ToString())))
                {
                    break;
                }
            }

            if (i <= m_Rounds)
            {
                log.Info(string.Format((i == 1) ? rsc.Primetest.mr_witnessfound1 : rsc.Primetest.mr_witnessfound2, i, m_Value));
            }
            else
            {
                log.Info(string.Format((m_Rounds.IntValue == 1) ? rsc.Primetest.mr_witnessnotfound1 : rsc.Primetest.mr_witnessnotfound2, m_Rounds.IntValue, m_Value));
            }

            FireEventCancelTest();
        }
Exemple #8
0
        /// <summary>
        /// 计算S: S = (B - (k * g.ModExp(x, N))).ModExp(a + (u * x), N);
        /// </summary>
        /// <returns></returns>
        private BigInteger CalculateS()
        {
            BigInteger s1 = this.B - BigIntegerHelper.UModPow(this.G, this.X, this.N) * lowerK;
            BigInteger s2 = this.SmallA + (this.U * this.X);
            BigInteger s3 = BigIntegerHelper.UModPow(s1, s2, this.N);

            return(s3);
        }
Exemple #9
0
        //private void GetDigitsAndBitsWithTimeOut(out int digits, out int bits)
        //{
        //    int[] result = null;

        //    var tokenSource = new CancellationTokenSource();
        //    CancellationToken token = tokenSource.Token;
        //    int timeOut = 500; // milliseconds

        //    bool success;
        //    var task = Task.Factory.StartNew(() => result = GetDigitsAndBits(), token);
        //    success = task.Wait(timeOut, token);

        //    if (!success)
        //        throw new OverflowException();

        //    digits = result[0];
        //    bits = result[1];
        //}

        private BigInteger GetNumber()
        {
            //The input from the taskpane is converted to a BigNumber and is sent to the output.
            if (settings.Number == null || settings.Number.Equals(""))
            {
                return(BigInteger.Zero);
            }
            return(BigIntegerHelper.ParseExpression(settings.Number));
        }
Exemple #10
0
        /*
         *  Decryption using chinese remainder theorem
         */
        //public BigInteger decrypt(BigInteger c)
        //{
        //    // L_p(c^p-1)
        //    mp = (((BigInteger.ModPow(c, p_minus1, p_square) - 1) / p) * hp) % p;
        //    // L_q(c^q-1)
        //    mq = (((BigInteger.ModPow(c, q_minus1, q_square) - 1) / q) * hq) % q;
        //    // ( mp*eq + mq*ep ) % n
        //    return (mp * eq + mq * ep) % n;
        //}

        /*
         *  Encryption ( (1 + m*n) * r^n mod n^2 )
         *  Computing r^n using CRT.
         */
        //public BigInteger encrypt(BigInteger m)
        //{
        //    BigInteger r = RandomInt(keyBitLength) % n;

        //    mp = BigInteger.ModPow(r, n, p_square);
        //    mq = BigInteger.ModPow(r, n, q_square);
        //    r = (mp * eq2 + mq * ep2) % n_square;

        //    return (((n * m + 1) % n_square) * r) % n_square;
        //}

        /*
         *  Decryption ( ((c^lambda) % n^2 - 1) div n ) * lambda^(-1) ) % n
         */
        private BigInteger decrypt(BigInteger c)
        {
            if (c >= n_square)
            {
                GuiLogMessage("Cipher is bigger than N^2 - this will produce a wrong result!", NotificationLevel.Warning);
            }

            BigInteger lambdainv = BigIntegerHelper.ModInverse(InputLambda, n);

            return((((BigInteger.ModPow(c, InputLambda, n_square) - 1) / n) * lambdainv) % n);
        }
Exemple #11
0
        /*
         * DGK encryption using CRT for the owner of the private key (p,q,vp,vq).
         */
        BigInteger encryptCRT(BigInteger message)
        {
            if (message >= u)
            {
                GuiLogMessage("Message is bigger than U - this will produce a wrong result!", NotificationLevel.Warning);
            }

            // Use Zv instead of a 2t bit number:
            BigInteger r = BigIntegerHelper.RandomIntLimit(vpvq);

            // Calculate in Zp and Zq instead of Zn:
            BigInteger tmp_cp = BigInteger.ModPow(g, message, p) * BigInteger.ModPow(h, r, p);
            BigInteger tmp_cq = BigInteger.ModPow(g, message, q) * BigInteger.ModPow(h, r, q);

            return((tmp_cp * qq_inv + tmp_cq * pp_inv) % n);
        }
Exemple #12
0
        protected override void DoExecute()
        {
            FireOnStart();

            try
            {
                BigInteger second = BigInteger.Parse(m_SecondParameter.ToString());
                BigInteger from = BigInteger.Parse(m_From.ToString());
                BigInteger to = BigInteger.Parse(m_To.ToString());
                BigInteger a, b;

                for (BigInteger x = from; x <= to; x++)
                {
                    string msg;

                    try
                    {
                        BigInteger gcd = BigIntegerHelper.ExtEuclid(x, second, out a, out b);
                        string     sa  = a.ToString(); if (a < 0)
                        {
                            sa = "(" + sa + ")";
                        }
                        string sb = b.ToString(); if (b < 0)
                        {
                            sb = "(" + sb + ")";
                        }
                        if (b < 0)
                        {
                            b = -b;
                        }
                        msg = String.Format("{0}*{1} + {2}*{3} = {4}", sa, x, sb, second, gcd);
                    }
                    catch (Exception ex)
                    {
                        msg = "-";
                    }

                    FireOnMessage(this, new PrimesBigInteger(x.ToString()), msg);
                }
            }
            catch (Exception ex)
            {
            }

            FireOnStop();
        }
Exemple #13
0
        private void miIntegerManyFactors_Click(object sender, RoutedEventArgs e)
        {
            PrimesBigInteger value = null;

            try
            {
                if (sender == miPrime)
                {
                    value = new PrimesBigInteger(MaxValue.RandomPrimeLimit());
                }
                else if (sender == miBigInteger)
                {
                    value = new PrimesBigInteger(MaxValue.RandomIntLimit());
                }
                else if (sender == miIntegerManyFactors)
                {
                    int        bits = Math.Max(MaxValue.BitCount() / 16, 8);
                    BigInteger p    = MaxValue.Sqrt().RandomIntLimit();
                    for (int i = 0; i < 16; i++)
                    {
                        BigInteger pp = p * BigIntegerHelper.RandomPrimeBits(bits);
                        if (pp < MaxValue)
                        {
                            p = pp;
                        }
                    }
                    value = new PrimesBigInteger(p);
                }
                else if (sender == miTowBigFactors)
                {
                    BigInteger a = MaxValue.Sqrt().RandomPrimeLimit();
                    BigInteger b = (MaxValue / a).RandomPrimeLimit();
                    value = new PrimesBigInteger(a * b);
                }
            }
            catch
            {
                return;
            }

            if (value != null)
            {
                FireOnRandomNumberGenerated(value);
            }
        }
Exemple #14
0
        private BigInteger RandomPrimeMSBSet(int bits)
        {
            if (bits <= 1)
            {
                throw new ArithmeticException("No primes with this bitcount");
            }

            BigInteger limit = ((BigInteger)1) << bits;

            while (true)
            {
                var p = this.NextProbablePrime(BigIntegerHelper.SetBit(BigIntegerHelper.RandomIntBits(bits - 1), bits - 1));
                if (p < limit)
                {
                    return(p);
                }
            }
        }
Exemple #15
0
        public void Execute()
        {
            ProgressChanged(0, 1);

            if (b < 0 || b >= x.Length)
            {
                GuiLogMessage("Requested message index " + b + " is illegal, it must be bigger than 0 and smaller than " + x.Length, NotificationLevel.Error);
                return;
            }

            K = BigIntegerHelper.RandomIntLimit(N);
            v = (x[b] + BigInteger.ModPow(K, e, N)) % N;

            OnPropertyChanged("K");
            OnPropertyChanged("v");

            ProgressChanged(1, 1);
        }
Exemple #16
0
        // not used, public/private keys are input variables for this plugin
        private void generateKeys()
        {
            BigInteger twoPowModulusBits, n_plus1;

            p = BigIntegerHelper.RandomPrimeBits(keyBitLength - (keyBitLength / 2));
            q = BigIntegerHelper.RandomPrimeBits(keyBitLength / 2);
            n = p * q;

            // Just complete PK: n^2
            n_plus1  = n + 1;
            n_square = n * n;

            // compute lambda
            p_minus1 = p - 1;
            q_minus1 = q - 1;
            lambda   = BigIntegerHelper.LCM(p_minus1, q_minus1);

            // Compute n^(-1)
            twoPowModulusBits = 1 << keyBitLength;
            n_inv             = BigIntegerHelper.ModInverse(n, twoPowModulusBits);

            // Store the L(lambda)-part for decryption
            decDiv = BigInteger.ModPow(n + 1, lambda, n_square);
            decDiv = BigIntegerHelper.ModInverse(L(decDiv), n);

            p_square = p * p;
            q_square = q * q;

            hp = BigIntegerHelper.ModInverse((BigInteger.ModPow(n + 1, p_minus1, p_square) - 1) / p, p);
            hq = BigIntegerHelper.ModInverse((BigInteger.ModPow(n + 1, q_minus1, q_square) - 1) / q, q);

            // for CRT
            BigInteger s, t;

            BigIntegerHelper.ExtEuclid(p, q, out s, out t);
            ep = s * p;
            eq = t * q;

            // CRT Encryption:
            BigIntegerHelper.ExtEuclid(p_square, q_square, out s, out t);
            ep2 = s * p_square;
            eq2 = t * q_square;
        }
Exemple #17
0
        /*
         *      Standard DGK encryption.
         */
        BigInteger encrypt(BigInteger message)
        {
            if (secretKeyValid)
            {
                return(encryptCRT(message));
            }

            if (message >= u)
            {
                GuiLogMessage("Message is bigger than U - this will produce a wrong result!", NotificationLevel.Warning);
            }

            //BigInteger r = BigIntegerHelper.RandomIntBits(DGK_BLINDING_T);
            // Choose random number with 2t bits. But t is not part of the public key.
            // Workaround: use n as upper bound. n has k bits and k>t, so n^2 has 2k bits.
            BigInteger r = BigIntegerHelper.RandomIntLimit(n_square);

            return(cipherAdd(cipherMul(g, message), cipherMul(h, r)));
            //return ( BigInteger.ModPow(g,message,n) * BigInteger.ModPow(h,r,n) ) % n;
        }
        /// <summary>
        /// Implementation of solutionfinding for chinese remainder theorem.
        /// i.e. finding an x that fullfills
        /// x = a1 (mod m1)
        /// x = a2 (mod m2)
        /// ...
        /// </summary>
        /// <param name="congruences">The congruences (a_i, m_i)</param>
        /// <returns>the value that fits into all congruences</returns>
        private BigInteger CRT(List <KeyValuePair <BigInteger, BigInteger> > congruences)
        {
            BigInteger x = 0;

            for (int i = 0; i < congruences.Count; i++)
            {
                BigInteger k = 1;
                for (int c = 0; c < congruences.Count; c++)
                {
                    if (c != i)
                    {
                        k *= congruences[c].Value;
                    }
                }
                BigInteger r = BigIntegerHelper.ModInverse(k, congruences[i].Value);

                x += congruences[i].Key * r * k;
            }

            return(x);
        }
Exemple #19
0
        public void Execute()
        {
            BigInteger m, k;

            ProgressChanged(0, 1);

            if (x == null || Messages == null)
            {
                GuiLogMessage("Illegal array 'x' or 'messages'.", NotificationLevel.Error);
                return;
            }

            if (x.Length != Messages.Length)
            {
                GuiLogMessage("Arrays 'x' and 'messages' must have the same number of entries.", NotificationLevel.Error);
                return;
            }

            EncryptedMessages = new BigInteger[x.Length];

            for (int i = 0; i < Messages.Length; i++)
            {
                try // can be read as parseable expression?
                {
                    m = BigIntegerHelper.ParseExpression(Messages[i]);
                }
                catch (Exception ex)
                {
                    GuiLogMessage("Error while converting '" + Messages[i] + "' to a number.", NotificationLevel.Error);
                    return;
                }

                k = BigInteger.ModPow(((v - x[i]) % N + N) % N, d, N);
                EncryptedMessages[i] = (m + k) % N;

                ProgressChanged(i + 1, Messages.Length);
            }

            OnPropertyChanged("EncryptedMessages");
        }
Exemple #20
0
        public void PrimesGeneratorTestMethod()
        {
            var pluginInstance = TestHelpers.GetPluginInstance("PrimesGenerator");
            var scenario       = new PluginTestScenario(pluginInstance, new[] { "n", ".Mode" }, new[] { "OutputString" });

            foreach (TestVector vector in testvectors)
            {
                if (vector.mode <= 2)
                {
                    for (int i = 0; i < vector.count; i++)
                    {
                        object[] output = scenario.GetOutputs(new object[] { vector.input, vector.mode });
                        Assert.IsTrue(BigIntegerHelper.IsProbablePrime((BigInteger)output[0]), (BigInteger)output[0] + " is not a prime number in test #" + vector.n + ".");
                    }
                }
                else
                {
                    object[] output = scenario.GetOutputs(new object[] { vector.input, vector.mode });
                    Assert.AreEqual(vector.output, output[0], "Unexpected value in test #" + vector.n + ".");
                }
            }
        }
Exemple #21
0
 public void MakeBinaryOperandsCompatible(Type leftType, Type rightType, ref Expression leftExpression, ref Expression rightExpression)
 {
     if (CanBeConverted(leftType, rightType))
     {
         leftExpression = VelocityExpressions.ConvertIfNeeded(leftExpression, rightType);
     }
     else if (CanBeConverted(rightType, leftType))
     {
         rightExpression = VelocityExpressions.ConvertIfNeeded(rightExpression, leftType);
     }
     else if (leftType == typeof(string) && (rightType == typeof(char) || rightType.IsEnum))
     {
         rightExpression = Expression.Call(rightExpression, MethodHelpers.ToStringMethodInfo);
     }
     else if (rightType == typeof(string) && (leftType == typeof(char) || leftType.IsEnum))
     {
         leftExpression = Expression.Call(leftExpression, MethodHelpers.ToStringMethodInfo);
     }
     else if (leftType != rightType && TypeHelper.IsInteger(leftType) && TypeHelper.IsInteger(rightType))
     {
         leftExpression  = BigIntegerHelper.ConvertToBigInteger(leftExpression);
         rightExpression = BigIntegerHelper.ConvertToBigInteger(rightExpression);
     }
 }
Exemple #22
0
 /*
  *  Compute: res = E(-m)
  *  Computes the multiplicative inverse of some ciphertext c = E(m).
  */
 private BigInteger cipherNeg(BigInteger c)
 {
     return(BigIntegerHelper.ModInverse(c, n_square));
 }
Exemple #23
0
        public void Execute()
        {
            ProgressChanged(0, 1);

            if (n < 2 * 3)
            {
                GuiLogMessage("Illegal Input N - DGK can not work", NotificationLevel.Error);
                return;
            }

            n_square = n * n;

            // check whether the sectret key is provided
            secretKeyValid = false;
            if (p != null && p != 0)
            {
                q = n / p;

                if (vp != null && vp > 0 && vq != null && vq > 0)
                {
                    vpvq = vp * vq; secretKeyValid = true;
                }

                // for faster de-/encryption:
                pp_inv = BigIntegerHelper.ModInverse(p, q) * p;
                qq_inv = BigIntegerHelper.ModInverse(q, p) * q;
            }

            if (settings.Action == 0)   // Encryption
            {
                if (InputM is BigInteger)
                {
                    OutputC1 = encrypt((BigInteger)InputM);
                }
                else if (InputM is byte[])
                {
                    OutputC2 = BlockConvert((byte[])InputM, (u < 256)?256:u, n, encrypt, true);
                }
            }
            else if (settings.Action == 1)  // Decryption
            {
                if (!secretKeyValid)
                {
                    GuiLogMessage("Can't decrypt because secret key is not available", NotificationLevel.Error);
                    return;
                }

                if (!decrypttableIsValid)
                {
                    decrypttable = new BigInteger[(int)u];

                    BigInteger gv = BigInteger.ModPow(g, vp, p);
                    //for (int i = 0; i < (int)u; i++) decrypttable[i] = BigInteger.ModPow(gv,i,p);
                    decrypttableIsValid = true;

                    dechash = new Hashtable();
                    for (int i = 0; i < (int)u; i++)
                    {
                        dechash[BigInteger.ModPow(gv, i, p) % (((BigInteger)1) << 48)] = i;
                    }
                }

                if (InputM is BigInteger)
                {
                    OutputC1 = decrypt((BigInteger)InputM);
                }
                else if (InputM is byte[])
                {
                    OutputC2 = removeZeros(BlockConvert((byte[])InputM, n, (u < 256)?256:u, decrypt, false));
                }
            }

            // Make sure the progress bar is at maximum when your Execute() finished successfully.
            ProgressChanged(1, 1);
        }
Exemple #24
0
        /// <summary>
        /// Main method
        /// </summary>
        public void Execute()
        {
            BigInteger result = 0;

            //First checks if both inputs are set
            if (input1 != null && input2 != null)
            {
                ProgressChanged(0.5, 1.0);

                try
                {
                    //As the user changes the operation different outputs are calculated.
                    switch (settings.Operat)
                    {
                    // x + y
                    case 0:
                        result = Input1 + Input2;
                        break;

                    // x - y
                    case 1:
                        result = Input1 - Input2;
                        break;

                    //x * y
                    case 2:
                        result = Input1 * Input2;
                        break;

                    // x / y
                    case 3:
                        result = Input1 / Input2;
                        break;

                    // x ^ y
                    case 4:
                        if (Mod != 0)
                        {
                            if (Input2 >= 0)
                            {
                                result = BigInteger.ModPow(Input1, Input2, Mod);
                            }
                            else
                            {
                                result = BigInteger.ModPow(BigIntegerHelper.ModInverse(Input1, Mod), -Input2, Mod);
                            }
                        }
                        else
                        {
                            result = BigIntegerHelper.Pow(Input1, Input2);
                        }
                        break;

                    // gcd(x,y)
                    case 5:
                        result = Input1.GCD(Input2);
                        break;

                    // lcm(x,y)
                    case 6:
                        result = Input1.LCM(Input2);
                        break;

                    // sqrt(x,y)
                    case 7:
                        result = Input1.Sqrt();
                        break;

                    // modinv(x,y)
                    case 8:
                        if (Input2 != 0)
                        {
                            result = BigIntegerHelper.ModInverse(Input1, Input2);
                        }
                        else
                        {
                            result = 1 / Input1;
                        }
                        break;

                    // phi(x)
                    case 9:
                        result = Input1.Phi();
                        break;
                    }

                    Output = (Mod == 0) ? result : (((result % Mod) + Mod) % Mod);
                }
                catch (Exception e)
                {
                    GuiLogMessage("Big Number fail: " + e.Message, NotificationLevel.Error);
                    return;
                }

                ProgressChanged(1.0, 1.0);
            }
        }
Exemple #25
0
        /// <summary>
        /// Called by the environment to start generating of public/private keys
        /// </summary>
        public void Execute()
        {
            BigInteger p = 1, q = 1;

            ProgressChanged(0, 1);

            switch (settings.Source)
            {
            // manually enter primes
            case 0:
                try
                {
                    p = BigIntegerHelper.ParseExpression(settings.P);
                    q = BigIntegerHelper.ParseExpression(settings.Q);

                    if (!BigIntegerHelper.IsProbablePrime(p))
                    {
                        GuiLogMessage(p.ToString() + " is not prime!", NotificationLevel.Error);
                        return;
                    }
                    if (!BigIntegerHelper.IsProbablePrime(q))
                    {
                        GuiLogMessage(q.ToString() + " is not prime!", NotificationLevel.Error);
                        return;
                    }
                    if (p == q)
                    {
                        GuiLogMessage("The primes P and Q can not be equal!", NotificationLevel.Error);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    GuiLogMessage("Invalid Big Number input: " + ex.Message, NotificationLevel.Error);
                    return;
                }


                break;

            //randomly generated primes
            case 1:
                try
                {
                    int keyBitLength = Convert.ToInt32(settings.KeyBitLength);
                    if (keyBitLength < 4)
                    {
                        GuiLogMessage("The keylength must be greater than 3.", NotificationLevel.Error);
                        return;
                    }

                    int i, maxtries = 10;
                    for (i = 0; i < maxtries; i++)
                    {
                        p = BigIntegerHelper.RandomPrimeMSBSet(keyBitLength - (keyBitLength / 2));
                        q = BigIntegerHelper.RandomPrimeMSBSet(keyBitLength / 2);
                        //GuiLogMessage("p = " + p.ToString(), NotificationLevel.Info);
                        //GuiLogMessage("q = " + q.ToString(), NotificationLevel.Info);
                        if (p != q)
                        {
                            break;
                        }
                    }
                    if (i == maxtries)
                    {
                        throw new Exception("Could not create two differing primes");
                    }
                }
                catch (Exception ex)
                {
                    GuiLogMessage(ex.Message, NotificationLevel.Error);
                    return;
                }
                break;

            default:
                throw new Exception("Illegal Key Generation Mode");
            }

            N      = p * q;
            G      = N + 1;
            Lambda = (p - 1) * (q - 1);

            ProgressChanged(1, 1);
        }
Exemple #26
0
        public BigInteger[] Solve(List <BigInteger[]> matrix, BigInteger mod)
        {
            this.matrix   = matrix;
            this.mod      = mod;
            size          = matrix.Count;
            this.rowSwaps = new int[matrix.Count];
            for (int i = 0; i < matrix.Count; i++)
            {
                rowSwaps[i] = i;
            }

            //make lower triangular matrix:
            for (int x = 0; x < size; x++)
            {
                if ((matrix[x][x] % mod) == 0)
                {
                    int y = x + 1;
                    while (y < size && (matrix[y][x] % mod) == 0)
                    {
                        y++;
                    }
                    if (y == size)
                    {
                        int[] rowsToDelete = new int[size - (x + 1)];
                        for (int i = x + 1; i < size; i++)
                        {
                            rowsToDelete[i - (x + 1)] = rowSwaps[i];
                        }
                        throw new LinearDependentException(rowsToDelete);
                    }
                    SwapRows(x, y);
                }

                BigInteger matrixXXinverse;

                try
                {
                    matrixXXinverse = BigIntegerHelper.ModInverse(matrix[x][x], mod);
                }
                catch (ArithmeticException)
                {
                    throw new NotInvertibleException(matrix[x][x] % mod);
                }

                for (int y = x + 1; y < size; y++)
                {
                    if ((matrix[y][x] % mod) != 0)
                    {
                        SubAndMultiplyWithConstantRows(x, y, (matrixXXinverse * matrix[y][x]) % mod);
                    }
                    Debug.Assert((matrix[y][x] % mod) == 0);
                }
            }

            //make upper triangular matrix:
            for (int x = (size - 1); x >= 0; x--)
            {
                BigInteger matrixXXinverse;

                try
                {
                    matrixXXinverse = BigIntegerHelper.ModInverse(matrix[x][x], mod);
                }
                catch (ArithmeticException)
                {
                    throw new NotInvertibleException(matrix[x][x] % mod);
                }

                for (int y = x - 1; y >= 0; y--)
                {
                    if ((matrix[y][x] % mod) != 0)
                    {
                        SubAndMultiplyWithConstantRows(x, y, (matrixXXinverse * matrix[y][x]) % mod);
                    }
                    Debug.Assert((matrix[y][x] % mod) == 0);
                }
            }

            //get solution:
            BigInteger[] sol = new BigInteger[size];
            for (int x = 0; x < size; x++)
            {
                BigInteger matrixXXinverse = BigIntegerHelper.ModInverse(matrix[x][x], mod);
                sol[x] = (matrixXXinverse * matrix[x][size]) % mod;
                while (sol[x] < 0)
                {
                    sol[x] += mod;
                }
            }
            return(sol);
        }
Exemple #27
0
        public bool ConvertToOutput(object input)
        {
            if (input == null)
            {
                return(false);
            }

            #region ConvertFromTypes

            #region ConvertFromICryptoolStream
            if (input is ICryptoolStream)
            {
                switch (this.settings.Converter)
                {
                case OutputTypes.CryptoolStreamType:
                {
                    Output = (ICryptoolStream)input;
                    break;
                }

                case OutputTypes.StringType:
                {
                    byte[] buffer = ICryptoolStreamToByteArray((ICryptoolStream)input);
                    Output = GetStringForEncoding(buffer, settings.InputEncoding);
                    break;
                }

                case OutputTypes.ByteArrayType:
                {
                    Output = ICryptoolStreamToByteArray((ICryptoolStream)input);
                    break;
                }

                case OutputTypes.BigIntegerType:
                {
                    byte[] buffer = ICryptoolStreamToByteArray((ICryptoolStream)input);
                    Output = ByteArrayToBigInteger(buffer, settings.Endianness);
                    break;
                }

                default:
                    GuiLogMessage("Conversion from " + input.GetType() + " to " + GetType(settings.Converter) + " is not implemented", NotificationLevel.Error);
                    return(false);
                }

                return(true);
            }
            #endregion
            #region ConvertFromIntArray
            else if (input is int[])
            {
                GuiLogMessage("Conversion from int[] to the chosen type is not implemented", NotificationLevel.Error);
                return(false);
            }
            #endregion
            #region ConvertFromByteArray
            else if (input is byte[])
            {
                switch (this.settings.Converter)
                {
                case OutputTypes.BigIntegerType:     // byte[] to BigInteger
                {
                    byte[] temp = (byte[])input;
                    Output = ByteArrayToBigInteger(temp, settings.Endianness);
                    return(true);
                }

                case OutputTypes.IntType:     // byte[] to int
                {
                    try
                    {
                        byte[] temp = new byte[4];
                        Array.Copy((byte[])input, temp, 4);
                        if (settings.Endianness)
                        {
                            Array.Reverse(temp);
                        }
                        Output = BitConverter.ToInt32(temp, 0);
                        return(true);
                    }
                    catch (Exception e)
                    {
                        GuiLogMessage("Could not convert byte[] to integer: " + e.Message, NotificationLevel.Error);
                        return(false);
                    }
                }

                case OutputTypes.ShortType:     // byte[] to short
                {
                    try
                    {
                        byte[] temp = new byte[2];
                        Array.Copy((byte[])input, temp, 2);
                        if (settings.Endianness)
                        {
                            Array.Reverse(temp);
                        }
                        Output = BitConverter.ToInt16(temp, 0);
                        return(true);
                    }
                    catch (Exception e)
                    {
                        GuiLogMessage("Could not convert byte[] to short: " + e.Message, NotificationLevel.Error);
                        return(false);
                    }
                }

                case OutputTypes.ByteType:     // byte[] to byte
                {
                    try
                    {
                        Output = ((byte[])input)[0];
                        return(true);
                    }
                    catch (Exception e)
                    {
                        GuiLogMessage("Could not convert byte[] to byte: " + e.Message, NotificationLevel.Error);
                        return(false);
                    }
                }

                case OutputTypes.StringType:     // byte[] to String
                {
                    Output = GetStringForEncoding((byte[])input, settings.InputEncoding);
                    return(true);
                }

                case OutputTypes.ByteArrayType:     // byte[] to byte[]
                {
                    Output = (byte[])input;
                    return(true);
                }
                }
            }
            #endregion
            #region ConvertFromBigInteger
            else if (input is BigInteger)
            {
                if (this.settings.Converter == OutputTypes.ByteArrayType)
                {
                    Output = ((BigInteger)input).ToByteArray();
                    return(true);
                }
                try
                {
                    Output = ((BigInteger)input).ToString(this.settings.Format);
                    return(true);
                }
                catch (FormatException ex)
                {
                    ShowFormatErrorMessage(ex);
                }
            }
            #endregion
            #region  ConvertFromInt
            else if (input is int)
            {
                if (this.settings.Converter == OutputTypes.ByteArrayType)
                {
                    Output = BitConverter.GetBytes((int)input);
                    return(true);
                }
                try
                {
                    Output = ((int)input).ToString(this.settings.Format);
                    return(true);
                }
                catch (FormatException ex)
                {
                    ShowFormatErrorMessage(ex);
                }
            }
            #endregion
            #region ConvertFromShort
            else if (input is short)
            {
                if (this.settings.Converter == OutputTypes.ByteArrayType)
                {
                    Output = BitConverter.GetBytes((short)input);
                    return(true);
                }
                if (this.settings.Converter == OutputTypes.StringType && !string.IsNullOrEmpty(this.settings.Format))
                {
                    try
                    {
                        Output = ((short)input).ToString(this.settings.Format);
                        return(true);
                    }
                    catch (FormatException ex)
                    {
                        ShowFormatErrorMessage(ex);
                    }
                }
            }
            #endregion
            #region ConvertFromByte
            else if (input is byte)
            {
                if (this.settings.Converter == OutputTypes.ByteArrayType)
                {
                    Output = new byte[] { (byte)input };
                    return(true);
                }
                if (this.settings.Converter == OutputTypes.StringType && !string.IsNullOrEmpty(this.settings.Format))
                {
                    try
                    {
                        Output = ((byte)input).ToString(this.settings.Format);
                        return(true);
                    }
                    catch (FormatException ex)
                    {
                        ShowFormatErrorMessage(ex);
                    }
                }
            }
            #endregion
            #region ConvertFromDouble
            else if (input is Double)
            {
                if (this.settings.Converter == OutputTypes.ByteArrayType)
                {
                    Output = BitConverter.GetBytes((Double)input);
                    return(true);
                }
                if (this.settings.Converter == OutputTypes.StringType && !string.IsNullOrEmpty(this.settings.Format))
                {
                    try
                    {
                        Output = ((double)input).ToString(this.settings.Format);
                        return(true);
                    }
                    catch (FormatException ex)
                    {
                        ShowFormatErrorMessage(ex);
                    }
                }
            }
            #endregion
            #region ConvertFromBool
            else if (input is bool)
            {
                switch (this.settings.Converter)
                {
                case OutputTypes.BooleanType:
                    Output = input;
                    return(true);

                case OutputTypes.StringType:
                    Output = input.ToString();
                    return(true);

                case OutputTypes.IntType:
                    Output = (int)((bool)input ? 1 : 0);
                    return(true);

                case OutputTypes.ShortType:
                    Output = (short)((bool)input ? 1 : 0);
                    return(true);

                case OutputTypes.ByteType:
                    Output = (byte)((bool)input ? 1 : 0);
                    return(true);

                case OutputTypes.ByteArrayType:
                    Output = new byte[] { (byte)(((bool)input) ? 1 : 0) };
                    return(true);

                case OutputTypes.BigIntegerType:
                    Output = (BigInteger)((bool)input ? 1 : 0);
                    return(true);

                case OutputTypes.DoubleType:
                    Output = (Double)((bool)input ? 1 : 0);
                    return(true);

                case OutputTypes.CryptoolStreamType:
                    Output = new byte[] { (byte)(((bool)input) ? 1 : 0) };
                    return(true);

                default:
                    GuiLogMessage("Could not convert from bool to chosen type: ", NotificationLevel.Error);
                    return(false);
                }
            }
            #endregion

            #endregion

            if (input is string[])
            {
                string[] inputarray = (string[])input;
                if (this.settings.Converter == OutputTypes.BooleanType)
                {
                    bool[] result = new bool[inputarray.Length];
                    for (int i = 0; i < inputarray.Length; i++)
                    {
                        result[i] = inputarray[i] == "1";
                    }
                    Output = result;
                    return(true);
                }
                if (this.settings.Converter == OutputTypes.BigIntegerType)
                {
                    BigInteger[] result = new BigInteger[inputarray.Length];
                    try // can be read as parseable expression?
                    {
                        for (int i = 0; i < inputarray.Length; i++)
                        {
                            result[i] = BigIntegerHelper.ParseExpression(inputarray[i]);
                        }
                    }
                    catch (Exception)
                    {
                        GuiLogMessage("Could not convert input to BigInteger", NotificationLevel.Error);
                        return(false);
                    }
                    Output = result;
                    return(true);
                }
            }

            // the string representation is used for all upcoming operations
            string inpString = Convert.ToString(input);

            #region ConvertFromString

            switch (this.settings.Converter) // convert to what?
            {
                #region ConvertToString
            case OutputTypes.StringType:
            {
                if (settings.Numeric)
                {
                    try         // can be read as parseable expression?
                    {
                        Output = BigIntegerHelper.ParseExpression(inpString).ToString();
                        return(true);
                    }
                    catch (Exception) { }
                }

                Output = inpString;
                return(true);
            }

                #endregion
                #region ConvertToInt
            case OutputTypes.IntType:
            {
                try         // can be read as int from decimal string?
                {
                    Output = Convert.ToInt32(inpString);
                    return(true);
                }
                catch (Exception e)
                {
                }

                try         // can be read as int from hexadecimal string?
                {
                    Output = Convert.ToInt32(inpString, 16);
                    return(true);
                }
                catch (Exception e)
                {
                    GuiLogMessage("Could not convert input to integer: " + e.Message, NotificationLevel.Error);
                    return(false);
                }
            }

                #endregion
                #region ConvertToShort
            case OutputTypes.ShortType:
            {
                try         // can be read as short from decimal string?
                {
                    Output = Convert.ToInt16(inpString);
                    return(true);
                }
                catch (Exception e)
                {
                }

                try         // can be read as short from hexadecimal string?
                {
                    Output = Convert.ToInt16(inpString, 16);
                    return(true);
                }
                catch (Exception e)
                {
                    GuiLogMessage("Could not convert input to short: " + e.Message, NotificationLevel.Error);
                    return(false);
                }
            }

                #endregion
                #region ConvertToByte
            case OutputTypes.ByteType:
            {
                try         // can be read as byte from decimal string?
                {
                    Output = Convert.ToByte(inpString);
                    return(true);
                }
                catch (Exception e)
                {
                }

                try         // can be read as byte hexadecimal string?
                {
                    Output = Convert.ToByte(inpString, 16);
                    return(true);
                }
                catch (Exception e)
                {
                    GuiLogMessage("Could not convert input to byte: " + e.Message, NotificationLevel.Error);
                    return(false);
                }
            }

                #endregion
                #region ConvertToDouble
            case OutputTypes.DoubleType:
            {
                try         // can be read as double?
                {
                    Output = StringToDouble(inpString, this.settings.FormatAmer ? "en" : "de");
                    GuiLogMessage("Converting String to double is not safe. Digits may have been cut off.", NotificationLevel.Warning);
                    return(true);
                }
                catch (Exception e)
                {
                    GuiLogMessage("Could not convert input to double: " + e.Message, NotificationLevel.Error);
                    return(false);
                }
            }

                #endregion
                #region ConvertToBigInteger
            case OutputTypes.BigIntegerType:
            {
                try         // can be read as parseable expression?
                {
                    Output = BigIntegerHelper.ParseExpression(inpString);
                    return(true);
                }
                catch (Exception) { }

                // remove all non-hex characters and parse as hexstring
                byte[] result = TryMatchHex(inpString);
                if (result != null)
                {
                    Output = ByteArrayToBigInteger(result, settings.Endianness);
                    return(true);
                }

                GuiLogMessage("Could not convert input to BigInteger", NotificationLevel.Error);
                return(false);
            }

                #endregion
                #region ConvertToIntArray
                #endregion
                #region ConvertToByteArray
            case OutputTypes.ByteArrayType:
            {
                if (settings.Numeric) // apply user setting concerning numeric interpretation of input (else input is read as string)
                {
                    try               // can be read as parseable expression?
                    {
                        Output = BigIntegerHelper.ParseExpression(inpString).ToByteArray();
                        return(true);
                    }
                    catch (Exception) { }

                    try         // can be read as Hexstring?
                    {
                        byte[] result = TryMatchHex(inpString);
                        if (result != null)
                        {
                            Output = result;
                            return(true);
                        }
                    }
                    catch (Exception) { }

                    try         // can be read as double
                    {
                        double tempDouble = StringToDouble(inpString, this.settings.FormatAmer ? "en" : "de");
                        byte[] temp       = BitConverter.GetBytes(tempDouble);
                        Output = temp;

                        double test = BitConverter.ToDouble(temp, 0);
                        GuiLogMessage("Converting String to double is not safe. Digits may have been cut off: " + test.ToString(), NotificationLevel.Warning);

                        return(true);
                    }
                    catch (Exception) { }
                }

                // numeric interpretation NOT selected:
                Output = GetBytesForEncoding(inpString, settings.OutputEncoding);
                return(true);
            }

                #endregion
                #region ConvertToCryptoolStream
            case OutputTypes.CryptoolStreamType:
            {
                if (input is byte[] || input is byte || input is BigInteger || input is String)
                {
                    OnPropertyChanged("Output");
                    return(true);
                }
                else
                {
                    GuiLogMessage("Conversion from " + input.GetType().Name + " to CryptoolStream is not yet implemented", NotificationLevel.Error);
                    return(false);
                }
            }

                #endregion
                #region ConvertToAnythingLeft
            default:
                return(false);

                #endregion
            }

            #endregion
        }
Exemple #28
0
 /// <summary>
 /// 计算A: A = g ^ a % N
 /// </summary>
 /// <returns></returns>
 private BigInteger CalculateA()
 {
     return(BigIntegerHelper.UModPow(this.G, this.SmallA, this.N));
 }
Exemple #29
0
        private void DoCalculateGoldbach(object o)
        {
            if (o == null || o.GetType() != typeof(PrimesBigInteger))
            {
                return;
            }

            PrimesBigInteger value = o as PrimesBigInteger;

            if (value.Mod(PrimesBigInteger.Two).Equals(PrimesBigInteger.One)) // value is odd
            {
                ControlHandler.SetPropertyValue(lblGoldbachInfoCalc, "Text", string.Format(Distribution.numberline_isodd, value));
                ControlHandler.SetPropertyValue(gbGoldbach, "Visibility", Visibility.Collapsed);
            }
            else if (value.Equals(PrimesBigInteger.Two))  // value = 2
            {
                ControlHandler.SetPropertyValue(lblGoldbachInfoCalc, "Text", Distribution.numberline_istwo);
                ControlHandler.SetPropertyValue(gbGoldbach, "Visibility", Visibility.Collapsed);
            }
            else // value is even and not prime
            {
                int counter  = 0;
                int maxlines = 1000;

                if (!value.IsProbablePrime(10))
                {
                    long x    = value.LongValue;
                    int  i    = 0;
                    long sum1 = PrimeNumbers.primes[i];
                    while (sum1 <= x / 2)
                    {
                        long sum2 = x - sum1;
                        if (BigIntegerHelper.IsProbablePrime(sum2))
                        //if (PrimeNumbers.isprime.Contains(sum2))
                        {
                            counter++;

                            if (counter < maxlines)
                            {
                                logGoldbach.Info(string.Format("{0} + {1}   ", sum1, sum2));
                            }
                            else if (counter == maxlines)
                            {
                                logGoldbach.Info(string.Format(Distribution.numberline_goldbachmaxlines, maxlines));
                            }

                            if (counter % 50 == 0)
                            {
                                string fmt = (counter == 1) ? Distribution.numberline_goldbachfoundsum : Distribution.numberline_goldbachfoundsums;
                                ControlHandler.SetPropertyValue(lblGoldbachInfoCalc, "Text", string.Format(fmt, counter, value));
                            }
                        }
                        sum1 = (++i < PrimeNumbers.primes.Length) ? PrimeNumbers.primes[i] : (long)BigIntegerHelper.NextProbablePrime(sum1 + 1);
                    }

                    string fmt1 = (counter == 1) ? Distribution.numberline_goldbachfoundsum : Distribution.numberline_goldbachfoundsums;
                    ControlHandler.SetPropertyValue(lblGoldbachInfoCalc, "Text", string.Format(fmt1, counter, value));
                    ControlHandler.SetPropertyValue(gbGoldbach, "Visibility", goldbachIsOpen ? Visibility.Visible : Visibility.Collapsed);
                }
            }

            if (GoldbachDone != null)
            {
                GoldbachDone();
            }
        }
Exemple #30
0
        /// <summary>
        /// Called by the environment to start generating of public/private keys
        /// </summary>
        public void Execute()
        {
            BigInteger p;
            BigInteger q;
            BigInteger n;
            BigInteger e;
            BigInteger d;

            ProgressChanged(0.0, 1.0);

            switch (settings.Source)
            {
            // manual
            case 0:
                try
                {
                    p = BigIntegerHelper.ParseExpression(settings.P);
                    q = BigIntegerHelper.ParseExpression(settings.Q);
                    e = BigIntegerHelper.ParseExpression(settings.E);

                    if (!BigIntegerHelper.IsProbablePrime(p))
                    {
                        GuiLogMessage(p.ToString() + " is not prime!", NotificationLevel.Error);
                        return;
                    }
                    if (!BigIntegerHelper.IsProbablePrime(q))
                    {
                        GuiLogMessage(q.ToString() + " is not prime!", NotificationLevel.Error);
                        return;
                    }
                    if (p == q)
                    {
                        GuiLogMessage("The primes P and Q can not be equal!", NotificationLevel.Error);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    GuiLogMessage("Invalid Big Number input: " + ex.Message, NotificationLevel.Error);
                    return;
                }

                try
                {
                    D = BigIntegerHelper.ModInverse(e, (p - 1) * (q - 1));
                }
                catch (Exception)
                {
                    GuiLogMessage("RSAKeyGenerator Error: E (" + e + ") can not be inverted.", NotificationLevel.Error);
                    return;
                }

                try
                {
                    N = p * q;
                    E = e;
                }
                catch (Exception ex)
                {
                    GuiLogMessage("Big Number fail: " + ex.Message, NotificationLevel.Error);
                    return;
                }
                break;

            case 1:
                try
                {
                    n = BigIntegerHelper.ParseExpression(settings.N);
                    d = BigIntegerHelper.ParseExpression(settings.D);
                    e = BigIntegerHelper.ParseExpression(settings.E);
                }
                catch (Exception ex)
                {
                    GuiLogMessage("Invalid Big Number input: " + ex.Message, NotificationLevel.Error);
                    return;
                }

                try
                {
                    N = n;
                    E = e;
                    D = d;
                }
                catch (Exception ex)
                {
                    GuiLogMessage("Big Number fail: " + ex.Message, NotificationLevel.Error);
                    return;
                }
                break;

            //randomly generated
            case 2:
                try
                {
                    n = BigInteger.Parse(this.settings.Range);

                    switch (this.settings.RangeType)
                    {
                    case 0:         // n = number of bits for primes
                        if ((int)n <= 2)
                        {
                            GuiLogMessage("Value for n has to be greater than 2.", NotificationLevel.Error);
                            return;
                        }

                        if (n >= 1024)
                        {
                            GuiLogMessage("Please note that the generation of prime numbers with " + n + " bits may take some time...", NotificationLevel.Warning);
                        }

                        // calculate the number of expected tries for the indeterministic prime number generation using the density of primes in the given region
                        BigInteger limit = ((BigInteger)1) << (int)n;
                        limittries    = (int)(BigInteger.Log(limit) / 6);
                        expectedtries = 2 * limittries;

                        tries = 0;
                        p     = this.RandomPrimeBits((int)n);
                        tries = limittries;  limittries = expectedtries;
                        do
                        {
                            q = this.RandomPrimeBits((int)n);
                        } while (p == q);
                        break;

                    case 1:         // n = upper limit for primes
                    default:
                        if (n <= 4)
                        {
                            GuiLogMessage("Value for n has to be greater than 4", NotificationLevel.Error);
                            return;
                        }

                        p = BigIntegerHelper.RandomPrimeLimit(n + 1);
                        ProgressChanged(0.5, 1.0);
                        do
                        {
                            q = BigIntegerHelper.RandomPrimeLimit(n + 1);
                        } while (p == q);
                        break;
                    }
                }
                catch
                {
                    GuiLogMessage("Please enter an integer value for n.", NotificationLevel.Error);
                    return;
                }

                BigInteger phi = (p - 1) * (q - 1);

                // generate E for the given values of p and q
                bool found = false;
                foreach (var ee in new BigInteger[] { 3, 5, 7, 11, 17, 65537 })
                {
                    if (ee < phi && ee.GCD(phi) == 1)
                    {
                        E = ee;  found = true; break;
                    }
                }
                if (!found)
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        e = BigIntegerHelper.RandomIntLimit(phi);
                        if (e >= 2 && e.GCD(phi) == 1)
                        {
                            E = e; found = true; break;
                        }
                    }
                }
                if (!found)
                {
                    GuiLogMessage("Could not generate a valid E for p=" + p + " and q=" + q + ".", NotificationLevel.Error);
                    return;
                }

                N = p * q;
                D = BigIntegerHelper.ModInverse(E, phi);
                break;

            //using x509 certificate
            case 3:
                try
                {
                    X509Certificate2 cert;
                    RSAParameters    par;

                    if (this.settings.Password != "")
                    {
                        GuiLogMessage("Password entered. Try getting public and private key", NotificationLevel.Info);
                        cert = new X509Certificate2(settings.CertificateFile, settings.Password, X509KeyStorageFlags.Exportable);
                        if (cert == null || cert.PrivateKey == null)
                        {
                            throw new Exception("Private Key of X509Certificate could not be fetched");
                        }
                        RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PrivateKey;
                        par = provider.ExportParameters(true);
                    }
                    else
                    {
                        GuiLogMessage("No Password entered. Try loading public key only", NotificationLevel.Info);
                        cert = new X509Certificate2(settings.CertificateFile);
                        if (cert == null || cert.PublicKey == null || cert.PublicKey.Key == null)
                        {
                            throw new Exception("Private Key of X509Certificate could not be fetched");
                        }
                        RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PublicKey.Key;
                        par = provider.ExportParameters(false);
                    }

                    try
                    {
                        N = new BigInteger(par.Modulus);
                    }
                    catch (Exception ex)
                    {
                        GuiLogMessage("Could not get N from certificate: " + ex.Message, NotificationLevel.Warning);
                    }

                    try
                    {
                        E = new BigInteger(par.Exponent);
                    }
                    catch (Exception ex)
                    {
                        GuiLogMessage("Could not get E from certificate: " + ex.Message, NotificationLevel.Warning);
                    }

                    try
                    {
                        if (this.settings.Password != "")
                        {
                            D = new BigInteger(par.D);
                        }
                        else
                        {
                            D = 0;
                        }
                    }
                    catch (Exception ex)
                    {
                        GuiLogMessage("Could not get D from certificate: " + ex.Message, NotificationLevel.Warning);
                    }
                }
                catch (Exception ex)
                {
                    GuiLogMessage("Could not load the selected certificate: " + ex.Message, NotificationLevel.Error);
                }
                break;
            }

            ProgressChanged(1.0, 1.0);
        }