PageRenderTime 65ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/SSISSSHFTP/SSISSharpSSHFTP/SharpSSH/BigInteger.cs

#
C# | 2535 lines | 1641 code | 467 blank | 427 comment | 373 complexity | 5f517595d409cb5c07117a2c18fbcb26 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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 = res…

Large files files are truncated, but you can click here to view the full file