当前位置: 首页>>代码示例>>C#>>正文


C# BigInteger.genRandomBits方法代码示例

本文整理汇总了C#中BigInteger.genRandomBits方法的典型用法代码示例。如果您正苦于以下问题:C# BigInteger.genRandomBits方法的具体用法?C# BigInteger.genRandomBits怎么用?C# BigInteger.genRandomBits使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BigInteger的用法示例。


在下文中一共展示了BigInteger.genRandomBits方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ModSqrt

 //функция вычисления квадратоного корня по модулю простого числа q
 public BigInteger ModSqrt(BigInteger a, BigInteger q)
 {
     BigInteger b = new BigInteger();
     do
     {
         b.genRandomBits(255, new Random());
     } while (Legendre(b, q) == 1);
     BigInteger s = 0;
     BigInteger t = q - 1;
     while ((t & 1) != 1)
     {
         s++;
         t = t >> 1;
     }
     BigInteger InvA = a.modInverse(q);
     BigInteger c = b.modPow(t, q);
     BigInteger r = a.modPow(((t + 1) / 2), q);
     BigInteger d = new BigInteger();
     for (int i = 1; i < s; i++)
     {
         BigInteger temp = 2;
         temp = temp.modPow((s - i - 1), q);
         d = (r.modPow(2, q) * InvA).modPow(temp, q);
         if (d == (q - 1))
             r = (r * c) % q;
         c = c.modPow(2, q);
     }
     return r;
 }
开发者ID:msCube,项目名称:Scrambler,代码行数:30,代码来源:DSGost.cs

示例2: GenPrivateKey

 //Генерируем секретный ключ заданной длины
 public BigInteger GenPrivateKey(int BitSize)
 {
     BigInteger d = new BigInteger();
     do
     {
         d.genRandomBits(BitSize, new Random());
     } while ((d < 0) || (d > n));
     return d;
 }
开发者ID:msCube,项目名称:Scrambler,代码行数:10,代码来源:DSGost.cs

示例3: rand

        public bignum rand( Random randg )
        {
            BigInteger b = this.value;
               int numBits = b.bitCount();
               BigInteger x = new BigInteger();
               x.genRandomBits( numBits, randg );

               if (x > b)
              return new bignum(x % b);
               else
              return new bignum(x);
        }
开发者ID:mbrock,项目名称:bigloo-llvm,代码行数:12,代码来源:bignum.cs

示例4: GenerateNew

        public static DSAKeyPair GenerateNew(int bits, Rng random) {
            BigInteger one = new BigInteger(1);
            BigInteger[] pq = findRandomStrongPrime((uint)bits, 160, random);
            BigInteger p = pq[0], q = pq[1];
            BigInteger g = findRandomGenerator(q, p, random);

            BigInteger x;
            do {
                x = new BigInteger();
                x.genRandomBits(q.bitCount(), random);
            } while ((x < one) || (x > q));

            BigInteger y = g.modPow(x, p);

            return new DSAKeyPair(p, g, q, y, x);
        }
开发者ID:PavelTorgashov,项目名称:nfx,代码行数:16,代码来源:DSA.cs

示例5: findRandomStrongPrime

        private static BigInteger[] findRandomStrongPrime(uint primeBits, int orderBits,	Random 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 };
        }
开发者ID:rfyiamcool,项目名称:solrex,代码行数:80,代码来源:DSA.cs

示例6: findRandomGenerator

        private static BigInteger findRandomGenerator(BigInteger order, BigInteger modulo, Random random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger aux = modulo - new BigInteger(1);
            BigInteger t   = aux % order;
            BigInteger generator;

            if(t.LongValue() != 0) {
                return null;
            }

            t = aux / order;

            while(true) {
                generator = new BigInteger();
                generator.genRandomBits(modulo.bitCount(), random);
                generator = generator % modulo;
                generator = generator.modPow(t, modulo);
                if(generator!=one)
                    break;
            }

            aux = generator.modPow(order, modulo);

            if(aux!=one) {
                return null;
            }

            return generator;
        }
开发者ID:rfyiamcool,项目名称:solrex,代码行数:30,代码来源:DSA.cs

