isProbablePrime() public method

public isProbablePrime ( ) : bool
return bool
Ejemplo n.º 1
0
        public RSA(BigInteger p, BigInteger q)
        {
            if (!p.isProbablePrime())
            {
                throw new Exception("Podana przez Ciebie liczba p prawdopodobnie nie jest liczbą pierwszą!");
            }

            if (!q.isProbablePrime())
            {
                throw new Exception("Podana przez Ciebie liczba q prawdopodobnie nie jest liczbą pierwszą!");
            }

            this.p = p;
            this.q = q;
            this.n = this.p * this.q;
            this.eulerOfN = (this.p - 1) * (this.q - 1);
            Random randomGenerator = new Random(DateTime.Now.Millisecond);

            do
            {
                this.e = this.eulerOfN.genCoPrime(randomGenerator.Next(1, this.eulerOfN.bitCount()), randomGenerator);
            }
            while ((this.e > this.eulerOfN) && this.e.gcd(this.eulerOfN) > 1);

            this.d = e.modInverse(eulerOfN);
        }
Ejemplo n.º 2
0
 private void Initialize(BigInteger p, BigInteger g, BigInteger x, int secretLen, bool checkInput)
 {
     if (!p.isProbablePrime() || g <= 0 || g >= p || (x != null && (x <= 0 || x > p - 2)))
     {
         throw new CryptographicException();
     }
     if (secretLen == 0)
     {
         secretLen = p.bitCount();
     }
     this.m_P = p;
     this.m_G = g;
     if (x == null)
     {
         BigInteger bi = this.m_P - 1;
         this.m_X = BigInteger.genRandom(secretLen);
         while (this.m_X >= bi || this.m_X == 0u)
         {
             this.m_X = BigInteger.genRandom(secretLen);
         }
     }
     else
     {
         this.m_X = x;
     }
 }
Ejemplo n.º 3
0
        public RSA(BigInteger p, BigInteger q)
        {
            if (!p.isProbablePrime())
            {
                throw new Exception("Podana przez Ciebie liczba p prawdopodobnie nie jest liczbą pierwszą!");
            }

            if (!q.isProbablePrime())
            {
                throw new Exception("Podana przez Ciebie liczba q prawdopodobnie nie jest liczbą pierwszą!");
            }

            this.p        = p;
            this.q        = q;
            this.n        = this.p * this.q;
            this.eulerOfN = (this.p - 1) * (this.q - 1);
            Random randomGenerator = new Random(DateTime.Now.Millisecond);

            do
            {
                this.e = this.eulerOfN.genCoPrime(randomGenerator.Next(1, this.eulerOfN.bitCount()), randomGenerator);
            }while ((this.e > this.eulerOfN) && this.e.gcd(this.eulerOfN) > 1);

            this.d = e.modInverse(eulerOfN);
        }
Ejemplo n.º 4
0
 // initializes the private variables (throws CryptographicException)
 private void Initialize(BigInteger p, BigInteger g, BigInteger x, int secretLen, bool checkInput)
 {
     if (!p.isProbablePrime() || g <= 0 || g >= p || (x != null && (x <= 0 || x > p - 2)))
     {
         throw new CryptographicException();
     }
     // default is to generate a number as large as the prime this
     // is usually overkill, but it's the most secure thing we can
     // do if the user doesn't specify a desired secret length ...
     if (secretLen == 0)
     {
         secretLen = p.bitCount();
     }
     m_P = p;
     m_G = g;
     if (x == null)
     {
         BigInteger pm1 = m_P - 1;
         for (m_X = BigInteger.genRandom(secretLen); m_X >= pm1 || m_X == 0; m_X = BigInteger.genRandom(secretLen))
         {
         }
     }
     else
     {
         m_X = x;
     }
 }
