Mod() public method

public Mod ( BigInteger m ) : BigInteger
m BigInteger
return BigInteger
        /// <summary>
        /// Constructor which attempts to redeem a completed set of three codes, and calculate the private key.
        /// </summary>
        public EscrowCodeSet(string code1, string code2, string code3)
        {
            if (code1 == null || code2 == null || code3 == null || code1 == "" || code2 == "" || code3 == "") {
                throw new ArgumentException("Three codes are required to use this function.");
            }

            string codea = null, codeb=null, codep = null;

            if (code1.StartsWith("einva")) codea = code1;
            if (code2.StartsWith("einva")) codea = code2;
            if (code3.StartsWith("einva")) codea = code3;
            if (code1.StartsWith("einvb")) codeb = code1;
            if (code2.StartsWith("einvb")) codeb = code2;
            if (code3.StartsWith("einvb")) codeb = code3;
            if (code1.StartsWith("einvp")) codep = code1;
            if (code2.StartsWith("einvp")) codep = code2;
            if (code3.StartsWith("einvp")) codep = code3;

            if (codea==null || codeb == null || codep == null) {
                throw new ArgumentException("In order to use this function, one code MUST be an Escrow Invitation A (starting " +
                    "with \"einva\"), one must be an Escrow Invitation B (starting with \"einvb\") and the last " +
                    "code MUST be a Payment Invitation (starting with \"einvp\").");
            }

            byte[] pubparta, privparta;
            int identifier30a;
            string failreason = parseEscrowCode(codea, out pubparta, out privparta, out identifier30a);
            if (failreason != null) throw new ArgumentException("Escrow Invitation Code A: " + failreason);

            byte[] pubpartb, privpartb;
            int identifier30b;
            failreason = parseEscrowCode(codeb, out pubpartb, out privpartb, out identifier30b);
            if (failreason != null) throw new ArgumentException("Escrow Invitation Code B: " + failreason);

            if (identifier30a != identifier30b) {
                throw new ArgumentException("The two Escrow Invitations are not mates and cannot unlock the private key.");
            }

            string notvalid = "Not a valid Payment Invitation Code";
            string notvalid2 = "Code is not a valid Payment Invitation Code or may have a typo or other error.";
            string notvalid3 = "The Payment Invitation does not belong to the provided Escrow Invitation.";

            long headp;
            byte[] invbytesp;
            string failReason = parseEitherCode(codep, notvalid, notvalid2, out invbytesp, out headp);

            if (headp < headbaseP) throw new ArgumentException(notvalid);
            long identifier30L = headp - headbaseP;
            if (identifier30L < 0 || identifier30L > 0x3FFFFFFFL) throw new ArgumentException(notvalid);

            if (identifier30L != (long)identifier30a) {
                throw new ArgumentException("The Payment Invitation was not generated from either of the provided Escrow Invitation codes and cannot be unlocked by them.");
            }

            byte[] privpartz = new byte[32];
            Array.Copy(invbytesp, 8 + 1 + 1, privpartz, 0, 32);
            byte networkByte = invbytesp[8];
            bool compressedFlag = (invbytesp[8 + 1 + 1 + 32 + 20] & 0x1) == 1;

            // get private key
            BigInteger xyz = new BigInteger(1, privparta).Multiply(new BigInteger(1, privpartb)).Multiply(new BigInteger(1, privpartz));
            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            xyz = xyz.Mod(ps.N);

            KeyPair kp = new KeyPair(xyz, compressedFlag, networkByte);

            // provide everything
            this.EscrowInvitationCodeA = codea;
            this.EscrowInvitationCodeB = codeb;
            this.PaymentInvitationCode = codep;
            this.BitcoinAddress = kp.AddressBase58;
            this.PrivateKey = kp.PrivateKey;
        }
        /// <summary>Choose a random prime value for use with RSA</summary>
        /// <param name="bitlength">the bit-length of the returned prime</param>
        /// <param name="e">the RSA public exponent</param>
        /// <returns>a prime p, with (p-1) relatively prime to e</returns>
        protected virtual BigInteger ChooseRandomPrime(int bitlength, BigInteger e)
        {
            for (;;)
            {
                BigInteger p = new BigInteger(bitlength, 1, param.Random);

                if (p.Mod(e).Equals(BigInteger.One))
                    continue;

                if (!p.IsProbablePrime(param.Certainty))
                    continue;

                if (!e.Gcd(p.Subtract(BigInteger.One)).Equals(BigInteger.One))
                    continue;

                return p;
            }
        }