示例7: ShareData

    // secret shares an input based on n,r parameters
    public SharedData[] ShareData( long secret)
    {
        BigInteger[] coefficients = new BigInteger[numNecessaryParts - 1];
        BigInteger[] toReturn_p = new BigInteger[numAllParts];

        for (int i = 0; i < numNecessaryParts - 1; i++)
        {
            BigInteger a = new BigInteger();
            a.genRandomBits(64, new Random());
            a = a.abs() % modP;
            coefficients[i] = a;

        }

        for (long i = 0; i < numAllParts; i++)
        {
            toReturn_p[i] = 0;

            for (long j = 0; j < numNecessaryParts - 1; j++)
            {

                BigInteger tmp = new BigInteger((long)(Math.Pow(i + 1, j + 1)));

                toReturn_p[i] = (toReturn_p[i] + (BigInteger)(coefficients[j] * tmp)) % modP;
            }

        }

        SharedData[] toReturn = new SharedData[numAllParts];

        for (int i = 0; i < numAllParts; i++)
        {
            toReturn_p[i] = (toReturn_p[i] + new BigInteger(secret)) % modP;
            toReturn[i].yi = toReturn_p[i].LongValue();
            toReturn[i].xi = i + 1;
        }

        return toReturn;
    }
开发者ID:mertcetin,项目名称:P2P-Backup,代码行数:40,代码来源:ShamirSS.cs

示例8: SignGen

 //подписываем сообщение
 public string SignGen(byte[] h, BigInteger d)
 {
     alpha = new BigInteger(h);
     e = alpha % n;
     if (e == 0)
         e = 1;
     k = new BigInteger();
     C = new ECPoint();
     r = new BigInteger();
     s = new BigInteger();
     do
     {
         do
         {
             k.genRandomBits(n.bitCount(), new Random());
         } while ((k < 0) || (k > n));
         C = ECPoint.multiply(k, G);
         r = C.x % n;
         s = ((r * d) + (k * e)) % n;
     } while ((r == 0) || (s == 0));
     string Rvector = padding(r.ToHexString(), n.bitCount() / 4);
     string Svector = padding(s.ToHexString(), n.bitCount() / 4);
     return Rvector + Svector;
 }
开发者ID:BeRollOver,项目名称:Cryptology,代码行数:25,代码来源:GOST.cs

示例9: genCoPrime

        //***********************************************************************
        // Generates a random number with the specified number of bits such
        // that gcd(number, this) = 1
        //***********************************************************************

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

	        while(!done)
	        {
	                result.genRandomBits(bits, rand);
	                //Console.WriteLine(result.ToString(16));

		        // gcd test
		        BigInteger g = result.gcd(this);
			if(g.dataLength == 1 && g.data[0] == 1)
                                done = true;
	        }

	        return result;
        }
开发者ID:AudriusKniuras,项目名称:ChatClientServer,代码行数:23,代码来源:BigInteger.cs

示例10: SolovayStrassenTest

        //***********************************************************************
        // Probabilistic prime test based on Solovay-Strassen (Euler Criterion)
        //
        // p is probably prime if for any a < p (a is not multiple of p),
        // a^((p-1)/2) mod p = J(a, p)
        //
        // where J is the Jacobi symbol.
        //
        // Otherwise, p is composite.
        //
        // Returns
        // -------
        // True if "this" is a Euler pseudoprime to randomly chosen
        // bases.  The number of chosen bases is given by the "confidence"
        // parameter.
        //
        // False if "this" is definitely NOT prime.
        //
        //***********************************************************************

        public bool SolovayStrassenTest(int confidence)
        {
                BigInteger thisVal;
                if((this.data[maxLength-1] & 0x80000000) != 0)        // negative
                        thisVal = -this;
                else
                        thisVal = this;

                if(thisVal.dataLength == 1)
                {
                        // test small numbers
                        if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
                                return false;
                        else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
                                return true;
                }

                if((thisVal.data[0] & 0x1) == 0)     // even numbers
                        return false;


	        int bits = thisVal.bitCount();
	        BigInteger a = new BigInteger();
	        BigInteger p_sub1 = thisVal - 1;
	        BigInteger p_sub1_shift = p_sub1 >> 1;

	        Random rand = new Random();

	        for(int round = 0; round < confidence; round++)
	        {
		        bool done = false;

		        while(!done)		// generate a < n
		        {
			        int testBits = 0;

			        // make sure "a" has at least 2 bits
			        while(testBits < 2)
				        testBits = (int)(rand.NextDouble() * bits);

			        a.genRandomBits(testBits, rand);

			        int byteLen = a.dataLength;

                                // make sure "a" is not 0
			        if(byteLen > 1 || (byteLen == 1 && a.data[0] != 1))
				        done = true;
		        }

                        // check whether a factor exists (fix for version 1.03)
		        BigInteger gcdTest = a.gcd(thisVal);
                        if(gcdTest.dataLength == 1 && gcdTest.data[0] != 1)
                                return false;

		        // calculate a^((p-1)/2) mod p

		        BigInteger expResult = a.modPow(p_sub1_shift, thisVal);
		        if(expResult == p_sub1)
		                expResult = -1;

                        // calculate Jacobi symbol
                        BigInteger jacob = Jacobi(a, thisVal);

                        //Console.WriteLine("a = " + a.ToString(10) + " b = " + thisVal.ToString(10));
                        //Console.WriteLine("expResult = " + expResult.ToString(10) + " Jacob = " + jacob.ToString(10));

                        // if they are different then it is not prime
                        if(expResult != jacob)
			        return false;
	        }

	        return true;
        }
