PageRenderTime 32ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/SSISSSHFTP/SSISSharpSSHFTP/SharpSSH/BigInteger.cs

#
C# | 2535 lines | 1641 code | 467 blank | 427 comment | 373 complexity | 5f517595d409cb5c07117a2c18fbcb26 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Tamir.SharpSsh
  5. {
  6. //
  7. // BigInteger.cs - Big Integer implementation
  8. //
  9. // Authors:
  10. // Ben Maurer
  11. // Chew Keong TAN
  12. // Sebastien Pouliot <sebastien@ximian.com>
  13. // Pieter Philippaerts <Pieter@mentalis.org>
  14. //
  15. // Copyright (c) 2003 Ben Maurer
  16. // All rights reserved
  17. //
  18. // Copyright (c) 2002 Chew Keong TAN
  19. // All rights reserved.
  20. //
  21. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  22. //
  23. // Permission is hereby granted, free of charge, to any person obtaining
  24. // a copy of this software and associated documentation files (the
  25. // "Software"), to deal in the Software without restriction, including
  26. // without limitation the rights to use, copy, modify, merge, publish,
  27. // distribute, sublicense, and/or sell copies of the Software, and to
  28. // permit persons to whom the Software is furnished to do so, subject to
  29. // the following conditions:
  30. //
  31. // The above copyright notice and this permission notice shall be
  32. // included in all copies or substantial portions of the Software.
  33. //
  34. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  35. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  36. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  37. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  38. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  39. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  40. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  41. //
  42. using System;
  43. using System.Security.Cryptography;
  44. public class BigInteger
  45. {
  46. #region Data Storage
  47. /// <summary>
  48. /// The Length of this BigInteger
  49. /// </summary>
  50. uint length = 1;
  51. /// <summary>
  52. /// The data for this BigInteger
  53. /// </summary>
  54. uint[] data;
  55. #endregion
  56. #region Constants
  57. /// <summary>
  58. /// Default length of a BigInteger in bytes
  59. /// </summary>
  60. const uint DEFAULT_LEN = 20;
  61. /// <summary>
  62. /// Table of primes below 2000.
  63. /// </summary>
  64. /// <remarks>
  65. /// <para>
  66. /// This table was generated using Mathematica 4.1 using the following function:
  67. /// </para>
  68. /// <para>
  69. /// <code>
  70. /// PrimeTable [x_] := Prime [Range [1, PrimePi [x]]]
  71. /// PrimeTable [6000]
  72. /// </code>
  73. /// </para>
  74. /// </remarks>
  75. internal static readonly uint[] smallPrimes = {
  76. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
  77. 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
  78. 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
  79. 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
  80. 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
  81. 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
  82. 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
  83. 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
  84. 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
  85. 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
  86. 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997,
  87. 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087,
  88. 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181,
  89. 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279,
  90. 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
  91. 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471,
  92. 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
  93. 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637,
  94. 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747,
  95. 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867,
  96. 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973,
  97. 1979, 1987, 1993, 1997, 1999,
  98. 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089,
  99. 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207,
  100. 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
  101. 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389,
  102. 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503,
  103. 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621,
  104. 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707,
  105. 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797,
  106. 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903,
  107. 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
  108. 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109,
  109. 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221,
  110. 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329,
  111. 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449,
  112. 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539,
  113. 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631,
  114. 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733,
  115. 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
  116. 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943,
  117. 3947, 3967, 3989,
  118. 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091,
  119. 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211,
  120. 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289,
  121. 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423,
  122. 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523,
  123. 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649,
  124. 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759,
  125. 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
  126. 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987,
  127. 4993, 4999,
  128. 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101,
  129. 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231,
  130. 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351,
  131. 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449,
  132. 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563,
  133. 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669,
  134. 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791,
  135. 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869,
  136. 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987
  137. };
  138. public enum Sign : int
  139. {
  140. Negative = -1,
  141. Zero = 0,
  142. Positive = 1
  143. };
  144. #region Exception Messages
  145. const string WouldReturnNegVal = "Operation would return a negative value";
  146. #endregion
  147. #endregion
  148. #region Constructors
  149. public BigInteger()
  150. {
  151. data = new uint[DEFAULT_LEN];
  152. this.length = DEFAULT_LEN;
  153. }
  154. #if !INSIDE_CORLIB
  155. [CLSCompliant(false)]
  156. #endif
  157. public BigInteger(Sign sign, uint len)
  158. {
  159. this.data = new uint[len];
  160. this.length = len;
  161. }
  162. public BigInteger(BigInteger bi)
  163. {
  164. this.data = (uint[])bi.data.Clone();
  165. this.length = bi.length;
  166. }
  167. #if !INSIDE_CORLIB
  168. [CLSCompliant(false)]
  169. #endif
  170. public BigInteger(BigInteger bi, uint len)
  171. {
  172. this.data = new uint[len];
  173. for (uint i = 0; i < bi.length; i++)
  174. this.data[i] = bi.data[i];
  175. this.length = bi.length;
  176. }
  177. #endregion
  178. #region Conversions
  179. public BigInteger(byte[] inData)
  180. {
  181. length = (uint)inData.Length >> 2;
  182. int leftOver = inData.Length & 0x3;
  183. // length not multiples of 4
  184. if (leftOver != 0) length++;
  185. data = new uint[length];
  186. for (int i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++)
  187. {
  188. data[j] = (uint)(
  189. (inData[i - 3] << (3 * 8)) |
  190. (inData[i - 2] << (2 * 8)) |
  191. (inData[i - 1] << (1 * 8)) |
  192. (inData[i])
  193. );
  194. }
  195. switch (leftOver)
  196. {
  197. case 1: data[length - 1] = (uint)inData[0]; break;
  198. case 2: data[length - 1] = (uint)((inData[0] << 8) | inData[1]); break;
  199. case 3: data[length - 1] = (uint)((inData[0] << 16) | (inData[1] << 8) | inData[2]); break;
  200. }
  201. this.Normalize();
  202. }
  203. #if !INSIDE_CORLIB
  204. [CLSCompliant(false)]
  205. #endif
  206. public BigInteger(uint[] inData)
  207. {
  208. length = (uint)inData.Length;
  209. data = new uint[length];
  210. for (int i = (int)length - 1, j = 0; i >= 0; i--, j++)
  211. data[j] = inData[i];
  212. this.Normalize();
  213. }
  214. #if !INSIDE_CORLIB
  215. [CLSCompliant(false)]
  216. #endif
  217. public BigInteger(uint ui)
  218. {
  219. data = new uint[] { ui };
  220. }
  221. #if !INSIDE_CORLIB
  222. [CLSCompliant(false)]
  223. #endif
  224. public BigInteger(ulong ul)
  225. {
  226. data = new uint[2] { (uint)ul, (uint)(ul >> 32) };
  227. length = 2;
  228. this.Normalize();
  229. }
  230. #if !INSIDE_CORLIB
  231. [CLSCompliant(false)]
  232. #endif
  233. public static implicit operator BigInteger(uint value)
  234. {
  235. return (new BigInteger(value));
  236. }
  237. public static implicit operator BigInteger(int value)
  238. {
  239. if (value < 0) throw new ArgumentOutOfRangeException("value");
  240. return (new BigInteger((uint)value));
  241. }
  242. #if !INSIDE_CORLIB
  243. [CLSCompliant(false)]
  244. #endif
  245. public static implicit operator BigInteger(ulong value)
  246. {
  247. return (new BigInteger(value));
  248. }
  249. /* This is the BigInteger.Parse method I use. This method works
  250. because BigInteger.ToString returns the input I gave to Parse. */
  251. public static BigInteger Parse(string number)
  252. {
  253. if (number == null)
  254. throw new ArgumentNullException("number");
  255. int i = 0, len = number.Length;
  256. char c;
  257. bool digits_seen = false;
  258. BigInteger val = new BigInteger(0);
  259. if (number[i] == '+')
  260. {
  261. i++;
  262. }
  263. else if (number[i] == '-')
  264. {
  265. throw new FormatException(WouldReturnNegVal);
  266. }
  267. for (; i < len; i++)
  268. {
  269. c = number[i];
  270. if (c == '\0')
  271. {
  272. i = len;
  273. continue;
  274. }
  275. if (c >= '0' && c <= '9')
  276. {
  277. val = val * 10 + (c - '0');
  278. digits_seen = true;
  279. }
  280. else
  281. {
  282. if (Char.IsWhiteSpace(c))
  283. {
  284. for (i++; i < len; i++)
  285. {
  286. if (!Char.IsWhiteSpace(number[i]))
  287. throw new FormatException();
  288. }
  289. break;
  290. }
  291. else
  292. throw new FormatException();
  293. }
  294. }
  295. if (!digits_seen)
  296. throw new FormatException();
  297. return val;
  298. }
  299. #endregion
  300. #region Operators
  301. public static BigInteger operator +(BigInteger bi1, BigInteger bi2)
  302. {
  303. if (bi1 == 0)
  304. return new BigInteger(bi2);
  305. else if (bi2 == 0)
  306. return new BigInteger(bi1);
  307. else
  308. return Kernel.AddSameSign(bi1, bi2);
  309. }
  310. public static BigInteger operator -(BigInteger bi1, BigInteger bi2)
  311. {
  312. if (bi2 == 0)
  313. return new BigInteger(bi1);
  314. if (bi1 == 0)
  315. throw new ArithmeticException(WouldReturnNegVal);
  316. switch (Kernel.Compare(bi1, bi2))
  317. {
  318. case Sign.Zero:
  319. return 0;
  320. case Sign.Positive:
  321. return Kernel.Subtract(bi1, bi2);
  322. case Sign.Negative:
  323. throw new ArithmeticException(WouldReturnNegVal);
  324. default:
  325. throw new Exception();
  326. }
  327. }
  328. public static int operator %(BigInteger bi, int i)
  329. {
  330. if (i > 0)
  331. return (int)Kernel.DwordMod(bi, (uint)i);
  332. else
  333. return -(int)Kernel.DwordMod(bi, (uint)-i);
  334. }
  335. #if !INSIDE_CORLIB
  336. [CLSCompliant(false)]
  337. #endif
  338. public static uint operator %(BigInteger bi, uint ui)
  339. {
  340. return Kernel.DwordMod(bi, (uint)ui);
  341. }
  342. public static BigInteger operator %(BigInteger bi1, BigInteger bi2)
  343. {
  344. return Kernel.multiByteDivide(bi1, bi2)[1];
  345. }
  346. public static BigInteger operator /(BigInteger bi, int i)
  347. {
  348. if (i > 0)
  349. return Kernel.DwordDiv(bi, (uint)i);
  350. throw new ArithmeticException(WouldReturnNegVal);
  351. }
  352. public static BigInteger operator /(BigInteger bi1, BigInteger bi2)
  353. {
  354. return Kernel.multiByteDivide(bi1, bi2)[0];
  355. }
  356. public static BigInteger operator *(BigInteger bi1, BigInteger bi2)
  357. {
  358. if (bi1 == 0 || bi2 == 0) return 0;
  359. //
  360. // Validate pointers
  361. //
  362. if (bi1.data.Length < bi1.length) throw new IndexOutOfRangeException("bi1 out of range");
  363. if (bi2.data.Length < bi2.length) throw new IndexOutOfRangeException("bi2 out of range");
  364. BigInteger ret = new BigInteger(Sign.Positive, bi1.length + bi2.length);
  365. Kernel.Multiply(bi1.data, 0, bi1.length, bi2.data, 0, bi2.length, ret.data, 0);
  366. ret.Normalize();
  367. return ret;
  368. }
  369. public static BigInteger operator *(BigInteger bi, int i)
  370. {
  371. if (i < 0) throw new ArithmeticException(WouldReturnNegVal);
  372. if (i == 0) return 0;
  373. if (i == 1) return new BigInteger(bi);
  374. return Kernel.MultiplyByDword(bi, (uint)i);
  375. }
  376. public static BigInteger operator <<(BigInteger bi1, int shiftVal)
  377. {
  378. return Kernel.LeftShift(bi1, shiftVal);
  379. }
  380. public static BigInteger operator >>(BigInteger bi1, int shiftVal)
  381. {
  382. return Kernel.RightShift(bi1, shiftVal);
  383. }
  384. #endregion
  385. #region Friendly names for operators
  386. // with names suggested by FxCop 1.30
  387. public static BigInteger Add(BigInteger bi1, BigInteger bi2)
  388. {
  389. return (bi1 + bi2);
  390. }
  391. public static BigInteger Subtract(BigInteger bi1, BigInteger bi2)
  392. {
  393. return (bi1 - bi2);
  394. }
  395. public static int Modulus(BigInteger bi, int i)
  396. {
  397. return (bi % i);
  398. }
  399. #if !INSIDE_CORLIB
  400. [CLSCompliant(false)]
  401. #endif
  402. public static uint Modulus(BigInteger bi, uint ui)
  403. {
  404. return (bi % ui);
  405. }
  406. public static BigInteger Modulus(BigInteger bi1, BigInteger bi2)
  407. {
  408. return (bi1 % bi2);
  409. }
  410. public static BigInteger Divid(BigInteger bi, int i)
  411. {
  412. return (bi / i);
  413. }
  414. public static BigInteger Divid(BigInteger bi1, BigInteger bi2)
  415. {
  416. return (bi1 / bi2);
  417. }
  418. public static BigInteger Multiply(BigInteger bi1, BigInteger bi2)
  419. {
  420. return (bi1 * bi2);
  421. }
  422. public static BigInteger Multiply(BigInteger bi, int i)
  423. {
  424. return (bi * i);
  425. }
  426. #endregion
  427. #region Random
  428. private static RandomNumberGenerator rng;
  429. private static RandomNumberGenerator Rng
  430. {
  431. get
  432. {
  433. if (rng == null)
  434. rng = RandomNumberGenerator.Create();
  435. return rng;
  436. }
  437. }
  438. /// <summary>
  439. /// Generates a new, random BigInteger of the specified length.
  440. /// </summary>
  441. /// <param name="bits">The number of bits for the new number.</param>
  442. /// <param name="rng">A random number generator to use to obtain the bits.</param>
  443. /// <returns>A random number of the specified length.</returns>
  444. public static BigInteger GenerateRandom(int bits, RandomNumberGenerator rng)
  445. {
  446. int dwords = bits >> 5;
  447. int remBits = bits & 0x1F;
  448. if (remBits != 0)
  449. dwords++;
  450. BigInteger ret = new BigInteger(Sign.Positive, (uint)dwords + 1);
  451. byte[] random = new byte[dwords << 2];
  452. rng.GetBytes(random);
  453. Buffer.BlockCopy(random, 0, ret.data, 0, (int)dwords << 2);
  454. if (remBits != 0)
  455. {
  456. uint mask = (uint)(0x01 << (remBits - 1));
  457. ret.data[dwords - 1] |= mask;
  458. mask = (uint)(0xFFFFFFFF >> (32 - remBits));
  459. ret.data[dwords - 1] &= mask;
  460. }
  461. else
  462. ret.data[dwords - 1] |= 0x80000000;
  463. ret.Normalize();
  464. return ret;
  465. }
  466. /// <summary>
  467. /// Generates a new, random BigInteger of the specified length using the default RNG crypto service provider.
  468. /// </summary>
  469. /// <param name="bits">The number of bits for the new number.</param>
  470. /// <returns>A random number of the specified length.</returns>
  471. public static BigInteger GenerateRandom(int bits)
  472. {
  473. return GenerateRandom(bits, Rng);
  474. }
  475. /// <summary>
  476. /// Randomizes the bits in "this" from the specified RNG.
  477. /// </summary>
  478. /// <param name="rng">A RNG.</param>
  479. public void Randomize(RandomNumberGenerator rng)
  480. {
  481. if (this == 0)
  482. return;
  483. int bits = this.BitCount();
  484. int dwords = bits >> 5;
  485. int remBits = bits & 0x1F;
  486. if (remBits != 0)
  487. dwords++;
  488. byte[] random = new byte[dwords << 2];
  489. rng.GetBytes(random);
  490. Buffer.BlockCopy(random, 0, data, 0, (int)dwords << 2);
  491. if (remBits != 0)
  492. {
  493. uint mask = (uint)(0x01 << (remBits - 1));
  494. data[dwords - 1] |= mask;
  495. mask = (uint)(0xFFFFFFFF >> (32 - remBits));
  496. data[dwords - 1] &= mask;
  497. }
  498. else
  499. data[dwords - 1] |= 0x80000000;
  500. Normalize();
  501. }
  502. /// <summary>
  503. /// Randomizes the bits in "this" from the default RNG.
  504. /// </summary>
  505. public void Randomize()
  506. {
  507. Randomize(Rng);
  508. }
  509. #endregion
  510. #region Bitwise
  511. public int BitCount()
  512. {
  513. this.Normalize();
  514. uint value = data[length - 1];
  515. uint mask = 0x80000000;
  516. uint bits = 32;
  517. while (bits > 0 && (value & mask) == 0)
  518. {
  519. bits--;
  520. mask >>= 1;
  521. }
  522. bits += ((length - 1) << 5);
  523. return (int)bits;
  524. }
  525. /// <summary>
  526. /// Tests if the specified bit is 1.
  527. /// </summary>
  528. /// <param name="bitNum">The bit to test. The least significant bit is 0.</param>
  529. /// <returns>True if bitNum is set to 1, else false.</returns>
  530. #if !INSIDE_CORLIB
  531. [CLSCompliant(false)]
  532. #endif
  533. public bool TestBit(uint bitNum)
  534. {
  535. uint bytePos = bitNum >> 5; // divide by 32
  536. byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits
  537. uint mask = (uint)1 << bitPos;
  538. return ((this.data[bytePos] & mask) != 0);
  539. }
  540. public bool TestBit(int bitNum)
  541. {
  542. if (bitNum < 0) throw new IndexOutOfRangeException("bitNum out of range");
  543. uint bytePos = (uint)bitNum >> 5; // divide by 32
  544. byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits
  545. uint mask = (uint)1 << bitPos;
  546. return ((this.data[bytePos] | mask) == this.data[bytePos]);
  547. }
  548. #if !INSIDE_CORLIB
  549. [CLSCompliant(false)]
  550. #endif
  551. public void SetBit(uint bitNum)
  552. {
  553. SetBit(bitNum, true);
  554. }
  555. #if !INSIDE_CORLIB
  556. [CLSCompliant(false)]
  557. #endif
  558. public void ClearBit(uint bitNum)
  559. {
  560. SetBit(bitNum, false);
  561. }
  562. #if !INSIDE_CORLIB
  563. [CLSCompliant(false)]
  564. #endif
  565. public void SetBit(uint bitNum, bool value)
  566. {
  567. uint bytePos = bitNum >> 5; // divide by 32
  568. if (bytePos < this.length)
  569. {
  570. uint mask = (uint)1 << (int)(bitNum & 0x1F);
  571. if (value)
  572. this.data[bytePos] |= mask;
  573. else
  574. this.data[bytePos] &= ~mask;
  575. }
  576. }
  577. public int LowestSetBit()
  578. {
  579. if (this == 0) return -1;
  580. int i = 0;
  581. while (!TestBit(i)) i++;
  582. return i;
  583. }
  584. public byte[] GetBytes()
  585. {
  586. if (this == 0) return new byte[1];
  587. int numBits = BitCount();
  588. int numBytes = numBits >> 3;
  589. if ((numBits & 0x7) != 0)
  590. numBytes++;
  591. byte[] result = new byte[numBytes];
  592. int numBytesInWord = numBytes & 0x3;
  593. if (numBytesInWord == 0) numBytesInWord = 4;
  594. int pos = 0;
  595. for (int i = (int)length - 1; i >= 0; i--)
  596. {
  597. uint val = data[i];
  598. for (int j = numBytesInWord - 1; j >= 0; j--)
  599. {
  600. result[pos + j] = (byte)(val & 0xFF);
  601. val >>= 8;
  602. }
  603. pos += numBytesInWord;
  604. numBytesInWord = 4;
  605. }
  606. return result;
  607. }
  608. #endregion
  609. #region Compare
  610. #if !INSIDE_CORLIB
  611. [CLSCompliant(false)]
  612. #endif
  613. public static bool operator ==(BigInteger bi1, uint ui)
  614. {
  615. if (bi1.length != 1) bi1.Normalize();
  616. return bi1.length == 1 && bi1.data[0] == ui;
  617. }
  618. #if !INSIDE_CORLIB
  619. [CLSCompliant(false)]
  620. #endif
  621. public static bool operator !=(BigInteger bi1, uint ui)
  622. {
  623. if (bi1.length != 1) bi1.Normalize();
  624. return !(bi1.length == 1 && bi1.data[0] == ui);
  625. }
  626. public static bool operator ==(BigInteger bi1, BigInteger bi2)
  627. {
  628. // we need to compare with null
  629. if ((bi1 as object) == (bi2 as object))
  630. return true;
  631. if (null == bi1 || null == bi2)
  632. return false;
  633. return Kernel.Compare(bi1, bi2) == 0;
  634. }
  635. public static bool operator !=(BigInteger bi1, BigInteger bi2)
  636. {
  637. // we need to compare with null
  638. if ((bi1 as object) == (bi2 as object))
  639. return false;
  640. if (null == bi1 || null == bi2)
  641. return true;
  642. return Kernel.Compare(bi1, bi2) != 0;
  643. }
  644. public static bool operator >(BigInteger bi1, BigInteger bi2)
  645. {
  646. return Kernel.Compare(bi1, bi2) > 0;
  647. }
  648. public static bool operator <(BigInteger bi1, BigInteger bi2)
  649. {
  650. return Kernel.Compare(bi1, bi2) < 0;
  651. }
  652. public static bool operator >=(BigInteger bi1, BigInteger bi2)
  653. {
  654. return Kernel.Compare(bi1, bi2) >= 0;
  655. }
  656. public static bool operator <=(BigInteger bi1, BigInteger bi2)
  657. {
  658. return Kernel.Compare(bi1, bi2) <= 0;
  659. }
  660. public Sign Compare(BigInteger bi)
  661. {
  662. return Kernel.Compare(this, bi);
  663. }
  664. #endregion
  665. #region Formatting
  666. #if !INSIDE_CORLIB
  667. [CLSCompliant(false)]
  668. #endif
  669. public string ToString(uint radix)
  670. {
  671. return ToString(radix, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  672. }
  673. #if !INSIDE_CORLIB
  674. [CLSCompliant(false)]
  675. #endif
  676. public string ToString(uint radix, string characterSet)
  677. {
  678. if (characterSet.Length < radix)
  679. throw new ArgumentException("charSet length less than radix", "characterSet");
  680. if (radix == 1)
  681. throw new ArgumentException("There is no such thing as radix one notation", "radix");
  682. if (this == 0) return "0";
  683. if (this == 1) return "1";
  684. string result = "";
  685. BigInteger a = new BigInteger(this);
  686. while (a != 0)
  687. {
  688. uint rem = Kernel.SingleByteDivideInPlace(a, radix);
  689. result = characterSet[(int)rem] + result;
  690. }
  691. return result;
  692. }
  693. #endregion
  694. #region Misc
  695. /// <summary>
  696. /// Normalizes this by setting the length to the actual number of
  697. /// uints used in data and by setting the sign to Sign.Zero if the
  698. /// value of this is 0.
  699. /// </summary>
  700. private void Normalize()
  701. {
  702. // Normalize length
  703. while (length > 0 && data[length - 1] == 0) length--;
  704. // Check for zero
  705. if (length == 0)
  706. length++;
  707. }
  708. public void Clear()
  709. {
  710. for (int i = 0; i < length; i++)
  711. data[i] = 0x00;
  712. }
  713. #endregion
  714. #region Object Impl
  715. public override int GetHashCode()
  716. {
  717. uint val = 0;
  718. for (uint i = 0; i < this.length; i++)
  719. val ^= this.data[i];
  720. return (int)val;
  721. }
  722. public override string ToString()
  723. {
  724. return ToString(10);
  725. }
  726. public override bool Equals(object o)
  727. {
  728. if (o == null) return false;
  729. if (o is int) return (int)o >= 0 && this == (uint)o;
  730. return Kernel.Compare(this, (BigInteger)o) == 0;
  731. }
  732. #endregion
  733. #region Number Theory
  734. public BigInteger GCD(BigInteger bi)
  735. {
  736. return Kernel.gcd(this, bi);
  737. }
  738. public BigInteger ModInverse(BigInteger modulus)
  739. {
  740. return Kernel.modInverse(this, modulus);
  741. }
  742. public BigInteger ModPow(BigInteger exp, BigInteger n)
  743. {
  744. ModulusRing mr = new ModulusRing(n);
  745. return mr.Pow(this, exp);
  746. }
  747. #endregion
  748. #region Prime Testing
  749. /*
  750. public bool IsProbablePrime()
  751. {
  752. if (this < smallPrimes[smallPrimes.Length - 1])
  753. {
  754. for (int p = 0; p < smallPrimes.Length; p++)
  755. {
  756. if (this == smallPrimes[p])
  757. return true;
  758. }
  759. }
  760. else
  761. {
  762. for (int p = 0; p < smallPrimes.Length; p++)
  763. {
  764. if (this % smallPrimes[p] == 0)
  765. return false;
  766. }
  767. }
  768. return PrimalityTests.RabinMillerTest(this, Prime.ConfidenceFactor.Medium);
  769. }
  770. */
  771. #endregion
  772. #region Prime Number Generation
  773. /// <summary>
  774. /// Increments this by two
  775. /// </summary>
  776. public void Incr2()
  777. {
  778. int i = 0;
  779. data[0] += 2;
  780. // If there was no carry, nothing to do
  781. if (data[0] < 2)
  782. {
  783. // Account for the first carry
  784. data[++i]++;
  785. // Keep adding until no carry
  786. while (data[i++] == 0x0)
  787. data[i]++;
  788. // See if we increased the data length
  789. if (length == (uint)i)
  790. length++;
  791. }
  792. }
  793. #endregion
  794. #if INSIDE_CORLIB
  795. internal
  796. #else
  797. public
  798. #endif
  799. sealed class ModulusRing
  800. {
  801. BigInteger mod, constant;
  802. public ModulusRing(BigInteger modulus)
  803. {
  804. this.mod = modulus;
  805. // calculate constant = b^ (2k) / m
  806. uint i = mod.length << 1;
  807. constant = new BigInteger(Sign.Positive, i + 1);
  808. constant.data[i] = 0x00000001;
  809. constant = constant / mod;
  810. }
  811. public void BarrettReduction(BigInteger x)
  812. {
  813. BigInteger n = mod;
  814. uint k = n.length,
  815. kPlusOne = k + 1,
  816. kMinusOne = k - 1;
  817. // x < mod, so nothing to do.
  818. if (x.length < k) return;
  819. BigInteger q3;
  820. //
  821. // Validate pointers
  822. //
  823. if (x.data.Length < x.length) throw new IndexOutOfRangeException("x out of range");
  824. // q1 = x / b^ (k-1)
  825. // q2 = q1 * constant
  826. // q3 = q2 / b^ (k+1), Needs to be accessed with an offset of kPlusOne
  827. // TODO: We should the method in HAC p 604 to do this (14.45)
  828. q3 = new BigInteger(Sign.Positive, x.length - kMinusOne + constant.length);
  829. Kernel.Multiply(x.data, kMinusOne, x.length - kMinusOne, constant.data, 0, constant.length, q3.data, 0);
  830. // r1 = x mod b^ (k+1)
  831. // i.e. keep the lowest (k+1) words
  832. uint lengthToCopy = (x.length > kPlusOne) ? kPlusOne : x.length;
  833. x.length = lengthToCopy;
  834. x.Normalize();
  835. // r2 = (q3 * n) mod b^ (k+1)
  836. // partial multiplication of q3 and n
  837. BigInteger r2 = new BigInteger(Sign.Positive, kPlusOne);
  838. Kernel.MultiplyMod2p32pmod(q3.data, (int)kPlusOne, (int)q3.length - (int)kPlusOne, n.data, 0, (int)n.length, r2.data, 0, (int)kPlusOne);
  839. r2.Normalize();
  840. if (r2 <= x)
  841. {
  842. Kernel.MinusEq(x, r2);
  843. }
  844. else
  845. {
  846. BigInteger val = new BigInteger(Sign.Positive, kPlusOne + 1);
  847. val.data[kPlusOne] = 0x00000001;
  848. Kernel.MinusEq(val, r2);
  849. Kernel.PlusEq(x, val);
  850. }
  851. while (x >= n)
  852. Kernel.MinusEq(x, n);
  853. }
  854. public BigInteger Multiply(BigInteger a, BigInteger b)
  855. {
  856. if (a == 0 || b == 0) return 0;
  857. if (a.length >= mod.length << 1)
  858. a %= mod;
  859. if (b.length >= mod.length << 1)
  860. b %= mod;
  861. if (a.length >= mod.length)
  862. BarrettReduction(a);
  863. if (b.length >= mod.length)
  864. BarrettReduction(b);
  865. BigInteger ret = new BigInteger(a * b);
  866. BarrettReduction(ret);
  867. return ret;
  868. }
  869. public BigInteger Difference(BigInteger a, BigInteger b)
  870. {
  871. Sign cmp = Kernel.Compare(a, b);
  872. BigInteger diff;
  873. switch (cmp)
  874. {
  875. case Sign.Zero:
  876. return 0;
  877. case Sign.Positive:
  878. diff = a - b; break;
  879. case Sign.Negative:
  880. diff = b - a; break;
  881. default:
  882. throw new Exception();
  883. }
  884. if (diff >= mod)
  885. {
  886. if (diff.length >= mod.length << 1)
  887. diff %= mod;
  888. else
  889. BarrettReduction(diff);
  890. }
  891. if (cmp == Sign.Negative)
  892. diff = mod - diff;
  893. return diff;
  894. }
  895. public BigInteger Pow(BigInteger b, BigInteger exp)
  896. {
  897. if ((mod.data[0] & 1) == 1) return OddPow(b, exp);
  898. else return EvenPow(b, exp);
  899. }
  900. public BigInteger EvenPow(BigInteger b, BigInteger exp)
  901. {
  902. BigInteger resultNum = new BigInteger((BigInteger)1, mod.length << 1);
  903. BigInteger tempNum = new BigInteger(b % mod, mod.length << 1); // ensures (tempNum * tempNum) < b^ (2k)
  904. uint totalBits = (uint)exp.BitCount();
  905. uint[] wkspace = new uint[mod.length << 1];
  906. // perform squaring and multiply exponentiation
  907. for (uint pos = 0; pos < totalBits; pos++)
  908. {
  909. if (exp.TestBit(pos))
  910. {
  911. Array.Clear(wkspace, 0, wkspace.Length);
  912. Kernel.Multiply(resultNum.data, 0, resultNum.length, tempNum.data, 0, tempNum.length, wkspace, 0);
  913. resultNum.length += tempNum.length;
  914. uint[] t = wkspace;
  915. wkspace = resultNum.data;
  916. resultNum.data = t;
  917. BarrettReduction(resultNum);
  918. }
  919. Kernel.SquarePositive(tempNum, ref wkspace);
  920. BarrettReduction(tempNum);
  921. if (tempNum == 1)
  922. {
  923. return resultNum;
  924. }
  925. }
  926. return resultNum;
  927. }
  928. private BigInteger OddPow(BigInteger b, BigInteger exp)
  929. {
  930. BigInteger resultNum = new BigInteger(Montgomery.ToMont(1, mod), mod.length << 1);
  931. BigInteger tempNum = new BigInteger(Montgomery.ToMont(b, mod), mod.length << 1); // ensures (tempNum * tempNum) < b^ (2k)
  932. uint mPrime = Montgomery.Inverse(mod.data[0]);
  933. uint totalBits = (uint)exp.BitCount();
  934. uint[] wkspace = new uint[mod.length << 1];
  935. // perform squaring and multiply exponentiation
  936. for (uint pos = 0; pos < totalBits; pos++)
  937. {
  938. if (exp.TestBit(pos))
  939. {
  940. Array.Clear(wkspace, 0, wkspace.Length);
  941. Kernel.Multiply(resultNum.data, 0, resultNum.length, tempNum.data, 0, tempNum.length, wkspace, 0);
  942. resultNum.length += tempNum.length;
  943. uint[] t = wkspace;
  944. wkspace = resultNum.data;
  945. resultNum.data = t;
  946. Montgomery.Reduce(resultNum, mod, mPrime);
  947. }
  948. Kernel.SquarePositive(tempNum, ref wkspace);
  949. Montgomery.Reduce(tempNum, mod, mPrime);
  950. }
  951. Montgomery.Reduce(resultNum, mod, mPrime);
  952. return resultNum;
  953. }
  954. #region Pow Small Base
  955. // TODO: Make tests for this, not really needed b/c prime stuff
  956. // checks it, but still would be nice
  957. #if !INSIDE_CORLIB
  958. [CLSCompliant(false)]
  959. #endif
  960. public BigInteger Pow(uint b, BigInteger exp)
  961. {
  962. // if (b != 2) {
  963. if ((mod.data[0] & 1) == 1)
  964. return OddPow(b, exp);
  965. else
  966. return EvenPow(b, exp);
  967. /* buggy in some cases (like the well tested primes)
  968. } else {
  969. if ((mod.data [0] & 1) == 1)
  970. return OddModTwoPow (exp);
  971. else
  972. return EvenModTwoPow (exp);
  973. }*/
  974. }
  975. private unsafe BigInteger OddPow(uint b, BigInteger exp)
  976. {
  977. exp.Normalize();
  978. uint[] wkspace = new uint[mod.length << 1 + 1];
  979. BigInteger resultNum = Montgomery.ToMont((BigInteger)b, this.mod);
  980. resultNum = new BigInteger(resultNum, mod.length << 1 + 1);
  981. uint mPrime = Montgomery.Inverse(mod.data[0]);
  982. uint pos = (uint)exp.BitCount() - 2;
  983. //
  984. // We know that the first itr will make the val b
  985. //
  986. do
  987. {
  988. //
  989. // r = r ^ 2 % m
  990. //
  991. Kernel.SquarePositive(resultNum, ref wkspace);
  992. resultNum = Montgomery.Reduce(resultNum, mod, mPrime);
  993. if (exp.TestBit(pos))
  994. {
  995. //
  996. // r = r * b % m
  997. //
  998. // TODO: Is Unsafe really speeding things up?
  999. fixed (uint* u = resultNum.data)
  1000. {
  1001. uint i = 0;
  1002. ulong mc = 0;
  1003. do
  1004. {
  1005. mc += (ulong)u[i] * (ulong)b;
  1006. u[i] = (uint)mc;
  1007. mc >>= 32;
  1008. } while (++i < resultNum.length);
  1009. if (resultNum.length < mod.length)
  1010. {
  1011. if (mc != 0)
  1012. {
  1013. u[i] = (uint)mc;
  1014. resultNum.length++;
  1015. while (resultNum >= mod)
  1016. Kernel.MinusEq(resultNum, mod);
  1017. }
  1018. }
  1019. else if (mc != 0)
  1020. {
  1021. //
  1022. // First, we estimate the quotient by dividing
  1023. // the first part of each of the numbers. Then
  1024. // we correct this, if necessary, with a subtraction.
  1025. //
  1026. uint cc = (uint)mc;
  1027. // We would rather have this estimate overshoot,
  1028. // so we add one to the divisor
  1029. uint divEstimate;
  1030. if (mod.data[mod.length - 1] < UInt32.MaxValue)
  1031. {
  1032. divEstimate = (uint)((((ulong)cc << 32) | (ulong)u[i - 1]) /
  1033. (mod.data[mod.length - 1] + 1));
  1034. }
  1035. else
  1036. {
  1037. // guess but don't divide by 0
  1038. divEstimate = (uint)((((ulong)cc << 32) | (ulong)u[i - 1]) /
  1039. (mod.data[mod.length - 1]));
  1040. }
  1041. uint t;
  1042. i = 0;
  1043. mc = 0;
  1044. do
  1045. {
  1046. mc += (ulong)mod.data[i] * (ulong)divEstimate;
  1047. t = u[i];
  1048. u[i] -= (uint)mc;
  1049. mc >>= 32;
  1050. if (u[i] > t) mc++;
  1051. i++;
  1052. } while (i < resultNum.length);
  1053. cc -= (uint)mc;
  1054. if (cc != 0)
  1055. {
  1056. uint sc = 0, j = 0;
  1057. uint[] s = mod.data;
  1058. do
  1059. {
  1060. uint a = s[j];
  1061. if (((a += sc) < sc) | ((u[j] -= a) > ~a)) sc = 1;
  1062. else sc = 0;
  1063. j++;
  1064. } while (j < resultNum.length);
  1065. cc -= sc;
  1066. }
  1067. while (resultNum >= mod)
  1068. Kernel.MinusEq(resultNum, mod);
  1069. }
  1070. else
  1071. {
  1072. while (resultNum >= mod)
  1073. Kernel.MinusEq(resultNum, mod);
  1074. }
  1075. }
  1076. }
  1077. } while (pos-- > 0);
  1078. resultNum = Montgomery.Reduce(resultNum, mod, mPrime);
  1079. return resultNum;
  1080. }
  1081. private unsafe BigInteger EvenPow(uint b, BigInteger exp)
  1082. {
  1083. exp.Normalize();
  1084. uint[] wkspace = new uint[mod.length << 1 + 1];
  1085. BigInteger resultNum = new BigInteger((BigInteger)b, mod.length << 1 + 1);
  1086. uint pos = (uint)exp.BitCount() - 2;
  1087. //
  1088. // We know that the first itr will make the val b
  1089. //
  1090. do
  1091. {
  1092. //
  1093. // r = r ^ 2 % m
  1094. //
  1095. Kernel.SquarePositive(resultNum, ref wkspace);
  1096. if (!(resultNum.length < mod.length))
  1097. BarrettReduction(resultNum);
  1098. if (exp.TestBit(pos))
  1099. {
  1100. //
  1101. // r = r * b % m
  1102. //
  1103. // TODO: Is Unsafe really speeding things up?
  1104. fixed (uint* u = resultNum.data)
  1105. {
  1106. uint i = 0;
  1107. ulong mc = 0;
  1108. do
  1109. {
  1110. mc += (ulong)u[i] * (ulong)b;
  1111. u[i] = (uint)mc;
  1112. mc >>= 32;
  1113. } while (++i < resultNum.length);
  1114. if (resultNum.length < mod.length)
  1115. {
  1116. if (mc != 0)
  1117. {
  1118. u[i] = (uint)mc;
  1119. resultNum.length++;
  1120. while (resultNum >= mod)
  1121. Kernel.MinusEq(resultNum, mod);
  1122. }
  1123. }
  1124. else if (mc != 0)
  1125. {
  1126. //
  1127. // First, we estimate the quotient by dividing
  1128. // the first part of each of the numbers. Then
  1129. // we correct this, if necessary, with a subtraction.
  1130. //
  1131. uint cc = (uint)mc;
  1132. // We would rather have this estimate overshoot,
  1133. // so we add one to the divisor
  1134. uint divEstimate = (uint)((((ulong)cc << 32) | (ulong)u[i - 1]) /
  1135. (mod.data[mod.length - 1] + 1));
  1136. uint t;
  1137. i = 0;
  1138. mc = 0;
  1139. do
  1140. {
  1141. mc += (ulong)mod.data[i] * (ulong)divEstimate;
  1142. t = u[i];
  1143. u[i] -= (uint)mc;
  1144. mc >>= 32;
  1145. if (u[i] > t) mc++;
  1146. i++;
  1147. } while (i < resultNum.length);
  1148. cc -= (uint)mc;
  1149. if (cc != 0)
  1150. {
  1151. uint sc = 0, j = 0;
  1152. uint[] s = mod.data;
  1153. do
  1154. {
  1155. uint a = s[j];
  1156. if (((a += sc) < sc) | ((u[j] -= a) > ~a)) sc = 1;
  1157. else sc = 0;
  1158. j++;
  1159. } while (j < resultNum.length);
  1160. cc -= sc;
  1161. }
  1162. while (resultNum >= mod)
  1163. Kernel.MinusEq(resultNum, mod);
  1164. }
  1165. else
  1166. {
  1167. while (resultNum >= mod)
  1168. Kernel.MinusEq(resultNum, mod);
  1169. }
  1170. }
  1171. }
  1172. } while (pos-- > 0);
  1173. return resultNum;
  1174. }
  1175. /* known to be buggy in some cases
  1176. private unsafe BigInteger EvenModTwoPow (BigInteger exp)
  1177. {
  1178. exp.Normalize ();
  1179. uint [] wkspace = new uint [mod.length << 1 + 1];
  1180. BigInteger resultNum = new BigInteger (2, mod.length << 1 +1);
  1181. uint value = exp.data [exp.length - 1];
  1182. uint mask = 0x80000000;
  1183. // Find the first bit of the exponent
  1184. while ((value & mask) == 0)
  1185. mask >>= 1;
  1186. //
  1187. // We know that the first itr will make the val 2,
  1188. // so eat one bit of the exponent
  1189. //
  1190. mask >>= 1;
  1191. uint wPos = exp.length - 1;
  1192. do {
  1193. value = exp.data [wPos];
  1194. do {
  1195. Kernel.SquarePositive (resultNum, ref wkspace);
  1196. if (resultNum.length >= mod.length)
  1197. BarrettReduction (resultNum);
  1198. if ((value & mask) != 0) {
  1199. //
  1200. // resultNum = (resultNum * 2) % mod
  1201. //
  1202. fixed (uint* u = resultNum.data) {
  1203. //
  1204. // Double
  1205. //
  1206. uint* uu = u;
  1207. uint* uuE = u + resultNum.length;
  1208. uint x, carry = 0;
  1209. while (uu < uuE) {
  1210. x = *uu;
  1211. *uu = (x << 1) | carry;
  1212. carry = x >> (32 - 1);
  1213. uu++;
  1214. }
  1215. // subtraction inlined because we know it is square
  1216. if (carry != 0 || resultNum >= mod) {
  1217. uu = u;
  1218. uint c = 0;
  1219. uint [] s = mod.data;
  1220. uint i = 0;
  1221. do {
  1222. uint a = s [i];
  1223. if (((a += c) < c) | ((* (uu++) -= a) > ~a))
  1224. c = 1;
  1225. else
  1226. c = 0;
  1227. i++;
  1228. } while (uu < uuE);
  1229. }
  1230. }
  1231. }
  1232. } while ((mask >>= 1) > 0);
  1233. mask = 0x80000000;
  1234. } while (wPos-- > 0);
  1235. return resultNum;
  1236. }
  1237. private unsafe BigInteger OddModTwoPow (BigInteger exp)
  1238. {
  1239. uint [] wkspace = new uint [mod.length << 1 + 1];
  1240. BigInteger resultNum = Montgomery.ToMont ((BigInteger)2, this.mod);
  1241. resultNum = new BigInteger (resultNum, mod.length << 1 +1);
  1242. uint mPrime = Montgomery.Inverse (mod.data [0]);
  1243. //
  1244. // TODO: eat small bits, the ones we can do with no modular reduction
  1245. //
  1246. uint pos = (uint)exp.BitCount () - 2;
  1247. do {
  1248. Kernel.SquarePositive (resultNum, ref wkspace);
  1249. resultNum = Montgomery.Reduce (resultNum, mod, mPrime);
  1250. if (exp.TestBit (pos)) {
  1251. //
  1252. // resultNum = (resultNum * 2) % mod
  1253. //
  1254. fixed (uint* u = resultNum.data) {
  1255. //
  1256. // Double
  1257. //
  1258. uint* uu = u;
  1259. uint* uuE = u + resultNum.length;
  1260. uint x, carry = 0;
  1261. while (uu < uuE) {
  1262. x = *uu;
  1263. *uu = (x << 1) | carry;
  1264. carry = x >> (32 - 1);
  1265. uu++;
  1266. }
  1267. // subtraction inlined because we know it is square
  1268. if (carry != 0 || resultNum >= mod) {
  1269. fixed (uint* s = mod.data) {
  1270. uu = u;
  1271. uint c = 0;
  1272. uint* ss = s;
  1273. do {
  1274. uint a = *ss++;
  1275. if (((a += c) < c) | ((* (uu++) -= a) > ~a))
  1276. c = 1;
  1277. else
  1278. c = 0;
  1279. } while (uu < uuE);
  1280. }
  1281. }
  1282. }
  1283. }
  1284. } while (pos-- > 0);
  1285. resultNum = Montgomery.Reduce (resultNum, mod, mPrime);
  1286. return resultNum;
  1287. }
  1288. */
  1289. #endregion
  1290. }
  1291. internal sealed class Montgomery
  1292. {
  1293. private Montgomery()
  1294. {
  1295. }
  1296. public static uint Inverse(uint n)
  1297. {
  1298. uint y = n, z;
  1299. while ((z = n * y) != 1)
  1300. y *= 2 - z;
  1301. return (uint)-y;
  1302. }
  1303. public static BigInteger ToMont(BigInteger n, BigInteger m)
  1304. {
  1305. n.Normalize(); m.Normalize();
  1306. n <<= (int)m.length * 32;
  1307. n %= m;
  1308. return n;
  1309. }
  1310. public static unsafe BigInteger Reduce(BigInteger n, BigInteger m, uint mPrime)
  1311. {
  1312. BigInteger A = n;
  1313. fixed (uint* a = A.data, mm = m.data)
  1314. {
  1315. for (uint i = 0; i < m.length; i++)
  1316. {
  1317. // The mod here is taken care of by the CPU,
  1318. // since the multiply will overflow.
  1319. uint u_i = a[0] * mPrime /* % 2^32 */;
  1320. //
  1321. // A += u_i * m;
  1322. // A >>= 32
  1323. //
  1324. // mP = Position in mod
  1325. // aSP = the source of bits from a
  1326. // aDP = destination for bits
  1327. uint* mP = mm, aSP = a, aDP = a;
  1328. ulong c = (ulong)u_i * ((ulong)*(mP++)) + *(aSP++);
  1329. c >>= 32;
  1330. uint j = 1;
  1331. // Multiply and add
  1332. for (; j < m.length; j++)
  1333. {
  1334. c += (ulong)u_i * (ulong)*(mP++) + *(aSP++);
  1335. *(aDP++) = (uint)c;
  1336. c >>= 32;
  1337. }
  1338. // Account for carry
  1339. // TODO: use a better loop here, we dont need the ulong stuff
  1340. for (; j < A.length; j++)
  1341. {
  1342. c += *(aSP++);
  1343. *(aDP++) = (uint)c;
  1344. c >>= 32;
  1345. if (c == 0) { j++; break; }
  1346. }
  1347. // Copy the rest
  1348. for (; j < A.length; j++)
  1349. {
  1350. *(aDP++) = *(aSP++);
  1351. }
  1352. *(aDP++) = (uint)c;
  1353. }
  1354. while (A.length > 1 && a[A.length - 1] == 0) A.length--;
  1355. }
  1356. if (A >= m) Kernel.MinusEq(A, m);
  1357. return A;
  1358. }
  1359. #if _NOT_USED_
  1360. public static BigInteger Reduce (BigInteger n, BigInteger m)
  1361. {
  1362. return Reduce (n, m, Inverse (m.data [0]));
  1363. }
  1364. #endif
  1365. }
  1366. /// <summary>
  1367. /// Low level functions for the BigInteger
  1368. /// </summary>
  1369. private sealed class Kernel
  1370. {
  1371. #region Addition/Subtraction
  1372. /// <summary>
  1373. /// Adds two numbers with the same sign.
  1374. /// </summary>
  1375. /// <param name="bi1">A BigInteger</param>
  1376. /// <param name="bi2">A BigInteger</param>
  1377. /// <returns>bi1 + bi2</returns>
  1378. public static BigInteger AddSameSign(BigInteger bi1, BigInteger bi2)
  1379. {
  1380. uint[] x, y;
  1381. uint yMax, xMax, i = 0;
  1382. // x should be bigger
  1383. if (bi1.length < bi2.length)
  1384. {
  1385. x = bi2.data;
  1386. xMax = bi2.length;
  1387. y = bi1.data;
  1388. yMax = bi1.length;
  1389. }
  1390. else
  1391. {
  1392. x = bi1.data;
  1393. xMax = bi1.length;
  1394. y = bi2.data;
  1395. yMax = bi2.length;
  1396. }
  1397. BigInteger result = new BigInteger(Sign.Positive, xMax + 1);
  1398. uint[] r = result.data;
  1399. ulong sum = 0;
  1400. // Add common parts of both numbers
  1401. do
  1402. {
  1403. sum = ((ulong)x[i]) + ((ulong)y[i]) + sum;
  1404. r[i] = (uint)sum;
  1405. sum >>= 32;
  1406. } while (++i < yMax);
  1407. // Copy remainder of longer number while carry propagation is required
  1408. bool carry = (sum != 0);
  1409. if (carry)
  1410. {
  1411. if (i < xMax)
  1412. {
  1413. do
  1414. carry = ((r[i] = x[i] + 1) == 0);
  1415. while (++i < xMax && carry);
  1416. }
  1417. if (carry)
  1418. {
  1419. r[i] = 1;
  1420. result.length = ++i;
  1421. return result;
  1422. }
  1423. }
  1424. // Copy the rest
  1425. if (i < xMax)
  1426. {
  1427. do
  1428. r[i] = x[i];
  1429. while (++i < xMax);
  1430. }
  1431. result.Normalize();
  1432. return result;
  1433. }
  1434. public static BigInteger Subtract(BigInteger big, BigInteger small)
  1435. {
  1436. BigInteger result = new BigInteger(Sign.Positive, big.length);
  1437. uint[] r = result.data, b = big.data, s = small.data;
  1438. uint i = 0, c = 0;
  1439. do
  1440. {
  1441. uint x = s[i];
  1442. if (((x += c) < c) | ((r[i] = b[i] - x) > ~x))
  1443. c = 1;
  1444. else
  1445. c = 0;
  1446. } while (++i < small.length);
  1447. if (i == big.length) goto fixup;
  1448. if (c == 1)
  1449. {
  1450. do
  1451. r[i] = b[i] - 1;
  1452. while (b[i++] == 0 && i < big.length);
  1453. if (i == big.length) goto fixup;
  1454. }
  1455. do
  1456. r[i] = b[i];
  1457. while (++i < big.length);
  1458. fixup:
  1459. result.Normalize();
  1460. return result;
  1461. }
  1462. public static void MinusEq(BigInteger big, BigInteger small)
  1463. {
  1464. uint[] b = big.data, s = small.data;
  1465. uint i = 0, c = 0;
  1466. do
  1467. {
  1468. uint x = s[i];
  1469. if (((x += c) < c) | ((b[i] -= x) > ~x))
  1470. c = 1;
  1471. else
  1472. c = 0;
  1473. } while (++i < small.length);
  1474. if (i == big.length) goto fixup;
  1475. if (c == 1)
  1476. {
  1477. do
  1478. b[i]--;
  1479. while (b[i++] == 0 && i < big.length);
  1480. }
  1481. fixup:
  1482. // Normalize length
  1483. while (big.length > 0 && big.data[big.length - 1] == 0) big.length--;
  1484. // Check for zero
  1485. if (big.length == 0)
  1486. big.length++;
  1487. }
  1488. public static void PlusEq(BigInteger bi1, BigInteger bi2)
  1489. {
  1490. uint[] x, y;
  1491. uint yMax, xMax, i = 0;
  1492. bool flag = false;
  1493. // x should be bigger
  1494. if (bi1.length < bi2.length)
  1495. {
  1496. flag = true;
  1497. x = bi2.data;
  1498. xMax = bi2.length;
  1499. y = bi1.data;
  1500. yMax = bi1.length;
  1501. }
  1502. else
  1503. {
  1504. x = bi1.data;
  1505. xMax = bi1.length;
  1506. y = bi2.data;
  1507. yMax = bi2.length;
  1508. }
  1509. uint[] r = bi1.data;
  1510. ulong sum = 0;
  1511. // Add common parts of both numbers
  1512. do
  1513. {
  1514. sum += ((ulong)x[i]) + ((ulong)y[i]);
  1515. r[i] = (uint)sum;
  1516. sum >>= 32;
  1517. } while (++i < yMax);
  1518. // Copy remainder of longer number while carry propagation is required
  1519. bool carry = (sum != 0);
  1520. if (carry)
  1521. {
  1522. if (i < xMax)
  1523. {
  1524. do
  1525. carry = ((r[i] = x[i] + 1) == 0);
  1526. while (++i < xMax && carry);
  1527. }
  1528. if (carry)
  1529. {
  1530. r[i] = 1;
  1531. bi1.length = ++i;
  1532. return;
  1533. }
  1534. }
  1535. // Copy the rest
  1536. if (flag && i < xMax - 1)
  1537. {
  1538. do
  1539. r[i] = x[i];
  1540. while (++i < xMax);
  1541. }
  1542. bi1.length = xMax + 1;
  1543. bi1.Normalize();
  1544. }
  1545. #endregion
  1546. #region Compare
  1547. /// <summary>
  1548. /// Compares two BigInteger
  1549. /// </summary>
  1550. /// <param name="bi1">A BigInteger</param>
  1551. /// <param name="bi2">A BigInteger</param>
  1552. /// <returns>The sign of bi1 - bi2</returns>
  1553. public static Sign Compare(BigInteger bi1, BigInteger bi2)
  1554. {
  1555. //
  1556. // Step 1. Compare the lengths
  1557. //
  1558. uint l1 = bi1.length, l2 = bi2.length;
  1559. while (l1 > 0 && bi1.data[l1 - 1] == 0) l1--;
  1560. while (l2 > 0 && bi2.data[l2 - 1] == 0) l2--;
  1561. if (l1 == 0 && l2 == 0) return Sign.Zero;
  1562. // bi1 len < bi2 len
  1563. if (l1 < l2) return Sign.Negative;
  1564. // bi1 len > bi2 len
  1565. else if (l1 > l2) return Sign.Positive;
  1566. //
  1567. // Step 2. Compare the bits
  1568. //
  1569. uint pos = l1 - 1;
  1570. while (pos != 0 && bi1.data[pos] == bi2.data[pos]) pos--;
  1571. if (bi1.data[pos] < bi2.data[pos])
  1572. return Sign.Negative;
  1573. else if (bi1.data[pos] > bi2.data[pos])
  1574. return Sign.Positive;
  1575. else
  1576. return Sign.Zero;
  1577. }
  1578. #endregion
  1579. #region Division
  1580. #region Dword
  1581. /// <summary>
  1582. /// Performs n / d and n % d in one operation.
  1583. /// </summary>
  1584. /// <param name="n">A BigInteger, upon exit this will hold n / d</param>
  1585. /// <param name="d">The divisor</param>
  1586. /// <returns>n % d</returns>
  1587. public static uint SingleByteDivideInPlace(BigInteger n, uint d)
  1588. {
  1589. ulong r = 0;
  1590. uint i = n.length;
  1591. while (i-- > 0)
  1592. {
  1593. r <<= 32;
  1594. r |= n.data[i];
  1595. n.data[i] = (uint)(r / d);
  1596. r %= d;
  1597. }
  1598. n.Normalize();
  1599. return (uint)r;
  1600. }
  1601. public static uint DwordMod(BigInteger n, uint d)
  1602. {
  1603. ulong r = 0;
  1604. uint i = n.length;
  1605. while (i-- > 0)
  1606. {
  1607. r <<= 32;
  1608. r |= n.data[i];
  1609. r %= d;
  1610. }
  1611. return (uint)r;
  1612. }
  1613. public static BigInteger DwordDiv(BigInteger n, uint d)
  1614. {
  1615. BigInteger ret = new BigInteger(Sign.Positive, n.length);
  1616. ulong r = 0;
  1617. uint i = n.length;
  1618. while (i-- > 0)
  1619. {
  1620. r <<= 32;
  1621. r |= n.data[i];
  1622. ret.data[i] = (uint)(r / d);
  1623. r %= d;
  1624. }
  1625. ret.Normalize();
  1626. return ret;
  1627. }
  1628. public static BigInteger[] DwordDivMod(BigInteger n, uint d)
  1629. {
  1630. BigInteger ret = new BigInteger(Sign.Positive, n.length);
  1631. ulong r = 0;
  1632. uint i = n.length;
  1633. while (i-- > 0)
  1634. {
  1635. r <<= 32;
  1636. r |= n.data[i];
  1637. ret.data[i] = (uint)(r / d);
  1638. r %= d;
  1639. }
  1640. ret.Normalize();
  1641. BigInteger rem = (uint)r;
  1642. return new BigInteger[] { ret, rem };
  1643. }
  1644. #endregion
  1645. #region BigNum
  1646. public static BigInteger[] multiByteDivide(BigInteger bi1, BigInteger bi2)
  1647. {
  1648. if (Kernel.Compare(bi1, bi2) == Sign.Negative)
  1649. return new BigInteger[2] { 0, new BigInteger(bi1) };
  1650. bi1.Normalize(); bi2.Normalize();
  1651. if (bi2.length == 1)
  1652. return DwordDivMod(bi1, bi2.data[0]);
  1653. uint remainderLen = bi1.length + 1;
  1654. int divisorLen = (int)bi2.length + 1;
  1655. uint mask = 0x80000000;
  1656. uint val = bi2.data[bi2.length - 1];
  1657. int shift = 0;
  1658. int resultPos = (int)bi1.length - (int)bi2.length;
  1659. while (mask != 0 && (val & mask) == 0)
  1660. {
  1661. shift++; mask >>= 1;
  1662. }
  1663. BigInteger quot = new BigInteger(Sign.Positive, bi1.length - bi2.length + 1);
  1664. BigInteger rem = (bi1 << shift);
  1665. uint[] remainder = rem.data;
  1666. bi2 = bi2 << shift;
  1667. int j = (int)(remainderLen - bi2.length);
  1668. int pos = (int)remainderLen - 1;
  1669. uint firstDivisorByte = bi2.data[bi2.length - 1];
  1670. ulong secondDivisorByte = bi2.data[bi2.length - 2];
  1671. while (j > 0)
  1672. {
  1673. ulong dividend = ((ulong)remainder[pos] << 32) + (ulong)remainder[pos - 1];
  1674. ulong q_hat = dividend / (ulong)firstDivisorByte;
  1675. ulong r_hat = dividend % (ulong)firstDivisorByte;
  1676. do
  1677. {
  1678. if (q_hat == 0x100000000 ||
  1679. (q_hat * secondDivisorByte) > ((r_hat << 32) + remainder[pos - 2]))
  1680. {
  1681. q_hat--;
  1682. r_hat += (ulong)firstDivisorByte;
  1683. if (r_hat < 0x100000000)
  1684. continue;
  1685. }
  1686. break;
  1687. } while (true);
  1688. //
  1689. // At this point, q_hat is either exact, or one too large
  1690. // (more likely to be exact) so, we attempt to multiply the
  1691. // divisor by q_hat, if we get a borrow, we just subtract
  1692. // one from q_hat and add the divisor back.
  1693. //
  1694. uint t;
  1695. uint dPos = 0;
  1696. int nPos = pos - divisorLen + 1;
  1697. ulong mc = 0;
  1698. uint uint_q_hat = (uint)q_hat;
  1699. do
  1700. {
  1701. mc += (ulong)bi2.data[dPos] * (ulong)uint_q_hat;
  1702. t = remainder[nPos];
  1703. remainder[nPos] -= (uint)mc;
  1704. mc >>= 32;
  1705. if (remainder[nPos] > t) mc++;
  1706. dPos++; nPos++;
  1707. } while (dPos < divisorLen);
  1708. nPos = pos - divisorLen + 1;
  1709. dPos = 0;
  1710. // Overestimate
  1711. if (mc != 0)
  1712. {
  1713. uint_q_hat--;
  1714. ulong sum = 0;
  1715. do
  1716. {
  1717. sum = ((ulong)remainder[nPos]) + ((ulong)bi2.data[dPos]) + sum;
  1718. remainder[nPos] = (uint)sum;
  1719. sum >>= 32;
  1720. dPos++; nPos++;
  1721. } while (dPos < divisorLen);
  1722. }
  1723. quot.data[resultPos--] = (uint)uint_q_hat;
  1724. pos--;
  1725. j--;
  1726. }
  1727. quot.Normalize();
  1728. rem.Normalize();
  1729. BigInteger[] ret = new BigInteger[2] { quot, rem };
  1730. if (shift != 0)
  1731. ret[1] >>= shift;
  1732. return ret;
  1733. }
  1734. #endregion
  1735. #endregion
  1736. #region Shift
  1737. public static BigInteger LeftShift(BigInteger bi, int n)
  1738. {
  1739. if (n == 0) return new BigInteger(bi, bi.length + 1);
  1740. int w = n >> 5;
  1741. n &= ((1 << 5) - 1);
  1742. BigInteger ret = new BigInteger(Sign.Positive, bi.length + 1 + (uint)w);
  1743. uint i = 0, l = bi.length;
  1744. if (n != 0)
  1745. {
  1746. uint x, carry = 0;
  1747. while (i < l)
  1748. {
  1749. x = bi.data[i];
  1750. ret.data[i + w] = (x << n) | carry;
  1751. carry = x >> (32 - n);
  1752. i++;
  1753. }
  1754. ret.data[i + w] = carry;
  1755. }
  1756. else
  1757. {
  1758. while (i < l)
  1759. {
  1760. ret.data[i + w] = bi.data[i];
  1761. i++;
  1762. }
  1763. }
  1764. ret.Normalize();
  1765. return ret;
  1766. }
  1767. public static BigInteger RightShift(BigInteger bi, int n)
  1768. {
  1769. if (n == 0) return new BigInteger(bi);
  1770. int w = n >> 5;
  1771. int s = n & ((1 << 5) - 1);
  1772. BigInteger ret = new BigInteger(Sign.Positive, bi.length - (uint)w + 1);
  1773. uint l = (uint)ret.data.Length - 1;
  1774. if (s != 0)
  1775. {
  1776. uint x, carry = 0;
  1777. while (l-- > 0)
  1778. {
  1779. x = bi.data[l + w];
  1780. ret.data[l] = (x >> n) | carry;
  1781. carry = x << (32 - n);
  1782. }
  1783. }
  1784. else
  1785. {
  1786. while (l-- > 0)
  1787. ret.data[l] = bi.data[l + w];
  1788. }
  1789. ret.Normalize();
  1790. return ret;
  1791. }
  1792. #endregion
  1793. #region Multiply
  1794. public static BigInteger MultiplyByDword(BigInteger n, uint f)
  1795. {
  1796. BigInteger ret = new BigInteger(Sign.Positive, n.length + 1);
  1797. uint i = 0;
  1798. ulong c = 0;
  1799. do
  1800. {
  1801. c += (ulong)n.data[i] * (ulong)f;
  1802. ret.data[i] = (uint)c;
  1803. c >>= 32;
  1804. } while (++i < n.length);
  1805. ret.data[i] = (uint)c;
  1806. ret.Normalize();
  1807. return ret;
  1808. }
  1809. /// <summary>
  1810. /// Multiplies the data in x [xOffset:xOffset+xLen] by
  1811. /// y [yOffset:yOffset+yLen] and puts it into
  1812. /// d [dOffset:dOffset+xLen+yLen].
  1813. /// </summary>
  1814. /// <remarks>
  1815. /// This code is unsafe! It is the caller's responsibility to make
  1816. /// sure that it is safe to access x [xOffset:xOffset+xLen],
  1817. /// y [yOffset:yOffset+yLen], and d [dOffset:dOffset+xLen+yLen].
  1818. /// </remarks>
  1819. public static unsafe void Multiply(uint[] x, uint xOffset, uint xLen, uint[] y, uint yOffset, uint yLen, uint[] d, uint dOffset)
  1820. {
  1821. fixed (uint* xx = x, yy = y, dd = d)
  1822. {
  1823. uint* xP = xx + xOffset,
  1824. xE = xP + xLen,
  1825. yB = yy + yOffset,
  1826. yE = yB + yLen,
  1827. dB = dd + dOffset;
  1828. for (; xP < xE; xP++, dB++)
  1829. {
  1830. if (*xP == 0) continue;
  1831. ulong mcarry = 0;
  1832. uint* dP = dB;
  1833. for (uint* yP = yB; yP < yE; yP++, dP++)
  1834. {
  1835. mcarry += ((ulong)*xP * (ulong)*yP) + (ulong)*dP;
  1836. *dP = (uint)mcarry;
  1837. mcarry >>= 32;
  1838. }
  1839. if (mcarry != 0)
  1840. *dP = (uint)mcarry;
  1841. }
  1842. }
  1843. }
  1844. /// <summary>
  1845. /// Multiplies the data in x [xOffset:xOffset+xLen] by
  1846. /// y [yOffset:yOffset+yLen] and puts the low mod words into
  1847. /// d [dOffset:dOffset+mod].
  1848. /// </summary>
  1849. /// <remarks>
  1850. /// This code is unsafe! It is the caller's responsibility to make
  1851. /// sure that it is safe to access x [xOffset:xOffset+xLen],
  1852. /// y [yOffset:yOffset+yLen], and d [dOffset:dOffset+mod].
  1853. /// </remarks>
  1854. public static unsafe void MultiplyMod2p32pmod(uint[] x, int xOffset, int xLen, uint[] y, int yOffest, int yLen, uint[] d, int dOffset, int mod)
  1855. {
  1856. fixed (uint* xx = x, yy = y, dd = d)
  1857. {
  1858. uint* xP = xx + xOffset,
  1859. xE = xP + xLen,
  1860. yB = yy + yOffest,
  1861. yE = yB + yLen,
  1862. dB = dd + dOffset,
  1863. dE = dB + mod;
  1864. for (; xP < xE; xP++, dB++)
  1865. {
  1866. if (*xP == 0) continue;
  1867. ulong mcarry = 0;
  1868. uint* dP = dB;
  1869. for (uint* yP = yB; yP < yE && dP < dE; yP++, dP++)
  1870. {
  1871. mcarry += ((ulong)*xP * (ulong)*yP) + (ulong)*dP;
  1872. *dP = (uint)mcarry;
  1873. mcarry >>= 32;
  1874. }
  1875. if (mcarry != 0 && dP < dE)
  1876. *dP = (uint)mcarry;
  1877. }
  1878. }
  1879. }
  1880. public static unsafe void SquarePositive(BigInteger bi, ref uint[] wkSpace)
  1881. {
  1882. uint[] t = wkSpace;
  1883. wkSpace = bi.data;
  1884. uint[] d = bi.data;
  1885. uint dl = bi.length;
  1886. bi.data = t;
  1887. fixed (uint* dd = d, tt = t)
  1888. {
  1889. uint* ttE = tt + t.Length;
  1890. // Clear the dest
  1891. for (uint* ttt = tt; ttt < ttE; ttt++)
  1892. *ttt = 0;
  1893. uint* dP = dd, tP = tt;
  1894. for (uint i = 0; i < dl; i++, dP++)
  1895. {
  1896. if (*dP == 0)
  1897. continue;
  1898. ulong mcarry = 0;
  1899. uint bi1val = *dP;
  1900. uint* dP2 = dP + 1, tP2 = tP + 2 * i + 1;
  1901. for (uint j = i + 1; j < dl; j++, tP2++, dP2++)
  1902. {
  1903. // k = i + j
  1904. mcarry += ((ulong)bi1val * (ulong)*dP2) + *tP2;
  1905. *tP2 = (uint)mcarry;
  1906. mcarry >>= 32;
  1907. }
  1908. if (mcarry != 0)
  1909. *tP2 = (uint)mcarry;
  1910. }
  1911. // Double t. Inlined for speed.
  1912. tP = tt;
  1913. uint x, carry = 0;
  1914. while (tP < ttE)
  1915. {
  1916. x = *tP;
  1917. *tP = (x << 1) | carry;
  1918. carry = x >> (32 - 1);
  1919. tP++;
  1920. }
  1921. if (carry != 0) *tP = carry;
  1922. // Add in the diagnals
  1923. dP = dd;
  1924. tP = tt;
  1925. for (uint* dE = dP + dl; (dP < dE); dP++, tP++)
  1926. {
  1927. ulong val = (ulong)*dP * (ulong)*dP + *tP;
  1928. *tP = (uint)val;
  1929. val >>= 32;
  1930. *(++tP) += (uint)val;
  1931. if (*tP < (uint)val)
  1932. {
  1933. uint* tP3 = tP;
  1934. // Account for the first carry
  1935. (*++tP3)++;
  1936. // Keep adding until no carry
  1937. while ((*tP3++) == 0)
  1938. (*tP3)++;
  1939. }
  1940. }
  1941. bi.length <<= 1;
  1942. // Normalize length
  1943. while (tt[bi.length - 1] == 0 && bi.length > 1) bi.length--;
  1944. }
  1945. }
  1946. /*
  1947. * Never called in BigInteger (and part of a private class)
  1948. * public static bool Double (uint [] u, int l)
  1949. {
  1950. uint x, carry = 0;
  1951. uint i = 0;
  1952. while (i < l) {
  1953. x = u [i];
  1954. u [i] = (x << 1) | carry;
  1955. carry = x >> (32 - 1);
  1956. i++;
  1957. }
  1958. if (carry != 0) u [l] = carry;
  1959. return carry != 0;
  1960. }*/
  1961. #endregion
  1962. #region Number Theory
  1963. public static BigInteger gcd(BigInteger a, BigInteger b)
  1964. {
  1965. BigInteger x = a;
  1966. BigInteger y = b;
  1967. BigInteger g = y;
  1968. while (x.length > 1)
  1969. {
  1970. g = x;
  1971. x = y % x;
  1972. y = g;
  1973. }
  1974. if (x == 0) return g;
  1975. // TODO: should we have something here if we can convert to long?
  1976. //
  1977. // Now we can just do it with single precision. I am using the binary gcd method,
  1978. // as it should be faster.
  1979. //
  1980. uint yy = x.data[0];
  1981. uint xx = y % yy;
  1982. int t = 0;
  1983. while (((xx | yy) & 1) == 0)
  1984. {
  1985. xx >>= 1; yy >>= 1; t++;
  1986. }
  1987. while (xx != 0)
  1988. {
  1989. while ((xx & 1) == 0) xx >>= 1;
  1990. while ((yy & 1) == 0) yy >>= 1;
  1991. if (xx >= yy)
  1992. xx = (xx - yy) >> 1;
  1993. else
  1994. yy = (yy - xx) >> 1;
  1995. }
  1996. return yy << t;
  1997. }
  1998. public static uint modInverse(BigInteger bi, uint modulus)
  1999. {
  2000. uint a = modulus, b = bi % modulus;
  2001. uint p0 = 0, p1 = 1;
  2002. while (b != 0)
  2003. {
  2004. if (b == 1)
  2005. return p1;
  2006. p0 += (a / b) * p1;
  2007. a %= b;
  2008. if (a == 0)
  2009. break;
  2010. if (a == 1)
  2011. return modulus - p0;
  2012. p1 += (b / a) * p0;
  2013. b %= a;
  2014. }
  2015. return 0;
  2016. }
  2017. public static BigInteger modInverse(BigInteger bi, BigInteger modulus)
  2018. {
  2019. if (modulus.length == 1) return modInverse(bi, modulus.data[0]);
  2020. BigInteger[] p = { 0, 1 };
  2021. BigInteger[] q = new BigInteger[2]; // quotients
  2022. BigInteger[] r = { 0, 0 }; // remainders
  2023. int step = 0;
  2024. BigInteger a = modulus;
  2025. BigInteger b = bi;
  2026. ModulusRing mr = new ModulusRing(modulus);
  2027. while (b != 0)
  2028. {
  2029. if (step > 1)
  2030. {
  2031. BigInteger pval = mr.Difference(p[0], p[1] * q[0]);
  2032. p[0] = p[1]; p[1] = pval;
  2033. }
  2034. BigInteger[] divret = multiByteDivide(a, b);
  2035. q[0] = q[1]; q[1] = divret[0];
  2036. r[0] = r[1]; r[1] = divret[1];
  2037. a = b;
  2038. b = divret[1];
  2039. step++;
  2040. }
  2041. if (r[0] != 1)
  2042. throw (new ArithmeticException("No inverse!"));
  2043. return mr.Difference(p[0], p[1] * q[0]);
  2044. }
  2045. #endregion
  2046. }
  2047. }
  2048. }