Esempio n. 1
0
 /**
  * Initialises the client to begin new authentication attempt
  * @param N The safe prime associated with the client's verifier
  * @param g The group parameter associated with the client's verifier
  * @param digest The digest algorithm associated with the client's verifier
  * @param random For key generation
  */
 public virtual void Init(BigInteger N, BigInteger g, IDigest digest, SecureRandom random)
 {
     this.N = N;
     this.g = g;
     this.digest = digest;
     this.random = random;
 }
Esempio n. 2
0
        /**
        * Return a random BigInteger not less than 'min' and not greater than 'max'
        *
        * @param min the least value that may be generated
        * @param max the greatest value that may be generated
        * @param random the source of randomness
        * @return a random BigInteger value in the range [min,max]
        */
        public static BigInteger CreateRandomInRange(
            BigInteger		min,
            BigInteger		max,
            // TODO Should have been just Random class
            SecureRandom	random)
        {
            int cmp = min.CompareTo(max);
            if (cmp >= 0)
            {
                if (cmp > 0)
                    throw new ArgumentException("'min' may not be greater than 'max'");

                return min;
            }

            if (min.BitLength > max.BitLength / 2)
            {
                return CreateRandomInRange(BigInteger.Zero, max.Subtract(min), random).Add(min);
            }

            for (int i = 0; i < MaxIterations; ++i)
            {
                BigInteger x = new BigInteger(max.BitLength, random);
                if (x.CompareTo(min) >= 0 && x.CompareTo(max) <= 0)
                {
                    return x;
                }
            }

            // fall back to a faster (restricted) method
            return new BigInteger(max.Subtract(min).BitLength - 1, random).Add(min);
        }
Esempio n. 3
0
        /**
         * Processes the client's credentials. If valid the shared secret is generated and returned.
         * @param clientA The client's credentials
         * @return A shared secret BigInteger
         * @throws CryptoException If client's credentials are invalid
         */
        public virtual BigInteger CalculateSecret(BigInteger clientA)
        {
            this.A = Srp6Utilities.ValidatePublicValue(N, clientA);
            this.u = Srp6Utilities.CalculateU(digest, N, A, pubB);
            this.S = CalculateS();

            return S;
        }
Esempio n. 4
0
        /**
         * Generates the server's credentials that are to be sent to the client.
         * @return The server's public value to the client
         */
        public virtual BigInteger GenerateServerCredentials()
        {
            BigInteger k = Srp6Utilities.CalculateK(digest, N, g);
            this.privB = SelectPrivateValue();
            this.pubB = k.Multiply(v).Mod(N).Add(g.ModPow(privB, N)).Mod(N);

            return pubB;
        }
Esempio n. 5
0
        /**
         * Generates client's verification message given the server's credentials
         * @param serverB The server's credentials
         * @return Client's verification message for the server
         * @throws CryptoException If server's credentials are invalid
         */
        public virtual BigInteger CalculateSecret(BigInteger serverB)
        {
            this.B = Srp6Utilities.ValidatePublicValue(N, serverB);
            this.u = Srp6Utilities.CalculateU(digest, N, pubA, B);
            this.S = CalculateS();

            return S;
        }
Esempio n. 6
0
        public static BigInteger GeneratePrivateValue(IDigest digest, BigInteger N, BigInteger g, SecureRandom random)
        {
            int minBits = Math.Min(256, N.BitLength / 2);
            BigInteger min = BigInteger.One.ShiftLeft(minBits - 1);
            BigInteger max = N.Subtract(BigInteger.One);

            return BigIntegers.CreateRandomInRange(min, max, random);
        }
Esempio n. 7
0
        /**
         * Generates client's credentials given the client's salt, identity and password
         * @param salt The salt used in the client's verifier.
         * @param identity The user's identity (eg. username)
         * @param password The user's password
         * @return Client's public value to send to server
         */
        public virtual BigInteger GenerateClientCredentials(byte[] salt, byte[] identity, byte[] password)
        {
            this.x = Srp6Utilities.CalculateX(digest, N, salt, identity, password);
            this.privA = SelectPrivateValue();
            this.pubA = g.ModPow(privA, N);

            return pubA;
        }
Esempio n. 8
0
        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;
        }
