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); }
/** * 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. } }
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)); } } } }
private static BigInteger ModPowMonty(BigInteger b, BigInteger e, BigInteger m, bool convert) { int n = m.magnitude.Length; int powR = 32 * n; bool smallMontyModulus = m.BitLength + 2 <= powR; uint mDash = (uint)m.GetMQuote(); // tmp = this * R mod m if (convert) { b = b.ShiftLeft(powR).Remainder(m); } int[] yAccum = new int[n + 1]; int[] zVal = b.magnitude; Debug.Assert(zVal.Length <= n); if (zVal.Length < n) { int[] tmp = new int[n]; zVal.CopyTo(tmp, n - zVal.Length); zVal = tmp; } // Sliding window from MSW to LSW int extraBits = 0; // Filter the common case of small RSA exponents with few bits set if (e.magnitude.Length > 1 || e.BitCount > 2) { int expLength = e.BitLength; while (expLength > ExpWindowThresholds[extraBits]) { ++extraBits; } } int numPowers = 1 << extraBits; int[][] oddPowers = new int[numPowers][]; oddPowers[0] = zVal; int[] zSquared = Arrays.Clone(zVal); SquareMonty(yAccum, zSquared, m.magnitude, mDash, smallMontyModulus); for (int i = 1; i < numPowers; ++i) { oddPowers[i] = Arrays.Clone(oddPowers[i - 1]); MultiplyMonty(yAccum, oddPowers[i], zSquared, m.magnitude, mDash, smallMontyModulus); } int[] windowList = GetWindowList(e.magnitude, extraBits); Debug.Assert(windowList.Length > 1); int window = windowList[0]; int mult = window & 0xFF, lastZeroes = window >> 8; int[] yVal; if (mult == 1) { yVal = zSquared; --lastZeroes; } else { yVal = Arrays.Clone(oddPowers[mult >> 1]); } int windowPos = 1; while ((window = windowList[windowPos++]) != -1) { mult = window & 0xFF; int bits = lastZeroes + BitLengthTable[mult]; for (int j = 0; j < bits; ++j) { SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus); } MultiplyMonty(yAccum, yVal, oddPowers[mult >> 1], m.magnitude, mDash, smallMontyModulus); lastZeroes = window >> 8; } for (int i = 0; i < lastZeroes; ++i) { SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus); } if (convert) { // Return y * R^(-1) mod m MontgomeryReduce(yVal, m.magnitude, mDash); } else if (smallMontyModulus && CompareTo(0, yVal, 0, m.magnitude) >= 0) { Subtract(0, yVal, 0, m.magnitude); } return new BigInteger(1, yVal, true); }
public BigInteger Multiply( BigInteger val) { if (val == this) return Square(); if ((sign & 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 = magnitude.Length + val.magnitude.Length; int[] res = new int[resLength]; Multiply(res, this.magnitude, val.magnitude); int resSign = sign ^ val.sign ^ 1; return new BigInteger(resSign, res, true); }
/** * 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)); }
/* * Finds a pair of prime BigInteger's {p, q: p = 2q + 1} * * (see: Handbook of Applied Cryptography 4.86) */ internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random) { BigInteger p, q; int qLength = size - 1; int minWeight = size >> 2; if (size <= 32) { for (;;) { q = new BigInteger(qLength, 2, random); p = q.ShiftLeft(1).Add(BigInteger.One); if (!p.IsProbablePrime(certainty)) continue; if (certainty > 2 && !q.IsProbablePrime(certainty - 2)) continue; break; } } else { // Note: Modified from Java version for speed for (;;) { q = new BigInteger(qLength, 0, random); retry: for (int i = 0; i < primeLists.Length; ++i) { int test = q.Remainder(BigPrimeProducts[i]).IntValue; if (i == 0) { int rem3 = test % 3; if (rem3 != 2) { int diff = 2 * rem3 + 2; q = q.Add(BigInteger.ValueOf(diff)); test = (test + diff) % primeProducts[i]; } } int[] primeList = primeLists[i]; for (int j = 0; j < primeList.Length; ++j) { int prime = primeList[j]; int qRem = test % prime; if (qRem == 0 || qRem == (prime >> 1)) { q = q.Add(Six); goto retry; } } } if (q.BitLength != qLength) continue; if (!q.RabinMillerTest(2, random)) continue; p = q.ShiftLeft(1).Add(BigInteger.One); if (!p.RabinMillerTest(certainty, random)) continue; if (certainty > 2 && !q.RabinMillerTest(certainty - 2, random)) continue; /* * Require a minimum weight of the NAF representation, since low-weight primes may be * weak against a version of the number-field-sieve for the discrete-logarithm-problem. * * See "The number field sieve for integers of low weight", Oliver Schirokauer. */ if (WNafUtilities.GetNafWeight(p) < minWeight) continue; break; } } return new BigInteger[] { p, q }; }
/* * Finds a pair of prime BigInteger's {p, q: p = 2q + 1} * * (see: Handbook of Applied Cryptography 4.86) */ internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random) { BigInteger p, q; int qLength = size - 1; if (size <= 32) { for (;;) { q = new BigInteger(qLength, 2, random); p = q.ShiftLeft(1).Add(BigInteger.One); if (p.IsProbablePrime(certainty) && (certainty <= 2 || q.IsProbablePrime(certainty))) break; } } else { // Note: Modified from Java version for speed for (;;) { q = new BigInteger(qLength, 0, random); retry: for (int i = 0; i < primeLists.Length; ++i) { int test = q.Remainder(BigPrimeProducts[i]).IntValue; if (i == 0) { int rem3 = test % 3; if (rem3 != 2) { int diff = 2 * rem3 + 2; q = q.Add(BigInteger.ValueOf(diff)); test = (test + diff) % primeProducts[i]; } } int[] primeList = primeLists[i]; for (int j = 0; j < primeList.Length; ++j) { int prime = primeList[j]; int qRem = test % prime; if (qRem == 0 || qRem == (prime >> 1)) { q = q.Add(Six); goto retry; } } } if (q.BitLength != qLength) continue; if (!q.RabinMillerTest(2, random)) continue; p = q.ShiftLeft(1).Add(BigInteger.One); if (p.RabinMillerTest(certainty, random) && (certainty <= 2 || q.RabinMillerTest(certainty - 2, random))) break; } } return new BigInteger[] { p, q }; }
public void TestShiftLeft() { for (int i = 0; i < 100; ++i) { int shift = random.Next(128); BigInteger a = new BigInteger(128 + i, random).Add(one); int bits = a.BitCount; // Make sure nBits is set BigInteger negA = a.Negate(); bits = negA.BitCount; // Make sure nBits is set BigInteger b = a.ShiftLeft(shift); BigInteger c = negA.ShiftLeft(shift); Assert.AreEqual(a.BitCount, b.BitCount); Assert.AreEqual(negA.BitCount + shift, c.BitCount); Assert.AreEqual(a.BitLength + shift, b.BitLength); Assert.AreEqual(negA.BitLength + shift, c.BitLength); int j = 0; for (; j < shift; ++j) { Assert.IsFalse(b.TestBit(j)); } for (; j < b.BitLength; ++j) { Assert.AreEqual(a.TestBit(j - shift), b.TestBit(j)); } } }
public void TestMultiply() { BigInteger one = BigInteger.One; Assert.AreEqual(one, one.Negate().Multiply(one.Negate())); for (int i = 0; i < 100; ++i) { int aLen = 64 + random.Next(64); int bLen = 64 + random.Next(64); BigInteger a = new BigInteger(aLen, random).SetBit(aLen); BigInteger b = new BigInteger(bLen, random).SetBit(bLen); BigInteger c = new BigInteger(32, random); BigInteger ab = a.Multiply(b); BigInteger bc = b.Multiply(c); Assert.AreEqual(ab.Add(bc), a.Add(c).Multiply(b)); Assert.AreEqual(ab.Subtract(bc), a.Subtract(c).Multiply(b)); } // Special tests for power of two since uses different code path internally for (int i = 0; i < 100; ++i) { int shift = random.Next(64); BigInteger a = one.ShiftLeft(shift); BigInteger b = new BigInteger(64 + random.Next(64), random); BigInteger bShift = b.ShiftLeft(shift); Assert.AreEqual(bShift, a.Multiply(b)); Assert.AreEqual(bShift.Negate(), a.Multiply(b.Negate())); Assert.AreEqual(bShift.Negate(), a.Negate().Multiply(b)); Assert.AreEqual(bShift, a.Negate().Multiply(b.Negate())); Assert.AreEqual(bShift, b.Multiply(a)); Assert.AreEqual(bShift.Negate(), b.Multiply(a.Negate())); Assert.AreEqual(bShift.Negate(), b.Negate().Multiply(a)); Assert.AreEqual(bShift, b.Negate().Multiply(a.Negate())); } }
public void TestGetLowestSetBit() { for (int i = 0; i < 10; ++i) { BigInteger test = new BigInteger(128, 0, random).Add(one); int bit1 = test.GetLowestSetBit(); Assert.AreEqual(test, test.ShiftRight(bit1).ShiftLeft(bit1)); int bit2 = test.ShiftLeft(i + 1).GetLowestSetBit(); Assert.AreEqual(i + 1, bit2 - bit1); int bit3 = test.ShiftLeft(13 * i + 1).GetLowestSetBit(); Assert.AreEqual(13 * i + 1, bit3 - bit1); } }
/// <summary> /// Finds a pair of prime BigInteger's {p, q: p = 2q + 1} /// /// (see: Handbook of Applied Cryptography 4.86) /// </summary> /// <param name="size">The size.</param> /// <param name="certainty">The certainty.</param> /// <param name="random">The random.</param> /// <returns></returns> internal static IBigInteger[] GenerateSafePrimes(int size, int certainty, ISecureRandom random) { IBigInteger p, q; var qLength = size - 1; if (size <= 32) { for (; ; ) { q = new BigInteger(qLength, 2, random); p = q.ShiftLeft(1).Add(BigInteger.One); if (p.IsProbablePrime(certainty) && (certainty <= 2 || q.IsProbablePrime(certainty))) break; } } else { // Note: Modified from Java version for speed for (; ; ) { q = new BigInteger(qLength, 0, random); retry: for (var i = 0; i < _primeLists.Length; ++i) { var test = q.Remainder(_primeProductsBigs[i]).IntValue; if (i == 0) { var rem3 = test % 3; if (rem3 != 2) { var diff = 2 * rem3 + 2; q = q.Add(BigInteger.ValueOf(diff)); test = (test + diff) % _primeProductsInts[i]; } } var primeList = _primeLists[i]; foreach (var prime in primeList) { var qRem = test % prime; if (qRem != 0 && qRem != (prime >> 1)) continue; q = q.Add(_six); goto retry; } } if (q.BitLength != qLength) continue; if (!((BigInteger)q).RabinMillerTest(2, random)) continue; p = q.ShiftLeft(1).Add(BigInteger.One); if (((BigInteger)p).RabinMillerTest(certainty, random) && (certainty <= 2 || ((BigInteger)q).RabinMillerTest(certainty - 2, random))) break; } } return new[] { p, q }; }