Ejemplo n.º 5
0
        public override MazeErrorCode onReceiveData(byte[] Data, ref byte[] ResponseData)
        {
            ResponseData = new byte[0];
            switch (base.Step)
            {
            case 1:
            {
                if (Data.Length != 32)
                {
                    SysLogger.Log("[MazeHandShake][Server] Receive Length missmatch", SysLogType.Debug);
                    return(MazeErrorCode.Error);
                }

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

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

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

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

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

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

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

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

            return(MazeErrorCode.Success);
        }
Ejemplo n.º 6
0
        private byte[] GetFailResponseData()
        {
            Random     rnd      = new Random();
            BigInteger retPrime = BigInteger.genPseudoPrime(64, 30, rnd);

            do
            {
                retPrime++;
            } while (retPrime.isProbablePrime());
            return(retPrime.getBytes()); //not encrypted, client knows this will fail
        }
Ejemplo n.º 7
0
    public static BigInteger genPseudoPrime(int bits, int confidence, Random rand)
    {
        BigInteger result = new BigInteger();
        bool       done   = false;

        while (!done)
        {
            result.genRandomBits(bits, rand);
            result.data[0] |= 0x01;             // make it odd

            // prime test
            done = result.isProbablePrime(confidence);
        }
        return(result);
    }
Ejemplo n.º 8
0
        public void testRun()
        {
            const int rounds = 50;

            Console.WriteLine("Test Performance of Miller Rabin Prime Probe");
            Console.WriteLine("Rounds: " + rounds);
            Console.WriteLine("Cycles per Round: " + cycles);


            prime = BigPrimes.Dig100;
            ptest = new MillerRabin(round5);
            Console.WriteLine("\nTest 100 Number Prime 5 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            ptest = new MillerRabin(round10);
            Console.WriteLine("\nTest 100 Number Prime 10 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            ptest = new MillerRabin(round15);
            Console.WriteLine("\nTest 100 Number Prime 15 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            Assert.AreEqual(prime.isProbablePrime(round15), bolprime);


            prime = BigPrimes.Dig500;
            ptest = new MillerRabin(round5);
            Console.WriteLine("\nTest 5000 Number Prime 5 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            ptest = new MillerRabin(round10);
            Console.WriteLine("\nTest 5000 Number Prime 10 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            ptest = new MillerRabin(round15);
            Console.WriteLine("\nTest 5000 Number Prime 15 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            Assert.AreEqual(prime.isProbablePrime(round15), bolprime);

            prime = BigPrimes.Dig1000;
            ptest = new MillerRabin(round5);
            Console.WriteLine("\nTest 10000 Number Prime 5 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            ptest = new MillerRabin(round10);
            Console.WriteLine("\nTest 10000 Number Prime 10 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            ptest = new MillerRabin(round15);
            Console.WriteLine("\nTest 10000 Number Prime 15 Rounds");
            PerfMeter.run(new Action(testPrimeProbe), rounds);
            Assert.AreEqual(prime.isProbablePrime(round15), bolprime);
        }
Ejemplo n.º 9
0
        private void gennr(bool cb)
        {
            Random rn = new Random();

            if (cb == true)
            {
                do
                {
                    q = BigInteger.genPseudoPrime(160, 100, rn);
                    r = BigInteger.genPseudoPrime(864, 100, rn);
                    p = new BigInteger(2 * q * r + 1);
                }while (!p.isProbablePrime(100));
            }
            else
            {
                q = new BigInteger("1357240200991138844597040462790625645217868549141", 10);
                r = new BigInteger("113598119916368178543726680204430381937875824948480914597565387121457881140775963786806669392598432983134451798231342845963966490631191394432315401337959287970864814764728934773343090591391155652090238298766028332871998156437678877229180157399463412668170350113", 10);
                p = new BigInteger("308359870215014078485257030866450886542952487603077718832462434453183859939031089613588944732186396626095766979593995910212976752989132511989881464667656451202440745056276306885148035449349526765128968559736391792793918308470057210553727052388063491635390548699144068380621588468735471047786563470306630805867", 10);
            }
        }
Ejemplo n.º 10
0
            static SRP()
            {
                // initialize N
                {
                    NHex =
                        //512bit
                        "D4C7F8A2B32C11B8FBA9581EC4BA4F1B04215642EF7355E37C0FC0443EF756EA2C6B8EEB755A1C723027663CAA265EF785B8FF6A9B35227A52D86633DBDFCA43";

                    N       = new BigInteger(NHex, 16);
                    _nbits  = N.bitCount();
                    Nminus1 = N - 1;

                    if (!N.isProbablePrime(80))
                    {
                        throw new Exception("Warning: N is not prime");
                    }

                    if (!(Nminus1 / 2).isProbablePrime(80))
                    {
                        throw new Exception("Warning: (N-1)/2 is not prime");
                    }
                }

                // initialize g
                {
                    gHex = "2";
                    g    = new BigInteger(gHex, 16);
                }

                // initialize k = H(N || g)
                {
                    BigInteger ktmp = new BigInteger(HHex(
                                                         (((NHex.Length & 1) == 0) ? "" : "0") + NHex +
                                                         new string('0', NHex.Length - gHex.Length) + gHex
                                                         ), 16);

                    k    = (ktmp < N) ? ktmp : (ktmp % N);
                    kHex = k.ToHexString();
                }
            }
        private void Initialize(BigInteger p, BigInteger g, BigInteger x)
        {
            if (!p.isProbablePrime() || g <= 0 || g >= p)
            {
                throw new CryptographicException("Inputs p or g are not as expected. P probably isn't a prime or G is less than zero or more than P.");
            }

            if (x != null)
            {
                _x = x;
            }
            else
            {
                var pMinus1   = p - 1;
                var secretLen = p.bitCount();
                for (_x = BigInteger.genRandom(secretLen); _x >= pMinus1 || _x == 0; _x = BigInteger.genRandom(secretLen))
                {
                }
            }

            _p = p;
            _g = g;
        }
Ejemplo n.º 12
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.º 13
0
        //***********************************************************************
        // Generates a positive BigInteger that is probably prime.
        //***********************************************************************

        public static BigInteger genPseudoPrime(int bits, int confidence, Random rand)
        {
	        BigInteger result = new BigInteger();
	        bool done = false;

	        while(!done)
	        {
		        result.genRandomBits(bits, rand);
		        result.data[0] |= 0x01;		// make it odd

		        // prime test
		        done = result.isProbablePrime(confidence);
	        }
	        return result;
        }
Ejemplo n.º 14
0
 private void ExpectPrime(BigInteger bi)
 {
     Assert.AreEqual(true, bi.isProbablePrime());
 }
Ejemplo n.º 15
0
		void runAllPrimes()
		{
			b_runningAllPrimes=true;

			Hashtable ht = new Hashtable();

			if(!b_PrimesLoaded)
			{
				loadPrimes();
			}
            this.Invoke((MethodInvoker)delegate{
                lblAllPrimes.Text = "Searching for primes...";
            });

			v_startPrime=int.Parse(txtAllPrimesStart.Text);
			v_endPrime = int.Parse(txtAllPrimesEnd.Text);

			int v_num1=0;
			int v_bnum1=0;
			int v_num2=0;
			int v_cnt=0;

			if(!isOdd(v_startPrime))
			{
				v_startPrime++;
			}
			if(isOdd(v_endPrime))
			{
				v_endPrime++;
			}
			for(int i = v_startPrime;i<=v_endPrime;i=i+2)
			{
				if(!b_runningAllPrimes)
				{
					break;
				}
				v_num1=i;
				v_num2=v_endPrime-i;
                double v_num3 = Math.Floor(((double)v_num2) / 2);
                double v_num4 = Math.Floor(((double)v_num3) / 2);
                double v_num5 = Math.Floor(((double)v_num4) / 2);
                if (!isOdd(v_num3))
                {
                    v_num3++;
                }
                if (!isOdd(v_num4))
                {
                    v_num4++;
                }
                if (!isOdd(v_num5))
                {
                    v_num5++;
                }

                this.Invoke((MethodInvoker)delegate
                {
                    txtAllPrimesStart.Text = v_startPrime.ToString();
                    txtAllPrimesEnd.Text = v_endPrime.ToString();
                });
				if((v_cnt%50)==0)
				{
                    this.Invoke((MethodInvoker)delegate
                    {
                        lblAllPrimes.Text = v_num1.ToString() + " - " + v_num2.ToString() + " - " + v_num3.ToString() + " - " + v_num4.ToString() + " - " + v_num5.ToString() + "\n" + htctrl.Count.ToString() + " - " + ht.Count.ToString() + "\n" + listBoxAllPrimes.Items.Count.ToString();
                    });
				}
				BigInteger bi1 = new BigInteger(v_num1);
				BigInteger bi2 = new BigInteger(v_num2);
					
				if (isOdd(v_num1) && !htctrl.ContainsKey(v_num1) && !ht.ContainsKey(v_num1) && bi1.isProbablePrime(10))// isPrime(v_num1))
				{
					ht.Add(v_num1,v_num1);
					htctrl.Add(v_num1,v_num1);
				}
				if (isOdd(v_num2) && !htctrl.ContainsKey(v_num2) && !ht.ContainsKey(v_num2) && bi2.isProbablePrime(10))// isPrime(v_num2))
				{
					ht.Add(v_num2,v_num2);
					htctrl.Add(v_num2,v_num2);
				}
                if (isOdd(v_num3) && !htctrl.ContainsKey(v_num3) && !ht.ContainsKey(v_num3) && bi2.isProbablePrime(10))// isPrime(v_num3))
                {
                    ht.Add(v_num3, v_num3);
                    htctrl.Add(v_num3, v_num3);
                }
                if (isOdd(v_num4) && !htctrl.ContainsKey(v_num4) && !ht.ContainsKey(v_num4) && bi2.isProbablePrime(10))// isPrime(v_num4))
                {
                    ht.Add(v_num4, v_num4);
                    htctrl.Add(v_num4, v_num4);
                }
                if (isOdd(v_num5) && !htctrl.ContainsKey(v_num5) && !ht.ContainsKey(v_num5) && bi2.isProbablePrime(10))// isPrime(v_num5))
                {
                    ht.Add(v_num5, v_num5);
                    htctrl.Add(v_num5, v_num5);
                }
                string strtxtAllPrimesSaveAfter = "";
                this.Invoke((MethodInvoker)delegate
                {
                    strtxtAllPrimesSaveAfter=txtAllPrimesSaveAfter.Text;
                });
                if (ht.Count >= int.Parse(strtxtAllPrimesSaveAfter))
				{
                    this.Invoke((MethodInvoker)delegate
                    {
                        lblAllPrimes.Text = v_num1.ToString() + " - " + v_num2.ToString() + " - " + v_num3.ToString() + " - " + v_num4.ToString() + " - " + v_num5.ToString() + "\n" + htctrl.Count.ToString() + " - " + ht.Count.ToString() + "\n" + listBoxAllPrimes.Items.Count.ToString();
                    });
					v_bnum1=v_num1;
					
					foreach(object k in ht.Keys)
					{
                        this.Invoke((MethodInvoker)delegate
                        {
                            listBoxAllPrimes.Items.Add(k + "\t" + DateTime.Now.ToString());
                            listBoxAllPrimes.SelectedIndex = listBoxAllPrimes.Items.Count - 1;
                        });
						//addToPrimeDb(k.ToString());
					}
					
					ht.Clear();
				}
                this.Invoke((MethodInvoker)delegate
                {
			        if (listBoxAllPrimes.Items.Count >= int.Parse(txtAllPrimesSaveAfter.Text)*10)
			        {
                        listBoxAllPrimes.Items.Clear();
			        }
                });
                GC.Collect();
				if ((v_cnt % 100)==0 )
				{
					Application.DoEvents();
				}
				if(!b_runningAllPrimes)
				{
					break;
				}

				v_cnt++;
			}

			tAllPrimes.Abort();
            this.Invoke((MethodInvoker)delegate
            {
                lblAllPrimes.Text = "Exiting runAllPrimes()...";
            });
		}
Ejemplo n.º 16
0
        private DSA_Secret_Key GenerateParams(int keyLength)
        {
            byte[] seed  = new byte[20];
            byte[] part1 = new byte[20];
            byte[] part2 = new byte[20];
            byte[] u     = new byte[20];
            RandomNumberGenerator rng = RandomNumberGenerator.Create();

            BigInteger     p = new BigInteger(); // prime
            BigInteger     q = new BigInteger(); // group order
            BigInteger     g;                    // group generator
            DSA_Secret_Key dskKey = new DSA_Secret_Key();

            SHA1 sha = SHA1.Create();

            int n = (keyLength - 1) / 160;

            byte[] w           = new byte [keyLength / 8];
            bool   primesFound = false;

            while (!primesFound)
            {
                do
                {
                    rng.GetBytes(seed);
                    part1 = sha.ComputeHash(seed);
                    Array.Copy(seed, 0, part2, 0, seed.Length);

                    add(part2, seed, 1);

                    part2 = sha.ComputeHash(part2);

                    for (int i = 0; i != u.Length; i++)
                    {
                        u[i] = (byte)(part1[i] ^ part2[i]);
                    }

                    // first bit must be set (to respect key length)
                    u[0] |= (byte)0x80;
                    // last bit must be set (prime are all odds - except 2)
                    u[19] |= (byte)0x01;

                    q = new BigInteger(u);
                } while (!q.isProbablePrime());

                int counter = 0;
                int offset  = 2;
                while (counter < 4096)
                {
                    for (int k = 0; k < n; k++)
                    {
                        add(part1, seed, offset + k);
                        part1 = sha.ComputeHash(part1);
                        Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
                    }

                    add(part1, seed, offset + n);
                    part1 = sha.ComputeHash(part1);
                    Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

                    w[0] |= (byte)0x80;
                    BigInteger xx = new BigInteger(w);

                    BigInteger c = xx % (q * 2);

                    p = xx - (c - 1);

                    if (p.testBit((uint)(keyLength - 1)))
                    {
                        if (p.isProbablePrime())
                        {
                            primesFound = true;
                            break;
                        }
                    }

                    counter += 1;
                    offset  += n + 1;
                }
            }

            // calculate the generator g
            BigInteger pMinusOneOverQ = (p - 1) / q;

            for (;;)
            {
                BigInteger h = new BigInteger();
                h = BigInteger.genRandom(keyLength);
                if ((h <= 1) || (h >= (p - 1)))
                {
                    continue;
                }

                g = h.modPow(pMinusOneOverQ, p);
                if (g <= 1)
                {
                    continue;
                }
                break;
            }

            dskKey.p = p;
            dskKey.q = q;
            dskKey.g = g;

            return(dskKey);
        }
Ejemplo n.º 17
0
 private void gennr(bool cb)
 {
     Random rn = new Random();
     if (cb == true)
     {
         do
         {
             q = BigInteger.genPseudoPrime(160, 100, rn);
             r = BigInteger.genPseudoPrime(864, 100, rn);
             p = new BigInteger(2 * q * r + 1);
         }
         while (!p.isProbablePrime(100));
     }
     else
     {
         q = new BigInteger("1357240200991138844597040462790625645217868549141", 10);
         r = new BigInteger("113598119916368178543726680204430381937875824948480914597565387121457881140775963786806669392598432983134451798231342845963966490631191394432315401337959287970864814764728934773343090591391155652090238298766028332871998156437678877229180157399463412668170350113", 10);
         p = new BigInteger("308359870215014078485257030866450886542952487603077718832462434453183859939031089613588944732186396626095766979593995910212976752989132511989881464667656451202440745056276306885148035449349526765128968559736391792793918308470057210553727052388063491635390548699144068380621588468735471047786563470306630805867", 10);
     }
 }
Ejemplo n.º 18
0
 private void ExpectComposite(BigInteger bi)
 {
     Assertion.AssertEquals(false, bi.isProbablePrime());
 }
Ejemplo n.º 19
0
        /**
         * which generates the p and g values from the given parameters,
         * returning the DSAParameters object.
         * <p>
         * Note: can take a while...
         */
        public DSAParameters generateParameters()
        {
            byte[]     seed  = new byte[20];
            byte[]     part1 = new byte[20];
            byte[]     part2 = new byte[20];
            byte[]     u     = new byte[20];
            SHA1Digest sha1  = new SHA1Digest();
            int        n     = (size - 1) / 160;

            byte[] w = new byte[size / 8];

            BigInteger q = null, p = null, g = null;
            int        counter     = 0;
            bool       primesFound = false;

            while (!primesFound)
            {
                do
                {
                    random.nextBytes(seed);

                    sha1.update(seed, 0, seed.Length);

                    sha1.doFinal(part1, 0);

                    Array.Copy(seed, 0, part2, 0, seed.Length);

                    add(part2, seed, 1);

                    sha1.update(part2, 0, part2.Length);

                    sha1.doFinal(part2, 0);

                    for (int i = 0; i != u.Length; i++)
                    {
                        u[i] = (byte)(part1[i] ^ part2[i]);
                    }

                    u[0]  |= (byte)0x80;
                    u[19] |= (byte)0x01;

                    q = new BigInteger(1, u);
                }while (!q.isProbablePrime(certainty));

                counter = 0;

                int offset = 2;

                while (counter < 4096)
                {
                    for (int k = 0; k < n; k++)
                    {
                        add(part1, seed, offset + k);
                        sha1.update(part1, 0, part1.Length);
                        sha1.doFinal(part1, 0);
                        Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
                    }

                    add(part1, seed, offset + n);
                    sha1.update(part1, 0, part1.Length);
                    sha1.doFinal(part1, 0);
                    Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

                    w[0] |= (byte)0x80;

                    BigInteger x = new BigInteger(1, w);

                    BigInteger c = x.mod(q.multiply(TWO));

                    p = x.subtract(c.subtract(ONE));

                    if (p.testBit(size - 1))
                    {
                        if (p.isProbablePrime(certainty))
                        {
                            primesFound = true;
                            break;
                        }
                    }

                    counter += 1;
                    offset  += n + 1;
                }
            }

            //
            // calculate the generator g
            //
            BigInteger pMinusOneOverQ = p.subtract(ONE).divide(q);

            for (;;)
            {
                BigInteger h = new BigInteger(size, random);
                if (h.compareTo(ONE) <= 0 || h.compareTo(p.subtract(ONE)) >= 0)
                {
                    continue;
                }

                g = h.modPow(pMinusOneOverQ, p);
                if (g.compareTo(ONE) <= 0)
                {
                    continue;
                }

                break;
            }

            return(new DSAParameters(p, q, g, new DSAValidationParameters(seed, counter)));
        }
Ejemplo n.º 20
0
		void runAllPrimes()
		{
			b_runningAllPrimes=true;

			Hashtable ht = new Hashtable();

			if(!b_PrimesLoaded)
			{
				loadPrimes();
			}

			lblAllPrimes.Text="Searching for primes...";
			

			v_startPrime=int.Parse(txtAllPrimesStart.Text);
			v_endPrime = int.Parse(txtAllPrimesEnd.Text);

			int v_num1=0;
			int v_bnum1=0;
			int v_num2=0;
			int v_cnt=0;

			if(!isOdd(v_startPrime))
			{
				v_startPrime++;
			}
			if(isOdd(v_endPrime))
			{
				v_endPrime++;
			}
			for(int i = v_startPrime;i<=v_endPrime;i=i+2)
			{
				if(!b_runningAllPrimes)
				{
					break;
				}
				v_num1=i;
				v_num2=v_endPrime-i;

				txtAllPrimesStart.Text = v_startPrime.ToString();
				txtAllPrimesEnd.Text = v_endPrime.ToString();

				if((v_cnt%50)==0)
				{
					lblAllPrimes.Text=v_num1.ToString() + " - " + v_num2.ToString() + "\n" + htctrl.Count.ToString() + " - " + ht.Count.ToString() + "\n" + listBoxAllPrimes.Items.Count.ToString();
				}
				BigInteger bi1 = new BigInteger(v_num1);
				BigInteger bi2 = new BigInteger(v_num2);
					
				if (isOdd(v_num1) && !htctrl.ContainsKey(v_num1) && !ht.ContainsKey(v_num1) && bi1.isProbablePrime(10))// isPrime(v_num1))
				{
					ht.Add(v_num1,v_num1);
					htctrl.Add(v_num1,v_num1);
				}
				if (isOdd(v_num2) && !htctrl.ContainsKey(v_num2) && !ht.ContainsKey(v_num2) && bi2.isProbablePrime(10))// isPrime(v_num2))
				{
					ht.Add(v_num2,v_num2);
					htctrl.Add(v_num2,v_num2);
				}
				if (ht.Count >= int.Parse(txtAllPrimesSaveAfter.Text))
				{
					lblAllPrimes.Text=v_num1.ToString() + " - " + v_num2.ToString() + "\n" + htctrl.Count.ToString() + " - " + ht.Count.ToString() + "\n" + listBoxAllPrimes.Items.Count.ToString();
					v_bnum1=v_num1;
					
					foreach(object k in ht.Keys)
					{
						listBoxAllPrimes.Items.Add(k + "\t" + DateTime.Now.ToString());
						listBoxAllPrimes.SelectedIndex=listBoxAllPrimes.Items.Count-1;
						addToPrimeDb(k.ToString());
					}
					
					ht.Clear();
				}
				if (listBoxAllPrimes.Items.Count >= int.Parse(txtAllPrimesSaveAfter.Text)*10)
				{
					listBoxAllPrimes.Items.Clear();
				}
				GC.Collect();
				if ((v_cnt % 100)==0 )
				{
					Application.DoEvents();
				}
				if(!b_runningAllPrimes)
				{
					break;
				}

				v_cnt++;
			}

			tAllPrimes.Abort();
			lblAllPrimes.Text="Exiting runAllPrimes()...";
		}
Ejemplo n.º 21
0
    public static void GenerateRSAKey(int moduleBitLen, int pubKeyBitLen, out BigInteger publicExponent, out BigInteger module, out BigInteger privateExponent)
    {
        /* from Wikipedia:
        RSA involves a public key and a private key. The public key can be known to everyone and is used for encrypting messages. Messages encrypted with the public key can only be decrypted using the private key. The keys for the RSA algorithm are generated the following way:
        Choose two distinct prime numbers p and q.
        For security purposes, the integers p and q should be chosen at random, and should be of similar bit-length. Prime integers can be efficiently found using a primality test.
        Compute n = pq.
        n is used as the modulus for both the public and private keys
        Compute φ(n) = (p – 1)(q – 1), where φ is Euler's totient function.
        Choose an integer e such that 1 < e < φ(n) and greatest common divisor of (e, φ(n)) = 1; i.e., e and φ(n) are coprime.
        e is released as the public key exponent.
        e having a short bit-length and small Hamming weight results in more efficient encryption - most commonly 0x10001 = 65,537. However, small values of e (such as 3) have been shown to be less secure in some settings.[4]
        Determine d as:
        d = e^-1 (mod φ(n))

        i.e., d is the multiplicative inverse of e mod φ(n).
        This is more clearly stated as solve for d given (de) mod φ(n) = 1
        This is often computed using the extended Euclidean algorithm.
        d is kept as the private key exponent.
         * */
        Random r = new Random();
        BigInteger P = new BigInteger();
        BigInteger Q = new BigInteger();
        int bitLenP = moduleBitLen >> 1;
        int bitLenQ = bitLenP + (moduleBitLen & 1);
        while (true)
        {
            while (true)
            {
                P.genRandomBits(bitLenP, r);
                P.data[0] |= 0x01;		// make it odd
                if (P.isProbablePrime())
                    break;
            }
            while (true)
            {
                Q.genRandomBits(bitLenQ, r);
                Q.data[0] |= 0x01;		// make it odd
                if (Q.isProbablePrime())
                    break;
            }
            var N = P * Q;
            var PHI = (P - 1) * (Q - 1);
            var E = PHI.genCoPrime(pubKeyBitLen,r);
            BigInteger D = E.modInverse(PHI);
            publicExponent = E;
            privateExponent = D;
            module = N;
            return;
        }
    }
Ejemplo n.º 22
0
        public static RSAPrivateCrtKey generateKey(int bits, BigInteger e,
                                                   RandomNumberGenerator secRand)
        {
            BigInteger p        = null;
            BigInteger q        = null;
            BigInteger t        = null;
            BigInteger phi      = null;
            BigInteger d        = null;
            BigInteger u        = null;
            BigInteger n        = null;
            bool       finished = false;

            int pbits = (bits + 1) / 2;
            int qbits = bits - pbits;

            while (!finished)
            {
                p = new BigInteger(pbits, 25, secRand);

                q = new BigInteger(qbits, 25, secRand);


                if (p == q)
                {
                    continue;
                }
                else if (p == q)
                {
                    t = q;
                    q = p;
                    p = t;
                }

                if (!p.isProbablePrime(25))
                {
                    continue;
                }

                if (!q.isProbablePrime(25))
                {
                    continue;
                }

                t = p.gcd(q);
                if (t.compareTo(BigInteger.ONE) != 0)
                {
                    continue;
                }

                n = p.multiply(q);

                if (n.bitLength() != bits)
                {
                    continue;
                }

                phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
                d   = e.modInverse(phi);
                u   = q.modInverse(p);

                finished = true;
            }

            return(new RSAPrivateCrtKey(n, e, d, p, q,
                                        RSA.getPrimeExponent(d, p),
                                        RSA.getPrimeExponent(d, q),
                                        u));
        }
Ejemplo n.º 23
0
 private void ExpectPrime(BigInteger bi)
 {
     Assertion.AssertEquals(true, bi.isProbablePrime());
 }
Ejemplo n.º 24
0
        private static BigInteger[] findRandomStrongPrime(uint primeBits, int orderBits, Rng random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger u, aux, aux2;

            long[]     table_q, table_u, prime_table;
            PrimeSieve sieve = new PrimeSieve(16000);
            uint       table_count = sieve.AvailablePrimes() - 1;
            int        i, j;
            bool       flag;
            BigInteger prime = null, order = null;

            order = BigInteger.genPseudoPrime(orderBits, 20, random);

            prime_table = new long[table_count];
            table_q     = new long[table_count];
            table_u     = new long[table_count];

            i = 0;
            for (int pN = 2; pN != 0; pN = sieve.getNextPrime(pN), i++)
            {
                prime_table[i] = (long)pN;
            }

            for (i = 0; i < table_count; i++)
            {
                table_q[i] =
                    (((order % new BigInteger(prime_table[i])).LongValue()) *
                     (long)2) % prime_table[i];
            }

            while (true)
            {
                u = new BigInteger();
                u.genRandomBits((int)primeBits, random);
                u.setBit(primeBits - 1);
                aux  = order << 1;
                aux2 = u % aux;
                u    = u - aux2;
                u    = u + one;

                if (u.bitCount() <= (primeBits - 1))
                {
                    continue;
                }

                for (j = 0; j < table_count; j++)
                {
                    table_u[j] =
                        (u % new BigInteger(prime_table[j])).LongValue();
                }

                aux2 = order << 1;

                for (i = 0; i < (1 << 24); i++)
                {
                    long cur_p;
                    long value;

                    flag = true;
                    for (j = 1; j < table_count; j++)
                    {
                        cur_p = prime_table[j];
                        value = table_u[j];
                        if (value >= cur_p)
                        {
                            value -= cur_p;
                        }
                        if (value == 0)
                        {
                            flag = false;
                        }
                        table_u[j] = value + table_q[j];
                    }
                    if (!flag)
                    {
                        continue;
                    }

                    aux   = aux2 * new BigInteger(i);
                    prime = u + aux;

                    if (prime.bitCount() > primeBits)
                    {
                        continue;
                    }

                    if (prime.isProbablePrime(20))
                    {
                        break;
                    }
                }

                if (i < (1 << 24))
                {
                    break;
                }
            }

            return(new BigInteger[] { prime, order });
        }
Ejemplo n.º 25
0
        private void BuildKeys()
        {
            //Make a call to Generate_Primes.
            BigInteger P = new BigInteger(m_RSAParams.P);
            BigInteger Q = new BigInteger(m_RSAParams.Q);

            //Exponent.  This needs to be a number such that the
            //GCD of the Exponent and Phi is 1.  The larger the exp.
            //the more secure, but it increases encryption time.
            BigInteger E = new BigInteger(m_RSAParams.E);

            BigInteger N = new BigInteger(0);
            //Public and Private Key Part (Modulus)
            BigInteger D = new BigInteger(0);
            //Private Key Part
            BigInteger DP  = new BigInteger(0);
            BigInteger DQ  = new BigInteger(0);
            BigInteger IQ  = new BigInteger(0);
            BigInteger Phi = new BigInteger(0);

            //Phi

            //Make sure P is greater than Q, swap if less.
            if (P < Q)
            {
                BigInteger biTmp = P;
                P     = Q;
                Q     = biTmp;
                biTmp = null;

                m_RSAParams.P = P.getBytesRaw();
                m_RSAParams.Q = Q.getBytesRaw();
            }

            //Calculate the modulus
            N             = P * Q;
            m_RSAParams.N = N.getBytesRaw();

            //Calculate Phi
            Phi             = (P - 1) * (Q - 1);
            m_RSAParams.Phi = Phi.getBytesRaw();


            //Make sure our Exponent will work, or choose a larger one.
            while (Phi.gcd(E) > 1)
            {
                //If the GCD is greater than 1 iterate the Exponent
                E = E + 2;
                //Also make sure the Exponent is prime.
                while (!E.isProbablePrime())
                {
                    E = E + 2;
                }
            }

            //Make sure the params contain the updated E value
            m_RSAParams.E = E.getBytesRaw();


            //Calculate the private exponent D.
            D             = E.modInverse(Phi);
            m_RSAParams.D = D.getBytesRaw();

            //Calculate DP
            DP             = E.modInverse(P - 1);
            m_RSAParams.DP = DP.getBytesRaw();

            //Calculate DQ
            DQ             = E.modInverse(Q - 1);
            m_RSAParams.DQ = DQ.getBytesRaw();

            //Calculate InverseQ
            IQ             = Q.modInverse(P);
            m_RSAParams.IQ = IQ.getBytesRaw();

            m_KeyLoaded = true;
            m_isBusy    = false;

            OnKeysGenerated(this);
        }