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


C# BigInteger.ModPow方法代码示例

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


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

示例1: GenerateParameters

        /**
         * which Generates the p and g values from the given parameters,
         * returning the DHParameters object.
         * <p>
         * Note: can take a while...</p>
         */
        public virtual DHParameters GenerateParameters()
        {
            //
            // find a safe prime p where p = 2*q + 1, where p and q are prime.
            //
            BigInteger[] safePrimes = DHParametersHelper.GenerateSafePrimes(size, certainty, random);

            BigInteger p = safePrimes[0];
            BigInteger q = safePrimes[1];

            BigInteger g;
            int qLength = size - 1;

            //
            // calculate the generator g - the advantage of using the 2q+1
            // approach is that we know the prime factorisation of (p - 1)...
            //
            do
            {
                g = new BigInteger(qLength, random);
            }
            while (g.ModPow(BigInteger.Two, p).Equals(BigInteger.One)
                || g.ModPow(q, p).Equals(BigInteger.One));

            return new DHParameters(p, g, q, 2);
        }
开发者ID:hjgode,项目名称:iTextSharpCF,代码行数:32,代码来源:DHParametersGenerator.cs

示例2: JPakePrimeOrderGroup

        /// <summary>
        /// Constructor used by the pre-approved groups in JPakePrimeOrderGroups.
        /// These pre-approved groups can avoid the expensive checks.
        /// User-specified groups should not use this constructor.
        /// </summary>
        public JPakePrimeOrderGroup(BigInteger p, BigInteger q, BigInteger g, bool skipChecks)
        {
            JPakeUtilities.ValidateNotNull(p, "p");
            JPakeUtilities.ValidateNotNull(q, "q");
            JPakeUtilities.ValidateNotNull(g, "g");

            if (!skipChecks)
            {
                if (!p.Subtract(JPakeUtilities.One).Mod(q).Equals(JPakeUtilities.Zero))
                    throw new ArgumentException("p-1 must be evenly divisible by q");
                if (g.CompareTo(BigInteger.Two) == -1 || g.CompareTo(p.Subtract(JPakeUtilities.One)) == 1)
                    throw new ArgumentException("g must be in [2, p-1]");
                if (!g.ModPow(q, p).Equals(JPakeUtilities.One))
                    throw new ArgumentException("g^q mod p must equal 1");

                // Note these checks do not guarantee that p and q are prime.
                // We just have reasonable certainty that they are prime.
                if (!p.IsProbablePrime(20))
                    throw new ArgumentException("p must be prime");
                if (!q.IsProbablePrime(20))
                    throw new ArgumentException("q must be prime");
            }

            this.p = p;
            this.q = q;
            this.g = g;
        }
开发者ID:KimikoMuffin,项目名称:bc-csharp,代码行数:32,代码来源:JPakePrimeOrderGroup.cs

示例3: CalculatePublic

        internal BigInteger CalculatePublic(
			BigInteger	p,
			BigInteger	g,
			BigInteger	x)
        {
            return g.ModPow(x, p);
        }
开发者ID:hjgode,项目名称:iTextSharpCF,代码行数:7,代码来源:DHKeyGeneratorHelper.cs

示例4: CalculateAgreement

        /**
         * given a message from a given party and the corresponding public key
         * calculate the next message in the agreement sequence. In this case
         * this will represent the shared secret.
         */
        public BigInteger CalculateAgreement(
			DHPublicKeyParameters	pub,
			BigInteger				message)
        {
            if (pub == null)
                throw new ArgumentNullException("pub");
            if (message == null)
                throw new ArgumentNullException("message");

            if (!pub.Parameters.Equals(dhParams))
            {
                throw new ArgumentException("Diffie-Hellman public key has wrong parameters.");
            }

            return message.ModPow(key.X, dhParams.P).Multiply(pub.Y.ModPow(privateValue, dhParams.P)).Mod(dhParams.P);
        }
开发者ID:hjgode,项目名称:iTextSharpCF,代码行数:21,代码来源:DHAgreement.cs