Esempio n. 9
0
 private static byte[] GetPadded(BigInteger n, int length)
 {
     byte[] bs = BigIntegers.AsUnsignedByteArray(n);
     if (bs.Length < length)
     {
         byte[] tmp = new byte[length];
         Array.Copy(bs, 0, tmp, length - bs.Length, bs.Length);
         bs = tmp;
     }
     return bs;
 }
Esempio n. 10
0
        public static BigInteger CalculateX(IDigest digest, BigInteger N, byte[] salt, byte[] identity, byte[] password)
        {
            byte[] output = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(identity, 0, identity.Length);
            digest.Update((byte)':');
            digest.BlockUpdate(password, 0, password.Length);
            digest.DoFinal(output, 0);

            digest.BlockUpdate(salt, 0, salt.Length);
            digest.BlockUpdate(output, 0, output.Length);
            digest.DoFinal(output, 0);

            return new BigInteger(1, output).Mod(N);
        }
Esempio n. 11
0
        private static BigInteger HashPaddedPair(IDigest digest, BigInteger N, BigInteger n1, BigInteger n2)
        {
            int padLength = (N.BitLength + 7) / 8;

            byte[] n1_bytes = GetPadded(n1, padLength);
            byte[] n2_bytes = GetPadded(n2, padLength);

            digest.BlockUpdate(n1_bytes, 0, n1_bytes.Length);
            digest.BlockUpdate(n2_bytes, 0, n2_bytes.Length);

            byte[] output = new byte[digest.GetDigestSize()];
            digest.DoFinal(output, 0);

            return new BigInteger(1, output).Mod(N);
        }
Esempio n. 12
0
 public static BigInteger CalculateU(IDigest digest, BigInteger N, BigInteger A, BigInteger B)
 {
     return HashPaddedPair(digest, N, A, B);
 }
Esempio n. 13
0
 public static BigInteger CalculateK(IDigest digest, BigInteger N, BigInteger g)
 {
     return HashPaddedPair(digest, N, N, g);
 }
Esempio n. 14
0
		public int CompareTo(
			BigInteger value)
		{
			return sign < value.sign ? -1
				: sign > value.sign ? 1
				: sign == 0 ? 0
				: sign * CompareNoLeadingZeroes(0, magnitude, 0, value.magnitude);
		}
Esempio n. 15
0
		public BigInteger AndNot(
			BigInteger val)
		{
			return And(val.Not());
		}
Esempio n. 16
0
		public BigInteger And(
			BigInteger value)
		{
			if (this.sign == 0 || value.sign == 0)
			{
				return Zero;
			}

			int[] aMag = this.sign > 0
				? this.magnitude
				: Add(One).magnitude;

			int[] bMag = value.sign > 0
				? value.magnitude
				: value.Add(One).magnitude;

			bool resultNeg = sign < 0 && value.sign < 0;
			int resultLength = System.Math.Max(aMag.Length, bMag.Length);
			int[] resultMag = new int[resultLength];

			int aStart = resultMag.Length - aMag.Length;
			int bStart = resultMag.Length - bMag.Length;

			for (int i = 0; i < resultMag.Length; ++i)
			{
				int aWord = i >= aStart ? aMag[i - aStart] : 0;
				int bWord = i >= bStart ? bMag[i - bStart] : 0;

				if (this.sign < 0)
				{
					aWord = ~aWord;
				}

				if (value.sign < 0)
				{
					bWord = ~bWord;
				}

				resultMag[i] = aWord & bWord;

				if (resultNeg)
				{
					resultMag[i] = ~resultMag[i];
				}
			}

			BigInteger result = new BigInteger(1, resultMag, true);

			// TODO Optimise this case
			if (resultNeg)
			{
				result = result.Not();
			}

			return result;
		}
