Example #1
0
        public static BigInteger GetPrime(int bits, Ibasa.Numerics.Random.Generator random)
        {
            if (bits < 2)
                throw new ArgumentException("bits is less than two.", "bits");

            BigInteger pi = 2;

            if (bits > 4)
                pi = pi * 3;
            if (bits > 6)
                pi = pi * 5 * 7;
            if (bits > 8)
                pi = pi * 11 * 13;
            if (bits > 10)
                pi = pi * 17 * 19 * 23 * 29;

            byte[] bytes = new byte[((bits + 7) / 8) + 1];
            var bytemask = (byte)(uint.MaxValue >> (32 - (bits % 8)));
            var intmask = BigInteger.Pow(2, bits) - 1;

            BigInteger prime;
            do
            {
                do
                {
                    random.NextBytes(bytes);
                    bytes[bytes.Length - 1] = 0;
                    bytes[bytes.Length - 2] &= bytemask;
                    prime = new BigInteger(bytes);
                } while (prime.IsEven);
            } while (BigInteger.GreatestCommonDivisor(prime, pi) != 1);

            while (!prime.IsProbablyPrime(100, random))
            {
                prime = (prime + pi) & intmask;
            }

            return prime;
        }