示例5: Miller

        /// <summary>
        /// millerov agoritam
        /// </summary>
        /// <param name="a">točka</param>
        /// <param name="b">točka</param>
        /// <param name="m">red grupe</param>
        /// <param name="p">red polja, prim</param>
        /// <returns></returns>
        private static BigInteger Miller(FpPoint P, FpPoint Q, BigInteger m, BigInteger prim)
        {
            // Millerov algoritam

            string mBin = m.ToString(2);

            BigInteger t1 = new BigInteger("1", 10);
            BigInteger t2 = new BigInteger("1", 10);
            FpPoint V = P;

            for (int i = 0; i < m.BitLength; i++)
            {
                V = (FpPoint)V.Twice();
                t1 = t1.ModPow(new BigInteger("2", 10), prim).Multiply(MLF(V, V, Q));
                if (mBin[i] == '1')
                {
                    t1 = t1.Multiply(MLF(V, P, Q));
                    V = (FpPoint)V.Add(P);
                }
            }
            return t1;
        }
开发者ID:excrucio,项目名称:ibe,代码行数:30,代码来源:GeneralFunctions.cs

示例6: TestModPow

		public void TestModPow()
		{
			try
			{
				two.ModPow(one, zero);
				Assert.Fail("expected ArithmeticException");
			}
			catch (ArithmeticException) {}

			Assert.AreEqual(zero, zero.ModPow(zero, one));
			Assert.AreEqual(one, zero.ModPow(zero, two));
			Assert.AreEqual(zero, two.ModPow(one, one));
			Assert.AreEqual(one, two.ModPow(zero, two));

			for (int i = 0; i < 10; ++i)
			{
				BigInteger m = BigInteger.ProbablePrime(10 + i * 3, random);
				BigInteger x = new BigInteger(m.BitLength - 1, random);

				Assert.AreEqual(x, x.ModPow(m, m));
				if (x.SignValue != 0)
				{
					Assert.AreEqual(zero, zero.ModPow(x, m));
					Assert.AreEqual(one, x.ModPow(m.Subtract(one), m));
				}

				BigInteger y = new BigInteger(m.BitLength - 1, random);
				BigInteger n = new BigInteger(m.BitLength - 1, random);
				BigInteger n3 = n.ModPow(three, m);

				BigInteger resX = n.ModPow(x, m);
				BigInteger resY = n.ModPow(y, m);
				BigInteger res = resX.Multiply(resY).Mod(m);
				BigInteger res3 = res.ModPow(three, m);

				Assert.AreEqual(res3, n3.ModPow(x.Add(y), m));

				BigInteger a = x.Add(one); // Make sure it's not zero
				BigInteger b = y.Add(one); // Make sure it's not zero

				Assert.AreEqual(a.ModPow(b, m).ModInverse(m), a.ModPow(b.Negate(), m));
			}
		}
开发者ID:randombit,项目名称:hacrypto,代码行数:43,代码来源:BigIntegerTest.cs