开发者ID:AudriusKniuras,项目名称:ChatClientServer,代码行数:93,代码来源:BigInteger.cs

示例11: Random

 public static BigInteger Random(int BitCount)
 {
 	Random rand = new Random(Environment.TickCount);
 	BigInteger b = new BigInteger();
 	b.genRandomBits(BitCount, rand);
 	return b;
 }
开发者ID:remixod,项目名称:NetLibClient,代码行数:7,代码来源:BigInteger.cs

示例12: genDS

        //формирование цифровой подписи.
        public string genDS(byte[] h, BigInteger d)
        {
            BigInteger a = new BigInteger(h);
            BigInteger e = a % n;
            if (e == 0)
                e = 1;
            BigInteger k = new BigInteger();
            CECPoint C=new CECPoint();
            BigInteger r=new BigInteger();
            BigInteger s = new BigInteger();
            do
            {
                do
                {
                    k.genRandomBits(n.bitCount(), new Random());
                } 
                while ((k < 0) || (k > n));

                C = CECPoint.multiply(G, k);
                r = C.x % n;
                s = ((r * d) + (k * e)) % n;
            } 
            while ((r == 0)||(s==0));

            string Rvector = padding(r.ToHexString(), n.bitCount() / 4);
            string Svector = padding(s.ToHexString(), n.bitCount() / 4);
            return Rvector + Svector;
        }
开发者ID:oxaoo,项目名称:GOST_34.10-2012,代码行数:29,代码来源:CDS.cs

示例13: GenerateRSAKey

    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;
        }
    }
开发者ID:sagar1589,项目名称:Delta.Cryptography,代码行数:51,代码来源:BigInteger.cs

示例14: FermatLittleTest

        //***********************************************************************
        // Probabilistic prime test based on Fermat's little theorem
        //
        // for any a < p (p does not divide a) if
        //      a^(p-1) mod p != 1 then p is not prime.
        //
        // Otherwise, p is probably prime (pseudoprime to the chosen base).
        //
        // Returns
        // -------
        // True if "this" is a pseudoprime to randomly chosen
        // bases.  The number of chosen bases is given by the "confidence"
        // parameter.
        //
        // False if "this" is definitely NOT prime.
        //
        // Note - this method is fast but fails for Carmichael numbers except
        // when the randomly chosen base is a factor of the number.
        //
        //***********************************************************************

        public bool FermatLittleTest(int confidence)
        {
                BigInteger thisVal;
                if((this.data[maxLength-1] & 0x80000000) != 0)        // negative
                        thisVal = -this;
                else
                        thisVal = this;

                if(thisVal.dataLength == 1)
                {
                        // test small numbers
                        if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
                                return false;
                        else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
                                return true;
                }

                if((thisVal.data[0] & 0x1) == 0)     // even numbers
                        return false;

	        int bits = thisVal.bitCount();
	        BigInteger a = new BigInteger();
	        BigInteger p_sub1 = thisVal - (new BigInteger(1));
	        Random rand = new Random();

	        for(int round = 0; round < confidence; round++)
	        {
		        bool done = false;

		        while(!done)		// generate a < n
		        {
			        int testBits = 0;

			        // make sure "a" has at least 2 bits
			        while(testBits < 2)
				        testBits = (int)(rand.NextDouble() * bits);

			        a.genRandomBits(testBits, rand);

			        int byteLen = a.dataLength;

                                // make sure "a" is not 0
			        if(byteLen > 1 || (byteLen == 1 && a.data[0] != 1))
                                        done = true;
		        }

                        // check whether a factor exists (fix for version 1.03)
		        BigInteger gcdTest = a.gcd(thisVal);
                        if(gcdTest.dataLength == 1 && gcdTest.data[0] != 1)
                                return false;

		        // calculate a^(p-1) mod p
		        BigInteger expResult = a.modPow(p_sub1, thisVal);

		        int resultLen = expResult.dataLength;

                        // is NOT prime is a^(p-1) mod p != 1

		        if(resultLen > 1 || (resultLen == 1 && expResult.data[0] != 1))
		        {
		                //Console.WriteLine("a = " + a.ToString());
			        return false;
                        }
	        }

	        return true;
        }