Beispiel #3
1
		public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            BigInteger p, q, n, d, e, pSub1, qSub1, phi;

            //
            // p and q values should have a length of half the strength in bits
            //
			int strength = param.Strength;
            int pbitlength = (strength + 1) / 2;
            int qbitlength = (strength - pbitlength);
			int mindiffbits = strength / 3;

			e = param.PublicExponent;

			// TODO Consider generating safe primes for p, q (see DHParametersHelper.generateSafePrimes)
			// (then p-1 and q-1 will not consist of only small factors - see "Pollard's algorithm")

			//
            // Generate p, prime and (p-1) relatively prime to e
            //
            for (;;)
            {
				p = new BigInteger(pbitlength, 1, param.Random);

				if (p.Mod(e).Equals(BigInteger.One))
					continue;

				if (!p.IsProbablePrime(param.Certainty))
					continue;

				if (e.Gcd(p.Subtract(BigInteger.One)).Equals(BigInteger.One)) 
					break;
			}

            //
            // Generate a modulus of the required length
            //
            for (;;)
            {
                // Generate q, prime and (q-1) relatively prime to e,
                // and not equal to p
                //
                for (;;)
                {
					q = new BigInteger(qbitlength, 1, param.Random);

					if (q.Subtract(p).Abs().BitLength < mindiffbits)
						continue;

					if (q.Mod(e).Equals(BigInteger.One))
						continue;

					if (!q.IsProbablePrime(param.Certainty))
						continue;

					if (e.Gcd(q.Subtract(BigInteger.One)).Equals(BigInteger.One)) 
						break;
				}

                //
                // calculate the modulus
                //
                n = p.Multiply(q);

                if (n.BitLength == param.Strength)
					break;

                //
                // if we Get here our primes aren't big enough, make the largest
                // of the two p and try again
                //
                p = p.Max(q);
            }

			if (p.CompareTo(q) < 0)
			{
				phi = p;
				p = q;
				q = phi;
			}

            pSub1 = p.Subtract(BigInteger.One);
            qSub1 = q.Subtract(BigInteger.One);
            phi = pSub1.Multiply(qSub1);

            //
            // calculate the private exponent
            //
            d = e.ModInverse(phi);

            //
            // calculate the CRT factors
            //
            BigInteger dP, dQ, qInv;

            dP = d.Remainder(pSub1);
            dQ = d.Remainder(qSub1);
            qInv = q.ModInverse(p);

            return new AsymmetricCipherKeyPair(
                new RsaKeyParameters(false, n, e),
                new RsaPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
        }
Beispiel #4
0
        public static string ByteArrayToBase58(byte[] ba)
        {
            Org.BouncyCastle.Math.BigInteger addrremain = new Org.BouncyCastle.Math.BigInteger(1, ba);

            Org.BouncyCastle.Math.BigInteger big0  = new Org.BouncyCastle.Math.BigInteger("0");
            Org.BouncyCastle.Math.BigInteger big58 = new Org.BouncyCastle.Math.BigInteger("58");

            string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            string rv = "";

            while (addrremain.CompareTo(big0) > 0)
            {
                int d = Convert.ToInt32(addrremain.Mod(big58).ToString());
                addrremain = addrremain.Divide(big58);
                rv         = b58.Substring(d, 1) + rv;
            }

            // handle leading zeroes
            foreach (byte b in ba)
            {
                if (b != 0)
                {
                    break;
                }
                rv = "1" + rv;
            }
            return(rv);
        }
		public static BigInteger ValidatePublicValue(BigInteger N, BigInteger val)
		{
		    val = val.Mod(N);

	        // Check that val % N != 0
	        if (val.Equals(BigInteger.Zero))
	            throw new CryptoException("Invalid public value: 0");

		    return val;
		}
Beispiel #6
0
        public String decipher(List <Org.BouncyCastle.Math.BigInteger> cipher, MHPrivateKey key)
        {
            String decrypted = "";

            Org.BouncyCastle.Math.BigInteger temp = Org.BouncyCastle.Math.BigInteger.ValueOf(0);
            int tmp = 0;

            Org.BouncyCastle.Math.BigInteger bits = Org.BouncyCastle.Math.BigInteger.ValueOf(0);

            for (int i = 0; i < cipher.Count; i++)
            {
                temp = cipher.ElementAt(i);
                int bitlen = temp.BitLength;
                int ff     = 0;
                while (bitlen < (int)Math.Pow(2, ff))
                {
                    ff++;
                }
                if (ff > bitlen)
                {
                    bitlen = ff;
                }

                for (int j = 0; j < bitlen; j++)
                {
                    if (temp.Mod(Org.BouncyCastle.Math.BigInteger.ValueOf(2)).CompareTo(Org.BouncyCastle.Math.BigInteger.ValueOf(1)) == 0)
                    {
                        bits = bits.Add(key.w1.Multiply(Org.BouncyCastle.Math.BigInteger.ValueOf((long)Math.Pow(2, j))));
                    }
                    temp = temp.ShiftRight(1);
                }
                bits = bits.Mod(key.n);
                List <Org.BouncyCastle.Math.BigInteger> list = key.a;
                Org.BouncyCastle.Math.BigInteger        temper;

                int k = key.a.Count - 1;
                while (k >= 0)
                {
                    temper = list.ElementAt(k);
                    if (bits.CompareTo(temper) > -1)
                    {
                        tmp += (int)Math.Pow(2, k);
                        bits = bits.Subtract(temper);
                    }
                    k--;
                }
                decrypted += (binaryToChar(Convert.ToString(tmp, 2))).ToString();

                bits = Org.BouncyCastle.Math.BigInteger.ValueOf(0);
                tmp  = 0;
            }
            return(decrypted);
        }