示例7: ProcessBlock

		/**
		* Process a single block using the basic ElGamal algorithm.
		*
		* @param in the input array.
		* @param inOff the offset into the input buffer where the data starts.
		* @param length the length of the data to be processed.
		* @return the result of the ElGamal process.
		* @exception DataLengthException the input block is too large.
		*/
        public virtual byte[] ProcessBlock(
			byte[]	input,
			int		inOff,
			int		length)
		{
			if (key == null)
				throw new InvalidOperationException("ElGamal engine not initialised");

			int maxLength = forEncryption
				?	(bitSize - 1 + 7) / 8
				:	GetInputBlockSize();

			if (length > maxLength)
				throw new DataLengthException("input too large for ElGamal cipher.\n");

			BigInteger p = key.Parameters.P;

			byte[] output;
			if (key is ElGamalPrivateKeyParameters) // decryption
			{
				int halfLength = length / 2;
				BigInteger gamma = new BigInteger(1, input, inOff, halfLength);
				BigInteger phi = new BigInteger(1, input, inOff + halfLength, halfLength);

				ElGamalPrivateKeyParameters priv = (ElGamalPrivateKeyParameters) key;

				// a shortcut, which generally relies on p being prime amongst other things.
				// if a problem with this shows up, check the p and g values!
				BigInteger m = gamma.ModPow(p.Subtract(BigInteger.One).Subtract(priv.X), p).Multiply(phi).Mod(p);

				output = m.ToByteArrayUnsigned();
			}
			else // encryption
			{
				BigInteger tmp = new BigInteger(1, input, inOff, length);

				if (tmp.BitLength >= p.BitLength)
					throw new DataLengthException("input too large for ElGamal cipher.\n");


				ElGamalPublicKeyParameters pub = (ElGamalPublicKeyParameters) key;

				BigInteger pSub2 = p.Subtract(BigInteger.Two);

				// TODO In theory, a series of 'k', 'g.ModPow(k, p)' and 'y.ModPow(k, p)' can be pre-calculated
				BigInteger k;
				do
				{
					k = new BigInteger(p.BitLength, random);
				}
				while (k.SignValue == 0 || k.CompareTo(pSub2) > 0);

				BigInteger g = key.Parameters.G;
				BigInteger gamma = g.ModPow(k, p);
				BigInteger phi = tmp.Multiply(pub.Y.ModPow(k, p)).Mod(p);

				output = new byte[this.GetOutputBlockSize()];

				// TODO Add methods to allow writing BigInteger to existing byte array?
				byte[] out1 = gamma.ToByteArrayUnsigned();
				byte[] out2 = phi.ToByteArrayUnsigned();
				out1.CopyTo(output, output.Length / 2 - out1.Length);
				out2.CopyTo(output, output.Length - out2.Length);
			}

			return output;
		}
开发者ID:ALange,项目名称:OutlookPrivacyPlugin,代码行数:76,代码来源:ElGamalEngine.cs

示例8: processHandshake


//.........这里部分代码省略.........
                                        MemoryStream signedData = new MemoryStream();
                                        TlsUtilities.WriteUint16(pLength, signedData);
                                        signedData.Write(pByte, 0, pByte.Length);
                                        TlsUtilities.WriteUint16(gLength, signedData);
                                        signedData.Write(gByte, 0, gByte.Length);
                                        TlsUtilities.WriteUint16(YsLength, signedData);
                                        signedData.Write(YsByte, 0, YsByte.Length);
                                        byte[] signed = signedData.ToArray();

                                        sigDigest.BlockUpdate(this.clientRandom, 0, this.clientRandom.Length);
                                        sigDigest.BlockUpdate(this.serverRandom, 0, this.serverRandom.Length);
                                        sigDigest.BlockUpdate(signed, 0, signed.Length);
                                        byte[] hash = new byte[sigDigest.GetDigestSize()];
                                        sigDigest.DoFinal(hash, 0);

                                        /*
                                        * Now, do the RSA operation
                                        */
                                        RsaBlindedEngine rsa = new RsaBlindedEngine();
                                        Pkcs1Encoding encoding = new Pkcs1Encoding(rsa);
                                        encoding.Init(false, this.serverRsaKey);

                                        /*
                                        * The data which was signed
                                        */
                                        byte[] sigHash = null;

                                        try
                                        {
                                            sigHash = encoding.ProcessBlock(sigByte, 0, sigByte.Length);
                                        }
                                        catch (InvalidCipherTextException)
                                        {
                                            this.FailWithError(AL_fatal, AP_bad_certificate);
                                        }

                                        /*
                                        * Check if the data which was signed is equal to
                                        * the hash we calculated.
                                        */
                                        if (sigHash.Length != hash.Length)
                                        {
                                            this.FailWithError(AL_fatal, AP_bad_certificate);
                                        }

                                        for (int i = 0; i < sigHash.Length; i++)
                                        {
                                            if (sigHash[i] != hash[i])
                                            {
                                                this.FailWithError(AL_fatal, AP_bad_certificate);
                                            }
                                        }

                                        /*
                                        * OK, Signature was correct.
                                        *
                                        * Do the DH calculation.
                                        */
                                        BigInteger p = new BigInteger(1, pByte);
                                        BigInteger g = new BigInteger(1, gByte);
                                        BigInteger Ys = new BigInteger(1, YsByte);
                                        BigInteger x = new BigInteger(p.BitLength - 1, this.random);
                                        Yc = g.ModPow(x, p);
                                        this.pms = (Ys.ModPow(x, p)).ToByteArray();

                                        /*
                                        * Remove leading zero byte, if present.
                                        */
                                        if (this.pms[0] == 0)
                                        {
                                            byte[] tmp = new byte[this.pms.Length - 1];
                                            Array.Copy(this.pms, 1, tmp, 0, tmp.Length);
                                            this.pms = tmp;
                                        }

                                        this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
                                        read = true;
                                        break;
                                    default:
                                        this.FailWithError(AL_fatal, AP_unexpected_message);
                                        break;
                                }
                                break;
                            case HP_HELLO_REQUEST:
                            case HP_CLIENT_KEY_EXCHANGE:
                            case HP_CERTIFICATE_REQUEST:
                            case HP_CERTIFICATE_VERIFY:
                            case HP_CLIENT_HELLO:
                            default:
                                // We do not support this!
                                this.FailWithError(AL_fatal, AP_unexpected_message);
                                break;

                        }

                    }
                }
            }
            while (read);
        }
