Пример #1
0
        /// <summary>
        /// Generates a random large prime near the given bit size.
        /// </summary>
        /// <param name="generator"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        private static BigInteger GetRandomLargePrime(IBasylKeyGenerator generator, int size)
        {
            //fills an array with random bytes. This is used for the prime search.
            byte[] vals = new byte[(int)Math.Ceiling(size / 8.0f)];

            lock (generator)
            {
                for (int i = 0; i < 20; i++)
                {
                    generator.FillBytes(vals);
                }

                for (int k = 0; k < 2; k++)
                    for (int i = 0; i < vals.Length; i++)
                    {
                        for (int n = 0; n < 3; n++)
                            generator.GetRandomByte();
                        generator.EncryptByte(ref vals[i]);
                    }
            }

            //searches for the prime number, decreases until it finds one that tests to be prime.
            BigInteger gco = new BigInteger(vals);
            if(gco < 0)
            {
                gco *= -1;
            }

            if (gco.IsEven)
            {
                gco -= 1;
            }

            var bouncyCastleBig = gco.Convert();
            var amt = new BigInteger(2).Convert();

            while (!bouncyCastleBig.IsProbablePrime(1))
            {
                bouncyCastleBig = bouncyCastleBig.Subtract(amt);
                gco -= 2;
            }
            //Bouncy castles isProbablePrime method is severely optimized compared to a naive approach.

            return gco;
        }