Beispiel #7
0
 public Org.BouncyCastle.Math.BigInteger getGCD(Org.BouncyCastle.Math.BigInteger bd1, Org.BouncyCastle.Math.BigInteger bd2)
 {
     Org.BouncyCastle.Math.BigInteger bigger  = (bd1.CompareTo(bd2) > 0) ? bd1 : bd2;
     Org.BouncyCastle.Math.BigInteger smaller = (bd1.CompareTo(bd2) < 0) ? bd1 : bd2;
     Org.BouncyCastle.Math.BigInteger gcd     = smaller;
     while (!Org.BouncyCastle.Math.BigInteger.Zero.Equals(smaller))
     {
         gcd     = smaller;
         smaller = bigger.Mod(smaller);
         bigger  = gcd;
     }
     return(gcd);
 }
Beispiel #8
0
        internal static BigInteger Pair(FpPoint Q, FpPoint P, BigInteger m, BigInteger p)
        {
            // TODO: napravi jebeno uparivanje!!!! - nešto zeza

            BigInteger pq = Miller(P, Q, m, p);
            BigInteger qp = Miller(Q, P, m, p);

            int parity = m.Mod(new BigInteger("2", 10)).IntValue;

            BigInteger rez = new BigInteger(Math.Pow(-1, parity).ToString(), 10).Multiply(pq.Divide(qp)).Mod(p);

            return rez;
        }
        /**
         * Generate a signature for the given message using the key we were
         * initialised with. For conventional DSA the message should be a SHA-1
         * hash of the message of interest.
         *
         * @param message the message that will be verified later.
         */
        public IBigInteger[] GenerateSignature(byte[] message)
        {
            var parameters = _key.Parameters;
            var q = parameters.Q;
            var m = CalculateE(q, message);
            IBigInteger k;
            do
            {
                k = new BigInteger(q.BitLength, _random);
            }
            while (k.CompareTo(q) >= 0);

            var r = parameters.G.ModPow(k, parameters.P).Mod(q);
            k = k.ModInverse(q).Multiply(m.Add(((DsaPrivateKeyParameters)_key).X.Multiply(r)));

            var s = k.Mod(q);

            return new[] { r, s };
        }