开发者ID:hjgode,项目名称:iTextSharpCF,代码行数:101,代码来源:TlsProtocolHandler.cs

示例9: CalculateZeroKnowledgeProof

        /// <summary>
        /// Calculate a zero knowledge proof of x using Schnorr's signature.
        /// The returned array has two elements {g^v, r = v-x*h} for x.
        /// </summary>
        public static BigInteger[] CalculateZeroKnowledgeProof(BigInteger p, BigInteger q, BigInteger g,
            BigInteger gx, BigInteger x, string participantId, IDigest digest, SecureRandom random)
        {
            /* Generate a random v, and compute g^v */
            BigInteger vMin = Zero;
            BigInteger vMax = q.Subtract(One);
            BigInteger v = BigIntegers.CreateRandomInRange(vMin, vMax, random);

            BigInteger gv = g.ModPow(v, p);
            BigInteger h = CalculateHashForZeroKnowledgeProof(g, gv, gx, participantId, digest); // h

            return new BigInteger[]
            {
                gv,
                v.Subtract(x.Multiply(h)).Mod(q) // r = v-x*h
            };
        }
开发者ID:KimikoMuffin,项目名称:bc-csharp,代码行数:21,代码来源:JPakeUtilities.cs

示例10: BlindObject

        // --- m => b
        public BigInteger BlindObject(byte[] message, BigInteger r)
        {
            BigInteger m = new BigInteger(message);
            BigInteger b = (r.ModPow(e, n).Multiply(m)).Mod(n);

            //Console.WriteLine("m: {0}\nr: {1}\ne: {2}\nn: {3}\nb: {4}", m, r, e, n, b);
            return b;
        }
开发者ID:Ziachu,项目名称:cyfrowe_banknoty_csharp,代码行数:9,代码来源:RSA.cs

示例11: RabinMillerTest

		internal bool RabinMillerTest(
			int		certainty,
			Random	random)
		{
			Debug.Assert(certainty > 0);
			Debug.Assert(BitLength > 2);
			Debug.Assert(TestBit(0));

			// let n = 1 + d . 2^s
			BigInteger n = this;
			BigInteger nMinusOne = n.Subtract(One);
			int s = nMinusOne.GetLowestSetBit();
			BigInteger r = nMinusOne.ShiftRight(s);

			Debug.Assert(s >= 1);

			do
			{
				// TODO Make a method for random BigIntegers in range 0 < x < n)
				// - Method can be optimized by only replacing examined bits at each trial
				BigInteger a;
				do
				{
					a = new BigInteger(n.BitLength, random);
				}
				while (a.CompareTo(One) <= 0 || a.CompareTo(nMinusOne) >= 0);

				BigInteger y = a.ModPow(r, n);

				if (!y.Equals(One))
				{
					int j = 0;
					while (!y.Equals(nMinusOne))
					{
						if (++j == s)
							return false;

						y = y.ModPow(Two, n);

						if (y.Equals(One))
							return false;
					}
				}

				certainty -= 2; // composites pass for only 1/4 possible 'a'
			}
			while (certainty > 0);

			return true;
		}