开发者ID:AudriusKniuras,项目名称:ChatClientServer,代码行数:88,代码来源:BigInteger.cs

示例15: EncodeMessage

            /// <summary>
            /// Adds padding to the input data and returns the padded data.
            /// </summary>
            /// <param name="dataBytes">Data to be padded prior to encryption</param>
            /// <param name="parameters">RSA Parameters used for padding computation</param>
            /// <returns>Padded message</returns>
            public byte[] EncodeMessage( byte[] dataBytes, RSAParameters parameters )
            {
                //Iterator
                int i = 0;

                //Get the size of the data to be encrypted
                m_mLen = dataBytes.Length;

                //Get the size of the public modulus (will serve as max length for cipher text)
                m_k = parameters.N.Length;

                if( m_mLen > GetMaxMessageLength( parameters ) ) {
                    throw new Exception( "Bad Data." );
                }

                //Generate the random octet seed (same length as hash)
                BigInteger biSeed = new BigInteger();
                biSeed.genRandomBits( m_hLen * 8, new Random() );
                byte[] bytSeed = biSeed.getBytesRaw();

                //Make sure all of the bytes are greater than 0.
                for( i = 0; i <= bytSeed.Length - 1; i++ ) {
                    if( bytSeed[i] == 0x00 ) {
                        //Replacing with the prime byte 17, no real reason...just picked at random.
                        bytSeed[i] = 0x17;
                    }
                }

                //Mask the seed with MFG Function(SHA1 Hash)
                //This is the mask to be XOR'd with the DataBlock below.
                byte[] dbMask = CryptoMathematics.OAEPMGF( bytSeed, m_k - m_hLen - 1, m_hLen, m_hashProvider );

                //Compute the length needed for PS (zero padding) and
                //fill a byte array to the computed length
                int psLen = GetMaxMessageLength( parameters ) - m_mLen;

                //Generate the SHA1 hash of an empty L (Label).  Label is not used for this
                //application of padding in the RSA specification.
                byte[] lHash = m_hashProvider.ComputeHash( System.Text.Encoding.UTF8.GetBytes( string.Empty.ToCharArray() ) );

                //Create a dataBlock which will later be masked.  The
                //data block includes the concatenated hash(L), PS,
                //a 0x01 byte, and the message.
                int dbLen = m_hLen + psLen + 1 + m_mLen;
                byte[] dataBlock = new byte[dbLen];

                int cPos = 0;
                //Current position

                //Add the L Hash to the data blcok
                for( i = 0; i <= lHash.Length - 1; i++ ) {
                    dataBlock[cPos] = lHash[i];
                    cPos += 1;
                }

                //Add the zero padding
                for( i = 0; i <= psLen - 1; i++ ) {
                    dataBlock[cPos] = 0x00;
                    cPos += 1;
                }

                //Add the 0x01 byte
                dataBlock[cPos] = 0x01;
                cPos += 1;

                //Add the message
                for( i = 0; i <= dataBytes.Length - 1; i++ ) {
                    dataBlock[cPos] = dataBytes[i];
                    cPos += 1;
                }

                //Create the masked data block.
                byte[] maskedDB = CryptoMathematics.BitwiseXOR( dbMask, dataBlock );

                //Create the seed mask
                byte[] seedMask = CryptoMathematics.OAEPMGF( maskedDB, m_hLen, m_hLen, m_hashProvider );

                //Create the masked seed
                byte[] maskedSeed = CryptoMathematics.BitwiseXOR( bytSeed, seedMask );

                //Create the resulting cipher - starting with a 0 byte.
                byte[] result = new byte[parameters.N.Length];
                result[0] = 0x00;

                //Add the masked seed
                maskedSeed.CopyTo( result, 1 );

                //Add the masked data block
                maskedDB.CopyTo( result, maskedSeed.Length + 1 );

                return result;
            }
开发者ID:chaoscode,项目名称:SteamSharp,代码行数:98,代码来源:PaddingProviders.cs


注:本文中的BigInteger.genRandomBits方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。