Esempio n. 17
0
		public BigInteger ModInverse(
			BigInteger m)
		{
			if (m.sign < 1)
				throw new ArithmeticException("Modulus must be positive");

			// TODO Too slow at the moment
//			// "Fast Key Exchange with Elliptic Curve Systems" R.Schoeppel
//			if (m.TestBit(0))
//			{
//				//The Almost Inverse Algorithm
//				int k = 0;
//				BigInteger B = One, C = Zero, F = this, G = m, tmp;
//
//				for (;;)
//				{
//					// While F is even, do F=F/u, C=C*u, k=k+1.
//					int zeroes = F.GetLowestSetBit();
//					if (zeroes > 0)
//					{
//						F = F.ShiftRight(zeroes);
//						C = C.ShiftLeft(zeroes);
//						k += zeroes;
//					}
//
//					// If F = 1, then return B,k.
//					if (F.Equals(One))
//					{
//						BigInteger half = m.Add(One).ShiftRight(1);
//						BigInteger halfK = half.ModPow(BigInteger.ValueOf(k), m);
//						return B.Multiply(halfK).Mod(m);
//					}
//
//					if (F.CompareTo(G) < 0)
//					{
//						tmp = G; G = F; F = tmp;
//						tmp = B; B = C; C = tmp;
//					}
//
//					F = F.Add(G);
//					B = B.Add(C);
//				}
//			}

			BigInteger x = new BigInteger();
			BigInteger gcd = ExtEuclid(this.Mod(m), m, x, null);

			if (!gcd.Equals(One))
				throw new ArithmeticException("Numbers not relatively prime.");

			if (x.sign < 0)
			{
				x.sign = 1;
				//x = m.Subtract(x);
				x.magnitude = doSubBigLil(m.magnitude, x.magnitude);
			}

			return x;
		}
Esempio n. 18
0
 /**
 * Return the passed in value as an unsigned byte array.
 *
 * @param value value to be converted.
 * @return a byte array without a leading zero byte if present in the signed encoding.
 */
 public static byte[] AsUnsignedByteArray(
     BigInteger n)
 {
     return n.ToByteArrayUnsigned();
 }
Esempio n. 19
0
		public BigInteger ShiftLeft(
			int n)
		{
			if (sign == 0 || magnitude.Length == 0)
				return Zero;

			if (n == 0)
				return this;

			if (n < 0)
				return ShiftRight(-n);

			BigInteger result = new BigInteger(sign, ShiftLeft(magnitude, n), true);

			if (this.nBits != -1)
			{
				result.nBits = sign > 0
					?	this.nBits
					:	this.nBits + n;
			}

			if (this.nBitLength != -1)
			{
				result.nBitLength = this.nBitLength + n;
			}

			return result;
		}
Esempio n. 20
0
		public BigInteger Remainder(
			BigInteger n)
		{
			if (n.sign == 0)
				throw new ArithmeticException("Division by zero error");

			if (this.sign == 0)
				return Zero;

			// For small values, use fast remainder method
			if (n.magnitude.Length == 1)
			{
				int val = n.magnitude[0];

				if (val > 0)
				{
					if (val == 1)
						return Zero;

					// TODO Make this func work on uint, and handle val == 1?
					int rem = Remainder(val);

					return rem == 0
						?	Zero
						:	new BigInteger(sign, new int[]{ rem }, false);
				}
			}

			if (CompareNoLeadingZeroes(0, magnitude, 0, n.magnitude) < 0)
				return this;

			int[] result;
			if (n.QuickPow2Check())  // n is power of two
			{
				// TODO Move before small values branch above?
				result = LastNBits(n.Abs().BitLength - 1);
			}
			else
			{
				result = (int[]) this.magnitude.Clone();
				result = Remainder(result, n.magnitude);
			}

			return new BigInteger(sign, result, true);
		}
Esempio n. 21
0
		public BigInteger Multiply(
			BigInteger val)
		{
			if (sign == 0 || val.sign == 0)
				return Zero;

			if (val.QuickPow2Check()) // val is power of two
			{
				BigInteger result = this.ShiftLeft(val.Abs().BitLength - 1);
				return val.sign > 0 ? result : result.Negate();
			}

			if (this.QuickPow2Check()) // this is power of two
			{
				BigInteger result = val.ShiftLeft(this.Abs().BitLength - 1);
				return this.sign > 0 ? result : result.Negate();
			}

			int resLength = (this.BitLength + val.BitLength) / BitsPerInt + 1;
			int[] res = new int[resLength];

			if (val == this)
			{
				Square(res, this.magnitude);
			}
			else
			{
				Multiply(res, this.magnitude, val.magnitude);
			}

			return new BigInteger(sign * val.sign, res, true);
		}