开发者ID:VimalKumarS,项目名称:mono-tls,代码行数:50,代码来源:BigInteger.cs

示例12: ProcessBlock

		/**
		* Process a single Block using the Naccache-Stern algorithm.
		*
		* @see org.bouncycastle.crypto.AsymmetricBlockCipher#ProcessBlock(byte[],
		*      int, int)
		*/
		public byte[] ProcessBlock(
			byte[]	inBytes,
			int		inOff,
			int		length)
		{
			if (key == null)
				throw new InvalidOperationException("NaccacheStern engine not initialised");
			if (length > (GetInputBlockSize() + 1))
				throw new DataLengthException("input too large for Naccache-Stern cipher.\n");

			if (!forEncryption)
			{
				// At decryption make sure that we receive padded data blocks
				if (length < GetInputBlockSize())
				{
					throw new InvalidCipherTextException("BlockLength does not match modulus for Naccache-Stern cipher.\n");
				}
			}

			// transform input into BigInteger
			BigInteger input = new BigInteger(1, inBytes, inOff, length);

			if (debug)
			{
				System.Diagnostics.Debug.WriteLine("input as BigInteger: " + input);
			}

			byte[] output;
			if (forEncryption)
			{
				output = Encrypt(input);
			}
			else
			{
				IList plain = Platform.CreateArrayList();
				NaccacheSternPrivateKeyParameters priv = (NaccacheSternPrivateKeyParameters)key;
				IList primes = priv.SmallPrimesList;
				// Get Chinese Remainders of CipherText
				for (int i = 0; i < primes.Count; i++)
				{
					BigInteger exp = input.ModPow(priv.PhiN.Divide((BigInteger)primes[i]), priv.Modulus);
					IList al = lookup[i];
					if (lookup[i].Count != ((BigInteger)primes[i]).IntValue)
					{
						if (debug)
						{
                            System.Diagnostics.Debug.WriteLine("Prime is " + primes[i] + ", lookup table has size " + al.Count);
						}
						throw new InvalidCipherTextException("Error in lookup Array for "
										+ ((BigInteger)primes[i]).IntValue
										+ ": Size mismatch. Expected ArrayList with length "
										+ ((BigInteger)primes[i]).IntValue + " but found ArrayList of length "
										+ lookup[i].Count);
					}
					int lookedup = al.IndexOf(exp);

					if (lookedup == -1)
					{
						if (debug)
						{
							System.Diagnostics.Debug.WriteLine("Actual prime is " + primes[i]);
							System.Diagnostics.Debug.WriteLine("Decrypted value is " + exp);

							System.Diagnostics.Debug.WriteLine("LookupList for " + primes[i] + " with size " + lookup[i].Count
											+ " is: ");
							for (int j = 0; j < lookup[i].Count; j++)
							{
								System.Diagnostics.Debug.WriteLine(lookup[i][j]);
							}
						}
						throw new InvalidCipherTextException("Lookup failed");
					}
					plain.Add(BigInteger.ValueOf(lookedup));
				}
				BigInteger test = chineseRemainder(plain, primes);

				// Should not be used as an oracle, so reencrypt output to see
				// if it corresponds to input

				// this breaks probabilisic encryption, so disable it. Anyway, we do
				// use the first n primes for key generation, so it is pretty easy
				// to guess them. But as stated in the paper, this is not a security
				// breach. So we can just work with the correct sigma.

				// if (debug) {
				//      System.Diagnostics.Debug.WriteLine("Decryption is " + test);
				// }
				// if ((key.G.ModPow(test, key.Modulus)).Equals(input)) {
				//      output = test.ToByteArray();
				// } else {
				//      if(debug){
				//          System.Diagnostics.Debug.WriteLine("Engine seems to be used as an oracle,
				//          returning null");
				//      }
//.........这里部分代码省略.........
开发者ID:roryshko,项目名称:BouncyCastle.Crypto,代码行数:101,代码来源:NaccacheSternEngine.cs

示例13: VerifySignature

        /**
         * return true if the value r and s represent a Gost3410 signature for
         * the passed in message for standard Gost3410 the message should be a
         * Gost3411 hash of the real message to be verified.
         */
        public bool VerifySignature(
			byte[]		message,
			BigInteger	r,
			BigInteger	s)
        {
            byte[] mRev = new byte[message.Length]; // conversion is little-endian
            for (int i = 0; i != mRev.Length; i++)
            {
                mRev[i] = message[mRev.Length - 1 - i];
            }

            BigInteger m = new BigInteger(1, mRev);
            Gost3410Parameters parameters = key.Parameters;

            if (r.SignValue < 0 || parameters.Q.CompareTo(r) <= 0)
            {
                return false;
            }

            if (s.SignValue < 0 || parameters.Q.CompareTo(s) <= 0)
            {
                return false;
            }

            BigInteger v = m.ModPow(parameters.Q.Subtract(BigInteger.Two), parameters.Q);

            BigInteger z1 = s.Multiply(v).Mod(parameters.Q);
            BigInteger z2 = (parameters.Q.Subtract(r)).Multiply(v).Mod(parameters.Q);

            z1 = parameters.A.ModPow(z1, parameters.P);
            z2 = ((Gost3410PublicKeyParameters)key).Y.ModPow(z2, parameters.P);

            BigInteger u = z1.Multiply(z2).Mod(parameters.P).Mod(parameters.Q);

            return u.Equals(r);
        }
开发者ID:hjgode,项目名称:iTextSharpCF,代码行数:41,代码来源:GOST3410Signer.cs

示例14: RabinMillerTest

        internal bool RabinMillerTest(
			int		certainty,
			Random	random)
        {
            Debug.Assert(certainty > 0);
            Debug.Assert(CompareTo(Two) > 0);
            Debug.Assert(TestBit(0));

            // let n = 1 + d . 2^s
            BigInteger n = this;
            int bitLengthOfN = n.BitLength;
            BigInteger nMinusOne = n.Subtract(One);
            int k = nMinusOne.GetLowestSetBit();
            BigInteger q = nMinusOne.ShiftRight(k);

            Debug.Assert(k >= 1);

            do
            {
                // TODO Make a method for random BigIntegers in range 0 < x < n)
                // - Method can be optimized by only replacing examined bits at each trial
                BigInteger x;
                do
                {
                    x = new BigInteger(bitLengthOfN, random);
                }
                // NB: Spec says 0 < x < n, but 1 is trivial
                while (x.CompareTo(One) <= 0 || x.CompareTo(n) >= 0);

                BigInteger y = x.ModPow(q, n);

                if (!y.Equals(One))
                {
                    // y already = x.ModPow(d << 0, n)
                    int r = 0;

                    while (!y.Equals(nMinusOne))
                    {
                        if (++r == k)
                            return false;

                        // y becomes x.ModPow(d << r, n)
                        y = y.ModPow(Two, n);

                        // TODO Confirm whether y.Equals(One) is worth testing here
                    }
                }

                certainty -= 2; // composites pass for only 1/4 possible 'x'
            }
            while (certainty > 0);

            return true;
        }
开发者ID:hjgode,项目名称:iTextSharpCF,代码行数:54,代码来源:BigInteger.cs

示例15: UnblindObject

        // --- b => m
        public byte[] UnblindObject(BigInteger y, BigInteger r)
        {
            //BigInteger m = (r.ModPow(e.ModInverse(n), n).Multiply(y)).Mod(n);
            //BigInteger m = (y.Multiply(r.ModPow(e, n))).Mod(n);

            BigInteger m = (y.Multiply(r.ModPow(e.Negate(), n))).Mod(n);

            //Console.WriteLine("m: {0}\nr: {1}\ne: {2}\nn: {3}\ny: {4}", m, r, e, n, y);
            return m.ToByteArray();
        }
开发者ID:Ziachu,项目名称:cyfrowe_banknoty_csharp,代码行数:11,代码来源:RSA.cs


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