Beispiel #10
0
 public static string Encode(byte[] input)
 {
     var bi = new BigInteger(1, input);
     var s = new StringBuilder();
     while (bi.CompareTo(Base) >= 0)
     {
         var mod = bi.Mod(Base);
         s.Insert(0, new[] {Alphabet[mod.IntValue]});
         bi = bi.Subtract(mod).Divide(Base);
     }
     s.Insert(0, new[] {Alphabet[bi.IntValue]});
     // Convert leading zeros too.
     foreach (var anInput in input)
     {
         if (anInput == 0)
             s.Insert(0, new[] {Alphabet[0]});
         else
             break;
     }
     return s.ToString();
 }
 /// <summary>
 /// Encode a byte sequence as a base58-encoded string
 /// </summary>
 /// <param name="bytes">Byte sequence</param>
 /// <returns>Encoding result</returns>
 public static string Base58Encode(byte[] input)
 {
     // TODO: This could be a lot more efficient.
     var bi = new BigInteger(1, input);
     var s = new StringBuilder();
     while (bi.CompareTo(_base) >= 0)
     {
         var mod = bi.Mod(_base);
         s.Insert(0, new[] { strDigits[mod.IntValue] });
         bi = bi.Subtract(mod).Divide(_base);
     }
     s.Insert(0, new[] { strDigits[bi.IntValue] });
     // Convert leading zeros too.
     foreach (var anInput in input)
     {
         if (anInput == 0)
             s.Insert(0, new[] { strDigits[0] });
         else
             break;
     }
     return s.ToString();
 }
        /**
         * which Generates the p and g values from the given parameters,
         * returning the DsaParameters object.
         * <p>
         * Note: can take a while...</p>
         */
        public DsaParameters GenerateParameters()
        {
            byte[]          seed = new byte[20];
            byte[]          part1 = new byte[20];
            byte[]          part2 = new byte[20];
            byte[]          u = new byte[20];
            Sha1Digest      sha1 = new Sha1Digest();
            int             n = (size - 1) / 160;
            byte[]          w = new byte[size / 8];

            BigInteger      q = null, p = null, g = null;
            int             counter = 0;
            bool         primesFound = false;

            while (!primesFound)
            {
                do
                {
                    random.NextBytes(seed);

                    sha1.BlockUpdate(seed, 0, seed.Length);

                    sha1.DoFinal(part1, 0);

                    Array.Copy(seed, 0, part2, 0, seed.Length);

                    Add(part2, seed, 1);

                    sha1.BlockUpdate(part2, 0, part2.Length);

                    sha1.DoFinal(part2, 0);

                    for (int i = 0; i != u.Length; i++)
                    {
                        u[i] = (byte)(part1[i] ^ part2[i]);
                    }

                    u[0] |= (byte)0x80;
                    u[19] |= (byte)0x01;

                    q = new BigInteger(1, u);
                }
                while (!q.IsProbablePrime(certainty));

                counter = 0;

                int offset = 2;

                while (counter < 4096)
                {
                    for (int k = 0; k < n; k++)
                    {
                        Add(part1, seed, offset + k);
                        sha1.BlockUpdate(part1, 0, part1.Length);
                        sha1.DoFinal(part1, 0);
                        Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
                    }

                    Add(part1, seed, offset + n);
                    sha1.BlockUpdate(part1, 0, part1.Length);
                    sha1.DoFinal(part1, 0);
                    Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

                    w[0] |= (byte)0x80;

                    BigInteger  x = new BigInteger(1, w);

                    BigInteger  c = x.Mod(q.ShiftLeft(1));

                    p = x.Subtract(c.Subtract(BigInteger.One));

                    if (p.TestBit(size - 1))
                    {
                        if (p.IsProbablePrime(certainty))
                        {
                            primesFound = true;
                            break;
                        }
                    }

                    counter += 1;
                    offset += n + 1;
                }
            }

            //
            // calculate the generator g
            //
            BigInteger  pMinusOneOverQ = p.Subtract(BigInteger.One).Divide(q);

            for (;;)
            {
                BigInteger h = new BigInteger(size, random);
                if (h.CompareTo(BigInteger.One) <= 0 || h.CompareTo(p.Subtract(BigInteger.One)) >= 0)
                {
                    continue;
                }

                g = h.ModPow(pMinusOneOverQ, p);
                if (g.CompareTo(BigInteger.One) <= 0)
                {
                    continue;
                }

                break;
            }

            return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
        }
		private DsaParameters GenerateParameters_FIPS186_2()
		{
            byte[] seed = new byte[20];
            byte[] part1 = new byte[20];
            byte[] part2 = new byte[20];
            byte[] u = new byte[20];
            Sha1Digest sha1 = new Sha1Digest();
			int n = (L - 1) / 160;
			byte[] w = new byte[L / 8];

			for (;;)
			{
				random.NextBytes(seed);

				Hash(sha1, seed, part1);
				Array.Copy(seed, 0, part2, 0, seed.Length);
				Inc(part2);
				Hash(sha1, part2, part2);

				for (int i = 0; i != u.Length; i++)
				{
					u[i] = (byte)(part1[i] ^ part2[i]);
				}

				u[0] |= (byte)0x80;
				u[19] |= (byte)0x01;

				BigInteger q = new BigInteger(1, u);

				if (!q.IsProbablePrime(certainty))
					continue;

				byte[] offset = Arrays.Clone(seed);
				Inc(offset);

				for (int counter = 0; counter < 4096; ++counter)
				{
					for (int k = 0; k < n; k++)
					{
						Inc(offset);
						Hash(sha1, offset, part1);
						Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
					}

					Inc(offset);
					Hash(sha1, offset, part1);
					Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

					w[0] |= (byte)0x80;

					BigInteger x = new BigInteger(1, w);

					BigInteger c = x.Mod(q.ShiftLeft(1));

					BigInteger p = x.Subtract(c.Subtract(BigInteger.One));

					if (p.BitLength != L)
						continue;

					if (p.IsProbablePrime(certainty))
					{
						BigInteger g = CalculateGenerator_FIPS186_2(p, q, random);

						return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
					}
				}
			}
		}
		/**
		 * generate suitable parameters for DSA, in line with
		 * <i>FIPS 186-3 A.1 Generation of the FFC Primes p and q</i>.
		 */
		private DsaParameters GenerateParameters_FIPS186_3()
		{
// A.1.1.2 Generation of the Probable Primes p and q Using an Approved Hash Function
			// FIXME This should be configurable (digest size in bits must be >= N)
			IDigest d = new Sha256Digest();
			int outlen = d.GetDigestSize() * 8;

// 1. Check that the (L, N) pair is in the list of acceptable (L, N pairs) (see Section 4.2). If
//    the pair is not in the list, then return INVALID.
			// Note: checked at initialisation
			
// 2. If (seedlen < N), then return INVALID.
			// FIXME This should be configurable (must be >= N)
			int seedlen = N;
			byte[] seed = new byte[seedlen / 8];

// 3. n = ceiling(L ⁄ outlen) – 1.
			int n = (L - 1) / outlen;

// 4. b = L – 1 – (n ∗ outlen).
			int b = (L - 1) % outlen;

			byte[] output = new byte[d.GetDigestSize()];
			for (;;)
			{
// 5. Get an arbitrary sequence of seedlen bits as the domain_parameter_seed.
				random.NextBytes(seed);

// 6. U = Hash (domain_parameter_seed) mod 2^(N–1).
				Hash(d, seed, output);
				BigInteger U = new BigInteger(1, output).Mod(BigInteger.One.ShiftLeft(N - 1));

// 7. q = 2^(N–1) + U + 1 – ( U mod 2).
				BigInteger q = BigInteger.One.ShiftLeft(N - 1).Add(U).Add(BigInteger.One).Subtract(
					U.Mod(BigInteger.Two));

// 8. Test whether or not q is prime as specified in Appendix C.3.
				// TODO Review C.3 for primality checking
				if (!q.IsProbablePrime(certainty))
				{
// 9. If q is not a prime, then go to step 5.
					continue;
				}

// 10. offset = 1.
				// Note: 'offset' value managed incrementally
				byte[] offset = Arrays.Clone(seed);

// 11. For counter = 0 to (4L – 1) do
				int counterLimit = 4 * L;
				for (int counter = 0; counter < counterLimit; ++counter)
				{
// 11.1 For j = 0 to n do
//      Vj = Hash ((domain_parameter_seed + offset + j) mod 2^seedlen).
// 11.2 W = V0 + (V1 ∗ 2^outlen) + ... + (V^(n–1) ∗ 2^((n–1) ∗ outlen)) + ((Vn mod 2^b) ∗ 2^(n ∗ outlen)).
					// TODO Assemble w as a byte array
					BigInteger W = BigInteger.Zero;
					for (int j = 0, exp = 0; j <= n; ++j, exp += outlen)
					{
						Inc(offset);
						Hash(d, offset, output);

						BigInteger Vj = new BigInteger(1, output);
						if (j == n)
						{
							Vj = Vj.Mod(BigInteger.One.ShiftLeft(b));
						}

						W = W.Add(Vj.ShiftLeft(exp));
					}

// 11.3 X = W + 2^(L–1). Comment: 0 ≤ W < 2L–1; hence, 2L–1 ≤ X < 2L.
					BigInteger X = W.Add(BigInteger.One.ShiftLeft(L - 1));

// 11.4 c = X mod 2q.
					BigInteger c = X.Mod(q.ShiftLeft(1));

// 11.5 p = X - (c - 1). Comment: p ≡ 1 (mod 2q).
					BigInteger p = X.Subtract(c.Subtract(BigInteger.One));

					// 11.6 If (p < 2^(L - 1)), then go to step 11.9
					if (p.BitLength != L)
						continue;

// 11.7 Test whether or not p is prime as specified in Appendix C.3.
					// TODO Review C.3 for primality checking
					if (p.IsProbablePrime(certainty))
					{
// 11.8 If p is determined to be prime, then return VALID and the values of p, q and
//      (optionally) the values of domain_parameter_seed and counter.
						// TODO Make configurable (8-bit unsigned)?
//	                    int index = 1;
//	                    BigInteger g = CalculateGenerator_FIPS186_3_Verifiable(d, p, q, seed, index);
//	                    if (g != null)
//	                    {
//	                        // TODO Should 'index' be a part of the validation parameters?
//	                        return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
//	                    }

						BigInteger g = CalculateGenerator_FIPS186_3_Unverifiable(p, q, random);
						return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
					}

// 11.9 offset = offset + n + 1.      Comment: Increment offset; then, as part of
//                                    the loop in step 11, increment counter; if
//                                    counter < 4L, repeat steps 11.1 through 11.8.
					// Note: 'offset' value already incremented in inner loop
				}
// 12. Go to step 5.
			}
		}
		/**
		* @exception InvalidCipherTextException if the decrypted block is not a valid ISO 9796 bit string
		*/
		private byte[] DecodeBlock(
			byte[]	input,
			int		inOff,
			int		inLen)
		{
			byte[]  block = engine.ProcessBlock(input, inOff, inLen);
			int     r = 1;
			int     t = (bitSize + 13) / 16;

			BigInteger iS = new BigInteger(1, block);
			BigInteger iR;
			if (iS.Mod(Sixteen).Equals(Six))
			{
				iR = iS;
			}
			else
			{
				iR = modulus.Subtract(iS);

				if (!iR.Mod(Sixteen).Equals(Six))
					throw new InvalidCipherTextException("resulting integer iS or (modulus - iS) is not congruent to 6 mod 16");
			}

			block = iR.ToByteArrayUnsigned();

			if ((block[block.Length - 1] & 0x0f) != 0x6)
				throw new InvalidCipherTextException("invalid forcing byte in block");

			block[block.Length - 1] =
				(byte)(((ushort)(block[block.Length - 1] & 0xff) >> 4)
				| ((inverse[(block[block.Length - 2] & 0xff) >> 4]) << 4));

			block[0] = (byte)((shadows[(uint) (block[1] & 0xff) >> 4] << 4)
				| shadows[block[1] & 0x0f]);

			bool boundaryFound = false;
			int boundary = 0;

			for (int i = block.Length - 1; i >= block.Length - 2 * t; i -= 2)
			{
				int val = ((shadows[(uint) (block[i] & 0xff) >> 4] << 4)
					| shadows[block[i] & 0x0f]);

				if (((block[i - 1] ^ val) & 0xff) != 0)
				{
					if (!boundaryFound)
					{
						boundaryFound = true;
						r = (block[i - 1] ^ val) & 0xff;
						boundary = i - 1;
					}
					else
					{
						throw new InvalidCipherTextException("invalid tsums in block");
					}
				}
			}

			block[boundary] = 0;

			byte[] nblock = new byte[(block.Length - boundary) / 2];

			for (int i = 0; i < nblock.Length; i++)
			{
				nblock[i] = block[2 * i + boundary + 1];
			}

			padBits = r - 1;

			return nblock;
		}