Esempio n. 22
0
		public BigInteger ModPow(
			BigInteger exponent,
			BigInteger m)
		{
			if (m.sign < 1)
				throw new ArithmeticException("Modulus must be positive");

			if (m.Equals(One))
				return Zero;

			if (exponent.sign == 0)
				return One;

			if (sign == 0)
				return Zero;

			int[] zVal = null;
			int[] yAccum = null;
			int[] yVal;

			// Montgomery exponentiation is only possible if the modulus is odd,
			// but AFAIK, this is always the case for crypto algo's
			bool useMonty = ((m.magnitude[m.magnitude.Length - 1] & 1) == 1);
			long mQ = 0;
			if (useMonty)
			{
				mQ = m.GetMQuote();

				// tmp = this * R mod m
				BigInteger tmp = ShiftLeft(32 * m.magnitude.Length).Mod(m);
				zVal = tmp.magnitude;

				useMonty = (zVal.Length <= m.magnitude.Length);

				if (useMonty)
				{
					yAccum = new int[m.magnitude.Length + 1];
					if (zVal.Length < m.magnitude.Length)
					{
						int[] longZ = new int[m.magnitude.Length];
						zVal.CopyTo(longZ, longZ.Length - zVal.Length);
						zVal = longZ;
					}
				}
			}

			if (!useMonty)
			{
				if (magnitude.Length <= m.magnitude.Length)
				{
					//zAccum = new int[m.magnitude.Length * 2];
					zVal = new int[m.magnitude.Length];
					magnitude.CopyTo(zVal, zVal.Length - magnitude.Length);
				}
				else
				{
					//
					// in normal practice we'll never see this...
					//
					BigInteger tmp = Remainder(m);

					//zAccum = new int[m.magnitude.Length * 2];
					zVal = new int[m.magnitude.Length];
					tmp.magnitude.CopyTo(zVal, zVal.Length - tmp.magnitude.Length);
				}

				yAccum = new int[m.magnitude.Length * 2];
			}

			yVal = new int[m.magnitude.Length];

			//
			// from LSW to MSW
			//
			for (int i = 0; i < exponent.magnitude.Length; i++)
			{
				int v = exponent.magnitude[i];
				int bits = 0;

				if (i == 0)
				{
					while (v > 0)
					{
						v <<= 1;
						bits++;
					}

					//
					// first time in initialise y
					//
					zVal.CopyTo(yVal, 0);

					v <<= 1;
					bits++;
				}

				while (v != 0)
				{
					if (useMonty)
					{
						// Montgomery square algo doesn't exist, and a normal
						// square followed by a Montgomery reduction proved to
						// be almost as heavy as a Montgomery mulitply.
						MultiplyMonty(yAccum, yVal, yVal, m.magnitude, mQ);
					}
					else
					{
						Square(yAccum, yVal);
						Remainder(yAccum, m.magnitude);
						Array.Copy(yAccum, yAccum.Length - yVal.Length, yVal, 0, yVal.Length);
						ZeroOut(yAccum);
					}
					bits++;

					if (v < 0)
					{
						if (useMonty)
						{
							MultiplyMonty(yAccum, yVal, zVal, m.magnitude, mQ);
						}
						else
						{
							Multiply(yAccum, yVal, zVal);
							Remainder(yAccum, m.magnitude);
							Array.Copy(yAccum, yAccum.Length - yVal.Length, yVal, 0,
								yVal.Length);
							ZeroOut(yAccum);
						}
					}

					v <<= 1;
				}

				while (bits < 32)
				{
					if (useMonty)
					{
						MultiplyMonty(yAccum, yVal, yVal, m.magnitude, mQ);
					}
					else
					{
						Square(yAccum, yVal);
						Remainder(yAccum, m.magnitude);
						Array.Copy(yAccum, yAccum.Length - yVal.Length, yVal, 0, yVal.Length);
						ZeroOut(yAccum);
					}
					bits++;
				}
			}

			if (useMonty)
			{
				// Return y * R^(-1) mod m by doing y * 1 * R^(-1) mod m
				ZeroOut(zVal);
				zVal[zVal.Length - 1] = 1;
				MultiplyMonty(yAccum, yVal, zVal, m.magnitude, mQ);
			}

			BigInteger result = new BigInteger(1, yVal, true);

			return exponent.sign > 0
				?	result
				:	result.ModInverse(m);
		}
