コード例 #1
0
        private static BigInteger GenerateRandomPrime()
        {
            var primeBigInteger = BigIntegerRandom.GenerateRandomByLength(keyLength);

            while (!MillerRabinTest.IsPrime(primeBigInteger, 10))
            {
                primeBigInteger++;
            }

            return(primeBigInteger);
        }
コード例 #2
0
        private static BigInteger FindE(BigInteger phi)
        {
            int[] staticE = new int[] { 3, 17, 65537 };

            foreach (var e in staticE)
            {
                if (ExtendedEuclid(phi, e).d == 1)
                {
                    return(e);
                }
            }

            BigInteger generatedE = BigIntegerRandom.Generate(phi);

            for (; ; generatedE++)
            {
                if (ExtendedEuclid(phi, generatedE).d == 1)
                {
                    return(generatedE);
                }
            }
        }
コード例 #3
0
        public static bool IsPrime(BigInteger n, BigInteger k)
        {
            if (n <= 1)
            {
                return(false);
            }

            if (n <= 3)
            {
                return(true);
            }

            if (n % 2 == 0)
            {
                return(false);
            }

            BigInteger s = BigInteger.One;
            BigInteger t = (n - 1) / two;

            while (t % 2 == BigInteger.Zero)
            {
                t = BigInteger.Divide(t, two);
                s++;
            }

            for (BigInteger i = BigInteger.Zero; i < k; i++)
            {
                BigInteger a = BigInteger.Add(two, BigIntegerRandom.Generate(n - 4));
                var        u = BigInteger.ModPow(a, t, n);

                if (u == 1 || u == n - 1)
                {
                    continue;
                }

                var  j          = BigInteger.Zero;
                bool isNotPrime = false;

                while (j < s)
                {
                    u = BigInteger.ModPow(u, two, n);
                    j++;

                    if (u.IsOne)
                    {
                        return(false);
                    }

                    if (u == n - 1)
                    {
                        isNotPrime = true;
                        break;
                    }
                }

                if (isNotPrime)
                {
                    continue;
                }

                return(false);
            }
            return(true);
        }