Beispiel #16
0
 public static string Encode(byte[] input)
 {
     // TODO: This could be a lot more efficient.
     var bigInteger = new BigInteger(1, input);
     var stringBuilder = new StringBuilder();
     while (bigInteger.CompareTo(Base) >= 0)
     {
         var mod = bigInteger.Mod(Base);
         stringBuilder.Insert(0, new[] {Alphabet[mod.IntValue]});
         bigInteger = bigInteger.Subtract(mod).Divide(Base);
     }
     stringBuilder.Insert(0, new[] {Alphabet[bigInteger.IntValue]});
     // Convert leading zeros too.
     foreach (var anInput in input)
     {
         if (anInput == 0)
             stringBuilder.Insert(0, new[] {Alphabet[0]});
         else
             break;
     }
     return stringBuilder.ToString();
 }
Beispiel #17
0
        private static bool ImplHasAnySmallFactors(BigInteger x)
        {
            /*
             * Bundle trial divisors into ~32-bit moduli then use fast tests on the ~32-bit remainders.
             */
            int m = 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23;
            int r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 2) == 0 || (r % 3) == 0 || (r % 5) == 0 || (r % 7) == 0 || (r % 11) == 0 || (r % 13) == 0
                || (r % 17) == 0 || (r % 19) == 0 || (r % 23) == 0)
            {
                return true;
            }

            m = 29 * 31 * 37 * 41 * 43;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 29) == 0 || (r % 31) == 0 || (r % 37) == 0 || (r % 41) == 0 || (r % 43) == 0)
            {
                return true;
            }

            m = 47 * 53 * 59 * 61 * 67;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 47) == 0 || (r % 53) == 0 || (r % 59) == 0 || (r % 61) == 0 || (r % 67) == 0)
            {
                return true;
            }

            m = 71 * 73 * 79 * 83;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 71) == 0 || (r % 73) == 0 || (r % 79) == 0 || (r % 83) == 0)
            {
                return true;
            }

            m = 89 * 97 * 101 * 103;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 89) == 0 || (r % 97) == 0 || (r % 101) == 0 || (r % 103) == 0)
            {
                return true;
            }

            m = 107 * 109 * 113 * 127;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 107) == 0 || (r % 109) == 0 || (r % 113) == 0 || (r % 127) == 0)
            {
                return true;
            }

            m = 131 * 137 * 139 * 149;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 131) == 0 || (r % 137) == 0 || (r % 139) == 0 || (r % 149) == 0)
            {
                return true;
            }

            m = 151 * 157 * 163 * 167;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 151) == 0 || (r % 157) == 0 || (r % 163) == 0 || (r % 167) == 0)
            {
                return true;
            }

            m = 173 * 179 * 181 * 191;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 173) == 0 || (r % 179) == 0 || (r % 181) == 0 || (r % 191) == 0)
            {
                return true;
            }

            m = 193 * 197 * 199 * 211;
            r = x.Mod(BigInteger.ValueOf(m)).IntValue;
            if ((r % 193) == 0 || (r % 197) == 0 || (r % 199) == 0 || (r % 211) == 0)
            {
                return true;
            }

            /*
             * NOTE: Unit tests depend on SMALL_FACTOR_LIMIT matching the
             * highest small factor tested here.
             */
            return false;
        }