Esempio n. 23
0
		/**
		 * Calculate the numbers u1, u2, and u3 such that:
		 *
		 * u1 * a + u2 * b = u3
		 *
		 * where u3 is the greatest common divider of a and b.
		 * a and b using the extended Euclid algorithm (refer p. 323
		 * of The Art of Computer Programming vol 2, 2nd ed).
		 * This also seems to have the side effect of calculating
		 * some form of multiplicative inverse.
		 *
		 * @param a    First number to calculate gcd for
		 * @param b    Second number to calculate gcd for
		 * @param u1Out      the return object for the u1 value
		 * @param u2Out      the return object for the u2 value
		 * @return     The greatest common divisor of a and b
		 */
		private static BigInteger ExtEuclid(
			BigInteger	a,
			BigInteger	b,
			BigInteger	u1Out,
			BigInteger	u2Out)
		{
			BigInteger u1 = One;
			BigInteger u3 = a;
			BigInteger v1 = Zero;
			BigInteger v3 = b;

			while (v3.sign > 0)
			{
				BigInteger[] q = u3.DivideAndRemainder(v3);

				BigInteger tmp = v1.Multiply(q[0]);
				BigInteger tn = u1.Subtract(tmp);
				u1 = v1;
				v1 = tn;

				u3 = v3;
				v3 = q[1];
			}

			if (u1Out != null)
			{
				u1Out.sign = u1.sign;
				u1Out.magnitude = u1.magnitude;
			}

			if (u2Out != null)
			{
				BigInteger tmp = u1.Multiply(a);
				tmp = u3.Subtract(tmp);
				BigInteger res = tmp.Divide(b);
				u2Out.sign = res.sign;
				u2Out.magnitude = res.magnitude;
			}

			return u3;
		}
Esempio n. 24
0
		public BigInteger Min(
			BigInteger value)
		{
			return CompareTo(value) < 0 ? this : value;
		}
Esempio n. 25
0
		public BigInteger Max(
			BigInteger value)
		{
			return CompareTo(value) > 0 ? this : value;
		}
Esempio n. 26
0
		public BigInteger Mod(
			BigInteger m)
		{
			if (m.sign < 1)
				throw new ArithmeticException("Modulus must be positive");

			BigInteger biggie = Remainder(m);

			return (biggie.sign >= 0 ? biggie : biggie.Add(m));
		}
Esempio n. 27
0
		private static BigInteger createUValueOf(
			ulong value)
		{
			int msw = (int)(value >> 32);
			int lsw = (int)value;

			if (msw != 0)
				return new BigInteger(1, new int[] { msw, lsw }, false);

			if (lsw != 0)
			{
				BigInteger n = new BigInteger(1, new int[] { lsw }, false);
				// Check for a power of two
				if ((lsw & -lsw) == lsw)
				{
					n.nBits = 1;
				}
				return n;
			}

			return Zero;
		}
Esempio n. 28
0
		public BigInteger Add(
			BigInteger value)
		{
			if (this.sign == 0)
				return value;

			if (this.sign != value.sign)
			{
				if (value.sign == 0)
					return this;

				if (value.sign < 0)
					return Subtract(value.Negate());

				return value.Subtract(Negate());
			}

			return AddToMagnitude(value.magnitude);
		}
Esempio n. 29
0
		public BigInteger Subtract(
			BigInteger n)
		{
			if (n.sign == 0)
				return this;

			if (this.sign == 0)
				return n.Negate();

			if (this.sign != n.sign)
				return Add(n.Negate());

			int compare = CompareNoLeadingZeroes(0, magnitude, 0, n.magnitude);
			if (compare == 0)
				return Zero;

			BigInteger bigun, lilun;
			if (compare < 0)
			{
				bigun = n;
				lilun = this;
			}
			else
			{
				bigun = this;
				lilun = n;
			}

			return new BigInteger(this.sign * compare, doSubBigLil(bigun.magnitude, lilun.magnitude), true);
		}
Esempio n. 30
0
		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;
		}