Beispiel #18
0
 private static bool MightBePrime(BigInteger x)
 {
     /*
      * Bundle trial divisors into ~32-bit moduli then use fast tests on the ~32-bit remainders.
      */
     int m = 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23;
     int r = x.Mod(BigInteger.ValueOf(m)).IntValue;
     if ((r & 1) != 0 && (r % 3) != 0 && (r % 5) != 0 && (r % 7) != 0 && (r % 11) != 0
         && (r % 13) != 0 && (r % 17) != 0 && (r % 19) != 0 && (r % 23) != 0)
     {
         m = 29 * 31 * 37 * 41 * 43;
         r = x.Mod(BigInteger.ValueOf(m)).IntValue;
         if ((r % 29) != 0 && (r % 31) != 0 && (r % 37) != 0 && (r % 41) != 0 && (r % 43) != 0)
         {
             m = 47 * 53 * 59 * 61 * 67;
             r = x.Mod(BigInteger.ValueOf(m)).IntValue;
             if ((r % 47) != 0 && (r % 53) != 0 && (r % 59) != 0 && (r % 61) != 0 && (r % 67) != 0)
             {
                 m = 71 * 73 * 79 * 83;
                 r = x.Mod(BigInteger.ValueOf(m)).IntValue;
                 if ((r % 71) != 0 && (r % 73) != 0 && (r % 79) != 0 && (r % 83) != 0)
                 {
                     m = 89 * 97 * 101 * 103;
                     r = x.Mod(BigInteger.ValueOf(m)).IntValue;
                     if ((r % 89) != 0 && (r % 97) != 0 && (r % 101) != 0 && (r % 103) != 0)
                     {
                         m = 107 * 109 * 113 * 127;
                         r = x.Mod(BigInteger.ValueOf(m)).IntValue;
                         if ((r % 107) != 0 && (r % 109) != 0 && (r % 113) != 0 && (r % 127) != 0)
                         {
                             return true;
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
Beispiel #19
0
        public string ToString(
			int radix)
        {
            // TODO Make this method work for other radices (ideally 2 <= radix <= 16)

            switch (radix)
            {
                case 2:
                case 10:
                case 16:
                    break;
                default:
                    throw new FormatException("Only base 10 or 16 are allowed");
            }

            // NB: Can only happen to internally managed instances
            if (magnitude == null)
                return "null";

            if (sign == 0)
                return "0";

            Debug.Assert(magnitude.Length > 0);

            StringBuilder sb = new StringBuilder();

            if (radix == 16)
            {
                sb.Append(magnitude[0].ToString("x"));

                for (int i = 1; i < magnitude.Length; i++)
                {
                    sb.Append(magnitude[i].ToString("x8"));
                }
            }
            else if (radix == 2)
            {
                for (int i = BitLength - 1; i >= 0; --i)
                {
                    sb.Append(TestBit(i) ? '1' : '0');
                }
            }
            else
            {
                // This is algorithm 1a from chapter 4.4 in Seminumerical Algorithms, slow but it works
                Stack S = new Stack();
                BigInteger bs = ValueOf(radix);

                // The sign is handled separatly.
                // Notice however that for this to work, radix 16 _MUST_ be a special case,
                // unless we want to enter a recursion well. In their infinite wisdom, why did not
                // the Sun engineers made a c'tor for BigIntegers taking a BigInteger as parameter?
                // (Answer: Becuase Sun's BigIntger is clonable, something bouncycastle's isn't.)
                BigInteger u = new BigInteger(Abs().ToString(16), 16);
                BigInteger b;

                while (u.sign != 0)
                {
                    b = u.Mod(bs);
                    if (b.sign == 0)
                    {
                        S.Push("0");
                    }
                    else
                    {
                        // see how to interact with different bases
                        S.Push(b.magnitude[0].ToString("d"));
                    }
                    u = u.Divide(bs);
                }

                // Then pop the stack
                while (S.Count != 0)
                {
                    sb.Append((string) S.Pop());
                }
            }

            string s = sb.ToString();

            Debug.Assert(s.Length > 0);

            // Strip leading zeros. (We know this number is not all zeroes though)
            if (s[0] == '0')
            {
                int nonZeroPos = 0;
                while (s[++nonZeroPos] == '0') {}

                s = s.Substring(nonZeroPos);
            }

            if (sign == -1)
            {
                s = "-" + s;
            }

            return s;
        }
Beispiel #20
0
        public void GenerateSignature(byte[] data_to_sign_byte_array, ref byte[] r_byte_array, ref byte[] s_byte_array)
        {
            if (data_to_sign_byte_array == null || data_to_sign_byte_array.Length < 1)
                throw new ArgumentException("GenerateSignature: The data byte array to sign cannot be null/empty");

            if (_private_key_param == null)
                throw new ArgumentException("GenerateSignature: The DSA private key cannot be null");

            if (_secure_random == null)
                _secure_random = new SecureRandom();

            BigInteger _data_to_sign = null;
            DsaParameters _parameters = null;
            BigInteger _k;
            BigInteger _r;
            BigInteger _s;
            int _q_bit_length;
            bool _do_again = false;
            int _failure_count = 0;

            _parameters = _private_key_param.Parameters;
            _data_to_sign = new BigInteger(1, data_to_sign_byte_array);
            _q_bit_length = _parameters.Q.BitLength;

            /*    */
               // if (IsValidPQLength(_parameters.P.BitLength, _parameters.Q.BitLength) == false)
            //throw new InvalidDataException("GenerateSignature: The Length of the DSA key P parameter does not correspond to that of the Q parameter");

            do
            {

                try
                {

                    do
                    {
                        _k = new BigInteger(1, _secure_random);

                    }
                    while (_k.CompareTo(_parameters.Q) >= 0);

                    _r = _parameters.G.ModPow(_k, _parameters.P).Mod(_parameters.Q);
                    _k = _k.ModInverse(_parameters.Q).Multiply(_data_to_sign.Add((_private_key_param).X.Multiply(_r)));
                    _s = _k.Mod(_parameters.Q);
                    r_byte_array = _r.ToByteArray();
                    s_byte_array = _s.ToByteArray();
                    _do_again = false;

                }

                catch (Exception)
                {
                    if (MAX_FAILURE_COUNT == _failure_count)
                   throw new InvalidDataException("GenerateSignature: Failed sign data after " + MAX_FAILURE_COUNT.ToString() + " tries.");
                    _do_again = true;
                    _failure_count++;

                }

            }
            while (_do_again == true);

            Utility.SetAsMinimalLengthBE(ref r_byte_array);
            Utility.SetAsMinimalLengthBE(ref s_byte_array);

            /*
            Console.WriteLine("Q Length {0} \n", _parameters.Q.BitLength/8);
            Console.WriteLine("R Length {0} \n", r_byte_array.Length);
            Console.WriteLine("S Length {0} \n", s_byte_array.Length);//*/
        }
        /// <summary>Choose a random prime value for use with RSA</summary>
        /// <param name="bitlength">the bit-length of the returned prime</param>
        /// <param name="e">the RSA public exponent</param>
        /// <returns>a prime p, with (p-1) relatively prime to e</returns>
        protected virtual BigInteger ChooseRandomPrime(int bitlength, BigInteger e)
        {
            bool eIsKnownOddPrime = (e.BitLength <= SPECIAL_E_BITS) && Arrays.Contains(SPECIAL_E_VALUES, e.IntValue);

            for (;;)
            {
                BigInteger p = new BigInteger(bitlength, 1, parameters.Random);

                if (p.Mod(e).Equals(One))
                    continue;

                if (!p.IsProbablePrime(parameters.Certainty, true))
                    continue;

                if (!eIsKnownOddPrime && !e.Gcd(p.Subtract(One)).Equals(One))
                    continue;

                return p;
            }
        }
Beispiel #22
0
		public void TestMod()
		{
			// TODO Basic tests

			for (int rep = 0; rep < 100; ++rep)
			{
				int diff = random.Next(25);
				BigInteger a = new BigInteger(100 - diff, 0, random);
				BigInteger b = new BigInteger(100 + diff, 0, random);
				BigInteger c = new BigInteger(10 + diff, 0, random);

				BigInteger d = a.Multiply(b).Add(c);
				BigInteger e = d.Mod(a);
				Assert.AreEqual(c, e);

				BigInteger pow2 = one.ShiftLeft(random.Next(128));
				Assert.AreEqual(b.And(pow2.Subtract(one)), b.Mod(pow2));
			}
		}