PageRenderTime 40ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/otp.net/Otp/Erlang/BigInteger.cs

https://github.com/bmizerany/jungerl
C# | 3333 lines | 1919 code | 721 blank | 693 comment | 674 complexity | 75c7f6133aee4dce19b6a0a13598d502 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, AGPL-1.0
  1. //************************************************************************************
  2. // BigInteger Class Version 1.03
  3. //
  4. // Copyright (c) 2002 Chew Keong TAN
  5. // All rights reserved.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a
  8. // copy of this software and associated documentation files (the
  9. // "Software"), to deal in the Software without restriction, including
  10. // without limitation the rights to use, copy, modify, merge, publish,
  11. // distribute, and/or sell copies of the Software, and to permit persons
  12. // to whom the Software is furnished to do so, provided that the above
  13. // copyright notice(s) and this permission notice appear in all copies of
  14. // the Software and that both the above copyright notice(s) and this
  15. // permission notice appear in supporting documentation.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  18. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
  20. // OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  21. // HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
  22. // INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
  23. // FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  24. // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  25. // WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  26. //
  27. //
  28. // Disclaimer
  29. // ----------
  30. // Although reasonable care has been taken to ensure the correctness of this
  31. // implementation, this code should never be used in any application without
  32. // proper verification and testing. I disclaim all liability and responsibility
  33. // to any person or entity with respect to any loss or damage caused, or alleged
  34. // to be caused, directly or indirectly, by the use of this BigInteger class.
  35. //
  36. // Comments, bugs and suggestions to
  37. // (http://www.codeproject.com/csharp/biginteger.asp)
  38. //
  39. //
  40. // Overloaded Operators +, -, *, /, %, >>, <<, ==, !=, >, <, >=, <=, &, |, ^, ++, --, ~
  41. //
  42. // Features
  43. // --------
  44. // 1) Arithmetic operations involving large signed integers (2's complement).
  45. // 2) Primality test using Fermat little theorm, Rabin Miller's method,
  46. // Solovay Strassen's method and Lucas strong pseudoprime.
  47. // 3) Modulo exponential with Barrett's reduction.
  48. // 4) Inverse modulo.
  49. // 5) Pseudo prime generation.
  50. // 6) Co-prime generation.
  51. //
  52. //
  53. // Known Problem
  54. // -------------
  55. // This pseudoprime passes my implementation of
  56. // primality test but failed in JDK's isProbablePrime test.
  57. //
  58. // byte[] pseudoPrime1 = { (byte)0x00,
  59. // (byte)0x85, (byte)0x84, (byte)0x64, (byte)0xFD, (byte)0x70, (byte)0x6A,
  60. // (byte)0x9F, (byte)0xF0, (byte)0x94, (byte)0x0C, (byte)0x3E, (byte)0x2C,
  61. // (byte)0x74, (byte)0x34, (byte)0x05, (byte)0xC9, (byte)0x55, (byte)0xB3,
  62. // (byte)0x85, (byte)0x32, (byte)0x98, (byte)0x71, (byte)0xF9, (byte)0x41,
  63. // (byte)0x21, (byte)0x5F, (byte)0x02, (byte)0x9E, (byte)0xEA, (byte)0x56,
  64. // (byte)0x8D, (byte)0x8C, (byte)0x44, (byte)0xCC, (byte)0xEE, (byte)0xEE,
  65. // (byte)0x3D, (byte)0x2C, (byte)0x9D, (byte)0x2C, (byte)0x12, (byte)0x41,
  66. // (byte)0x1E, (byte)0xF1, (byte)0xC5, (byte)0x32, (byte)0xC3, (byte)0xAA,
  67. // (byte)0x31, (byte)0x4A, (byte)0x52, (byte)0xD8, (byte)0xE8, (byte)0xAF,
  68. // (byte)0x42, (byte)0xF4, (byte)0x72, (byte)0xA1, (byte)0x2A, (byte)0x0D,
  69. // (byte)0x97, (byte)0xB1, (byte)0x31, (byte)0xB3,
  70. // };
  71. //
  72. //
  73. // Change Log
  74. // ----------
  75. // 1) September 23, 2002 (Version 1.03)
  76. // - Fixed operator- to give correct data length.
  77. // - Added Lucas sequence generation.
  78. // - Added Strong Lucas Primality test.
  79. // - Added integer square root method.
  80. // - Added setBit/unsetBit methods.
  81. // - New isProbablePrime() method which do not require the
  82. // confident parameter.
  83. //
  84. // 2) August 29, 2002 (Version 1.02)
  85. // - Fixed bug in the exponentiation of negative numbers.
  86. // - Faster modular exponentiation using Barrett reduction.
  87. // - Added getBytes() method.
  88. // - Fixed bug in ToHexString method.
  89. // - Added overloading of ^ operator.
  90. // - Faster computation of Jacobi symbol.
  91. //
  92. // 3) August 19, 2002 (Version 1.01)
  93. // - Big integer is stored and manipulated as unsigned integers (4 bytes) instead of
  94. // individual bytes this gives significant performance improvement.
  95. // - Updated Fermat's Little Theorem test to use a^(p-1) mod p = 1
  96. // - Added isProbablePrime method.
  97. // - Updated documentation.
  98. //
  99. // 4) August 9, 2002 (Version 1.0)
  100. // - Initial Release.
  101. //
  102. //
  103. // References
  104. // [1] D. E. Knuth, "Seminumerical Algorithms", The Art of Computer Programming Vol. 2,
  105. // 3rd Edition, Addison-Wesley, 1998.
  106. //
  107. // [2] K. H. Rosen, "Elementary Number Theory and Its Applications", 3rd Ed,
  108. // Addison-Wesley, 1993.
  109. //
  110. // [3] B. Schneier, "Applied Cryptography", 2nd Ed, John Wiley & Sons, 1996.
  111. //
  112. // [4] A. Menezes, P. van Oorschot, and S. Vanstone, "Handbook of Applied Cryptography",
  113. // CRC Press, 1996, www.cacr.math.uwaterloo.ca/hac
  114. //
  115. // [5] A. Bosselaers, R. Govaerts, and J. Vandewalle, "Comparison of Three Modular
  116. // Reduction Functions," Proc. CRYPTO'93, pp.175-186.
  117. //
  118. // [6] R. Baillie and S. S. Wagstaff Jr, "Lucas Pseudoprimes", Mathematics of Computation,
  119. // Vol. 35, No. 152, Oct 1980, pp. 1391-1417.
  120. //
  121. // [7] H. C. Williams, "�douard Lucas and Primality Testing", Canadian Mathematical
  122. // Society Series of Monographs and Advance Texts, vol. 22, John Wiley & Sons, New York,
  123. // NY, 1998.
  124. //
  125. // [8] P. Ribenboim, "The new book of prime number records", 3rd edition, Springer-Verlag,
  126. // New York, NY, 1995.
  127. //
  128. // [9] M. Joye and J.-J. Quisquater, "Efficient computation of full Lucas sequences",
  129. // Electronics Letters, 32(6), 1996, pp 537-538.
  130. //
  131. //************************************************************************************
  132. using System;
  133. public class BigInteger
  134. {
  135. // maximum length of the BigInteger in uint (4 bytes)
  136. // change this to suit the required level of precision.
  137. private const int maxLength = 70;
  138. // primes smaller than 2000 to test the generated prime number
  139. public static readonly int[] primesBelow2000 = {
  140. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
  141. 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
  142. 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
  143. 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
  144. 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
  145. 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,
  146. 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
  147. 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,
  148. 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,
  149. 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997,
  150. 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097,
  151. 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193,
  152. 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297,
  153. 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
  154. 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499,
  155. 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597,
  156. 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699,
  157. 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
  158. 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
  159. 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999 };
  160. private uint[] data = null; // stores bytes from the Big Integer
  161. public int dataLength; // number of actual chars used
  162. //***********************************************************************
  163. // Constructor (Default value for BigInteger is 0
  164. //***********************************************************************
  165. public BigInteger()
  166. {
  167. data = new uint[maxLength];
  168. dataLength = 1;
  169. }
  170. //***********************************************************************
  171. // Constructor (Default value provided by long)
  172. //***********************************************************************
  173. public BigInteger(long value)
  174. {
  175. data = new uint[maxLength];
  176. long tempVal = value;
  177. // copy bytes from long to BigInteger without any assumption of
  178. // the length of the long datatype
  179. dataLength = 0;
  180. while(value != 0 && dataLength < maxLength)
  181. {
  182. data[dataLength] = (uint)(value & 0xFFFFFFFF);
  183. value >>= 32;
  184. dataLength++;
  185. }
  186. if(tempVal > 0) // overflow check for +ve value
  187. {
  188. if(value != 0 || (data[maxLength-1] & 0x80000000) != 0)
  189. throw(new ArithmeticException("Positive overflow in constructor."));
  190. }
  191. else if(tempVal < 0) // underflow check for -ve value
  192. {
  193. if(value != -1 || (data[dataLength-1] & 0x80000000) == 0)
  194. throw(new ArithmeticException("Negative underflow in constructor."));
  195. }
  196. if(dataLength == 0)
  197. dataLength = 1;
  198. }
  199. //***********************************************************************
  200. // Constructor (Default value provided by ulong)
  201. //***********************************************************************
  202. public BigInteger(ulong value)
  203. {
  204. data = new uint[maxLength];
  205. // copy bytes from ulong to BigInteger without any assumption of
  206. // the length of the ulong datatype
  207. dataLength = 0;
  208. while(value != 0 && dataLength < maxLength)
  209. {
  210. data[dataLength] = (uint)(value & 0xFFFFFFFF);
  211. value >>= 32;
  212. dataLength++;
  213. }
  214. if(value != 0 || (data[maxLength-1] & 0x80000000) != 0)
  215. throw(new ArithmeticException("Positive overflow in constructor."));
  216. if(dataLength == 0)
  217. dataLength = 1;
  218. }
  219. //***********************************************************************
  220. // Constructor (Default value provided by BigInteger)
  221. //***********************************************************************
  222. public BigInteger(BigInteger bi)
  223. {
  224. data = new uint[maxLength];
  225. dataLength = bi.dataLength;
  226. for(int i = 0; i < dataLength; i++)
  227. data[i] = bi.data[i];
  228. }
  229. //***********************************************************************
  230. // Constructor (Default value provided by a string of digits of the
  231. // specified base)
  232. //
  233. // Example (base 10)
  234. // -----------------
  235. // To initialize "a" with the default value of 1234 in base 10
  236. // BigInteger a = new BigInteger("1234", 10)
  237. //
  238. // To initialize "a" with the default value of -1234
  239. // BigInteger a = new BigInteger("-1234", 10)
  240. //
  241. // Example (base 16)
  242. // -----------------
  243. // To initialize "a" with the default value of 0x1D4F in base 16
  244. // BigInteger a = new BigInteger("1D4F", 16)
  245. //
  246. // To initialize "a" with the default value of -0x1D4F
  247. // BigInteger a = new BigInteger("-1D4F", 16)
  248. //
  249. // Note that string values are specified in the <sign><magnitude>
  250. // format.
  251. //
  252. //***********************************************************************
  253. public BigInteger(string value, int radix)
  254. {
  255. BigInteger multiplier = new BigInteger(1);
  256. BigInteger result = new BigInteger();
  257. value = (value.ToUpper()).Trim();
  258. int limit = 0;
  259. if(value[0] == '-')
  260. limit = 1;
  261. for(int i = value.Length - 1; i >= limit ; i--)
  262. {
  263. int posVal = (int)value[i];
  264. if(posVal >= '0' && posVal <= '9')
  265. posVal -= '0';
  266. else if(posVal >= 'A' && posVal <= 'Z')
  267. posVal = (posVal - 'A') + 10;
  268. else
  269. posVal = 9999999; // arbitrary large
  270. if(posVal >= radix)
  271. throw(new ArithmeticException("Invalid string in constructor."));
  272. else
  273. {
  274. if(value[0] == '-')
  275. posVal = -posVal;
  276. result = result + (multiplier * posVal);
  277. if((i - 1) >= limit)
  278. multiplier = multiplier * radix;
  279. }
  280. }
  281. if(value[0] == '-') // negative values
  282. {
  283. if((result.data[maxLength-1] & 0x80000000) == 0)
  284. throw(new ArithmeticException("Negative underflow in constructor."));
  285. }
  286. else // positive values
  287. {
  288. if((result.data[maxLength-1] & 0x80000000) != 0)
  289. throw(new ArithmeticException("Positive overflow in constructor."));
  290. }
  291. data = new uint[maxLength];
  292. for(int i = 0; i < result.dataLength; i++)
  293. data[i] = result.data[i];
  294. dataLength = result.dataLength;
  295. }
  296. //***********************************************************************
  297. // Constructor (Default value provided by an array of bytes)
  298. //
  299. // The lowest index of the input byte array (i.e [0]) should contain the
  300. // most significant byte of the number, and the highest index should
  301. // contain the least significant byte.
  302. //
  303. // E.g.
  304. // To initialize "a" with the default value of 0x1D4F in base 16
  305. // byte[] temp = { 0x1D, 0x4F };
  306. // BigInteger a = new BigInteger(temp)
  307. //
  308. // Note that this method of initialization does not allow the
  309. // sign to be specified.
  310. //
  311. //***********************************************************************
  312. public BigInteger(byte[] inData)
  313. {
  314. dataLength = inData.Length >> 2;
  315. int leftOver = inData.Length & 0x3;
  316. if(leftOver != 0) // length not multiples of 4
  317. dataLength++;
  318. if(dataLength > maxLength)
  319. throw(new ArithmeticException("Byte overflow in constructor."));
  320. data = new uint[maxLength];
  321. for(int i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++)
  322. {
  323. data[j] = (uint)((inData[i-3] << 24) + (inData[i-2] << 16) +
  324. (inData[i-1] << 8) + inData[i]);
  325. }
  326. if(leftOver == 1)
  327. data[dataLength-1] = (uint)inData[0];
  328. else if(leftOver == 2)
  329. data[dataLength-1] = (uint)((inData[0] << 8) + inData[1]);
  330. else if(leftOver == 3)
  331. data[dataLength-1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]);
  332. while(dataLength > 1 && data[dataLength-1] == 0)
  333. dataLength--;
  334. //Console.WriteLine("Len = " + dataLength);
  335. }
  336. //***********************************************************************
  337. // Constructor (Default value provided by an array of bytes of the
  338. // specified length.)
  339. //***********************************************************************
  340. public BigInteger(byte[] inData, int inLen)
  341. {
  342. dataLength = inLen >> 2;
  343. int leftOver = inLen & 0x3;
  344. if(leftOver != 0) // length not multiples of 4
  345. dataLength++;
  346. if(dataLength > maxLength || inLen > inData.Length)
  347. throw(new ArithmeticException("Byte overflow in constructor."));
  348. data = new uint[maxLength];
  349. for(int i = inLen - 1, j = 0; i >= 3; i -= 4, j++)
  350. {
  351. data[j] = (uint)((inData[i-3] << 24) + (inData[i-2] << 16) +
  352. (inData[i-1] << 8) + inData[i]);
  353. }
  354. if(leftOver == 1)
  355. data[dataLength-1] = (uint)inData[0];
  356. else if(leftOver == 2)
  357. data[dataLength-1] = (uint)((inData[0] << 8) + inData[1]);
  358. else if(leftOver == 3)
  359. data[dataLength-1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]);
  360. if(dataLength == 0)
  361. dataLength = 1;
  362. while(dataLength > 1 && data[dataLength-1] == 0)
  363. dataLength--;
  364. //Console.WriteLine("Len = " + dataLength);
  365. }
  366. //***********************************************************************
  367. // Constructor (Default value provided by an array of unsigned integers)
  368. //*********************************************************************
  369. public BigInteger(uint[] inData)
  370. {
  371. dataLength = inData.Length;
  372. if(dataLength > maxLength)
  373. throw(new ArithmeticException("Byte overflow in constructor."));
  374. data = new uint[maxLength];
  375. for(int i = dataLength - 1, j = 0; i >= 0; i--, j++)
  376. data[j] = inData[i];
  377. while(dataLength > 1 && data[dataLength-1] == 0)
  378. dataLength--;
  379. //Console.WriteLine("Len = " + dataLength);
  380. }
  381. //***********************************************************************
  382. // Overloading of the typecast operator.
  383. // For BigInteger bi = 10;
  384. //***********************************************************************
  385. public static implicit operator BigInteger(long value)
  386. {
  387. return (new BigInteger(value));
  388. }
  389. public static implicit operator BigInteger(ulong value)
  390. {
  391. return (new BigInteger(value));
  392. }
  393. public static implicit operator BigInteger(int value)
  394. {
  395. return (new BigInteger((long)value));
  396. }
  397. public static implicit operator BigInteger(uint value)
  398. {
  399. return (new BigInteger((ulong)value));
  400. }
  401. //***********************************************************************
  402. // Overloading of addition operator
  403. //***********************************************************************
  404. public static BigInteger operator +(BigInteger bi1, BigInteger bi2)
  405. {
  406. BigInteger result = new BigInteger();
  407. result.dataLength = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  408. long carry = 0;
  409. for(int i = 0; i < result.dataLength; i++)
  410. {
  411. long sum = (long)bi1.data[i] + (long)bi2.data[i] + carry;
  412. carry = sum >> 32;
  413. result.data[i] = (uint)(sum & 0xFFFFFFFF);
  414. }
  415. if(carry != 0 && result.dataLength < maxLength)
  416. {
  417. result.data[result.dataLength] = (uint)(carry);
  418. result.dataLength++;
  419. }
  420. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  421. result.dataLength--;
  422. // overflow check
  423. int lastPos = maxLength - 1;
  424. if((bi1.data[lastPos] & 0x80000000) == (bi2.data[lastPos] & 0x80000000) &&
  425. (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000))
  426. {
  427. throw (new ArithmeticException());
  428. }
  429. return result;
  430. }
  431. //***********************************************************************
  432. // Overloading of the unary ++ operator
  433. //***********************************************************************
  434. public static BigInteger operator ++(BigInteger bi1)
  435. {
  436. BigInteger result = new BigInteger(bi1);
  437. long val, carry = 1;
  438. int index = 0;
  439. while(carry != 0 && index < maxLength)
  440. {
  441. val = (long)(result.data[index]);
  442. val++;
  443. result.data[index] = (uint)(val & 0xFFFFFFFF);
  444. carry = val >> 32;
  445. index++;
  446. }
  447. if(index > result.dataLength)
  448. result.dataLength = index;
  449. else
  450. {
  451. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  452. result.dataLength--;
  453. }
  454. // overflow check
  455. int lastPos = maxLength - 1;
  456. // overflow if initial value was +ve but ++ caused a sign
  457. // change to negative.
  458. if((bi1.data[lastPos] & 0x80000000) == 0 &&
  459. (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000))
  460. {
  461. throw (new ArithmeticException("Overflow in ++."));
  462. }
  463. return result;
  464. }
  465. //***********************************************************************
  466. // Overloading of subtraction operator
  467. //***********************************************************************
  468. public static BigInteger operator -(BigInteger bi1, BigInteger bi2)
  469. {
  470. BigInteger result = new BigInteger();
  471. result.dataLength = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  472. long carryIn = 0;
  473. for(int i = 0; i < result.dataLength; i++)
  474. {
  475. long diff;
  476. diff = (long)bi1.data[i] - (long)bi2.data[i] - carryIn;
  477. result.data[i] = (uint)(diff & 0xFFFFFFFF);
  478. if(diff < 0)
  479. carryIn = 1;
  480. else
  481. carryIn = 0;
  482. }
  483. // roll over to negative
  484. if(carryIn != 0)
  485. {
  486. for(int i = result.dataLength; i < maxLength; i++)
  487. result.data[i] = 0xFFFFFFFF;
  488. result.dataLength = maxLength;
  489. }
  490. // fixed in v1.03 to give correct datalength for a - (-b)
  491. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  492. result.dataLength--;
  493. // overflow check
  494. int lastPos = maxLength - 1;
  495. if((bi1.data[lastPos] & 0x80000000) != (bi2.data[lastPos] & 0x80000000) &&
  496. (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000))
  497. {
  498. throw (new ArithmeticException());
  499. }
  500. return result;
  501. }
  502. //***********************************************************************
  503. // Overloading of the unary -- operator
  504. //***********************************************************************
  505. public static BigInteger operator --(BigInteger bi1)
  506. {
  507. BigInteger result = new BigInteger(bi1);
  508. long val;
  509. bool carryIn = true;
  510. int index = 0;
  511. while(carryIn && index < maxLength)
  512. {
  513. val = (long)(result.data[index]);
  514. val--;
  515. result.data[index] = (uint)(val & 0xFFFFFFFF);
  516. if(val >= 0)
  517. carryIn = false;
  518. index++;
  519. }
  520. if(index > result.dataLength)
  521. result.dataLength = index;
  522. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  523. result.dataLength--;
  524. // overflow check
  525. int lastPos = maxLength - 1;
  526. // overflow if initial value was -ve but -- caused a sign
  527. // change to positive.
  528. if((bi1.data[lastPos] & 0x80000000) != 0 &&
  529. (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000))
  530. {
  531. throw (new ArithmeticException("Underflow in --."));
  532. }
  533. return result;
  534. }
  535. //***********************************************************************
  536. // Overloading of multiplication operator
  537. //***********************************************************************
  538. public static BigInteger operator *(BigInteger bi1, BigInteger bi2)
  539. {
  540. int lastPos = maxLength-1;
  541. bool bi1Neg = false, bi2Neg = false;
  542. // take the absolute value of the inputs
  543. try
  544. {
  545. if((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative
  546. {
  547. bi1Neg = true; bi1 = -bi1;
  548. }
  549. if((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative
  550. {
  551. bi2Neg = true; bi2 = -bi2;
  552. }
  553. }
  554. catch(Exception) {}
  555. BigInteger result = new BigInteger();
  556. // multiply the absolute values
  557. try
  558. {
  559. for(int i = 0; i < bi1.dataLength; i++)
  560. {
  561. if(bi1.data[i] == 0) continue;
  562. ulong mcarry = 0;
  563. for(int j = 0, k = i; j < bi2.dataLength; j++, k++)
  564. {
  565. // k = i + j
  566. ulong val = ((ulong)bi1.data[i] * (ulong)bi2.data[j]) +
  567. (ulong)result.data[k] + mcarry;
  568. result.data[k] = (uint)(val & 0xFFFFFFFF);
  569. mcarry = (val >> 32);
  570. }
  571. if(mcarry != 0)
  572. result.data[i+bi2.dataLength] = (uint)mcarry;
  573. }
  574. }
  575. catch(Exception)
  576. {
  577. throw(new ArithmeticException("Multiplication overflow."));
  578. }
  579. result.dataLength = bi1.dataLength + bi2.dataLength;
  580. if(result.dataLength > maxLength)
  581. result.dataLength = maxLength;
  582. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  583. result.dataLength--;
  584. // overflow check (result is -ve)
  585. if((result.data[lastPos] & 0x80000000) != 0)
  586. {
  587. if(bi1Neg != bi2Neg && result.data[lastPos] == 0x80000000) // different sign
  588. {
  589. // handle the special case where multiplication produces
  590. // a max negative number in 2's complement.
  591. if(result.dataLength == 1)
  592. return result;
  593. else
  594. {
  595. bool isMaxNeg = true;
  596. for(int i = 0; i < result.dataLength - 1 && isMaxNeg; i++)
  597. {
  598. if(result.data[i] != 0)
  599. isMaxNeg = false;
  600. }
  601. if(isMaxNeg)
  602. return result;
  603. }
  604. }
  605. throw(new ArithmeticException("Multiplication overflow."));
  606. }
  607. // if input has different signs, then result is -ve
  608. if(bi1Neg != bi2Neg)
  609. return -result;
  610. return result;
  611. }
  612. //***********************************************************************
  613. // Overloading of unary << operators
  614. //***********************************************************************
  615. public static BigInteger operator <<(BigInteger bi1, int shiftVal)
  616. {
  617. BigInteger result = new BigInteger(bi1);
  618. result.dataLength = shiftLeft(result.data, shiftVal);
  619. return result;
  620. }
  621. // least significant bits at lower part of buffer
  622. private static int shiftLeft(uint[] buffer, int shiftVal)
  623. {
  624. int shiftAmount = 32;
  625. int bufLen = buffer.Length;
  626. while(bufLen > 1 && buffer[bufLen-1] == 0)
  627. bufLen--;
  628. for(int count = shiftVal; count > 0;)
  629. {
  630. if(count < shiftAmount)
  631. shiftAmount = count;
  632. //Console.WriteLine("shiftAmount = {0}", shiftAmount);
  633. ulong carry = 0;
  634. for(int i = 0; i < bufLen; i++)
  635. {
  636. ulong val = ((ulong)buffer[i]) << shiftAmount;
  637. val |= carry;
  638. buffer[i] = (uint)(val & 0xFFFFFFFF);
  639. carry = val >> 32;
  640. }
  641. if(carry != 0)
  642. {
  643. if(bufLen + 1 <= buffer.Length)
  644. {
  645. buffer[bufLen] = (uint)carry;
  646. bufLen++;
  647. }
  648. }
  649. count -= shiftAmount;
  650. }
  651. return bufLen;
  652. }
  653. //***********************************************************************
  654. // Overloading of unary >> operators
  655. //***********************************************************************
  656. public static BigInteger operator >>(BigInteger bi1, int shiftVal)
  657. {
  658. BigInteger result = new BigInteger(bi1);
  659. result.dataLength = shiftRight(result.data, shiftVal);
  660. if((bi1.data[maxLength-1] & 0x80000000) != 0) // negative
  661. {
  662. for(int i = maxLength - 1; i >= result.dataLength; i--)
  663. result.data[i] = 0xFFFFFFFF;
  664. uint mask = 0x80000000;
  665. for(int i = 0; i < 32; i++)
  666. {
  667. if((result.data[result.dataLength-1] & mask) != 0)
  668. break;
  669. result.data[result.dataLength-1] |= mask;
  670. mask >>= 1;
  671. }
  672. result.dataLength = maxLength;
  673. }
  674. return result;
  675. }
  676. private static int shiftRight(uint[] buffer, int shiftVal)
  677. {
  678. int shiftAmount = 32;
  679. int invShift = 0;
  680. int bufLen = buffer.Length;
  681. while(bufLen > 1 && buffer[bufLen-1] == 0)
  682. bufLen--;
  683. //Console.WriteLine("bufLen = " + bufLen + " buffer.Length = " + buffer.Length);
  684. for(int count = shiftVal; count > 0;)
  685. {
  686. if(count < shiftAmount)
  687. {
  688. shiftAmount = count;
  689. invShift = 32 - shiftAmount;
  690. }
  691. //Console.WriteLine("shiftAmount = {0}", shiftAmount);
  692. ulong carry = 0;
  693. for(int i = bufLen - 1; i >= 0; i--)
  694. {
  695. ulong val = ((ulong)buffer[i]) >> shiftAmount;
  696. val |= carry;
  697. carry = ((ulong)buffer[i]) << invShift;
  698. buffer[i] = (uint)(val);
  699. }
  700. count -= shiftAmount;
  701. }
  702. while(bufLen > 1 && buffer[bufLen-1] == 0)
  703. bufLen--;
  704. return bufLen;
  705. }
  706. //***********************************************************************
  707. // Overloading of the NOT operator (1's complement)
  708. //***********************************************************************
  709. public static BigInteger operator ~(BigInteger bi1)
  710. {
  711. BigInteger result = new BigInteger(bi1);
  712. for(int i = 0; i < maxLength; i++)
  713. result.data[i] = (uint)(~(bi1.data[i]));
  714. result.dataLength = maxLength;
  715. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  716. result.dataLength--;
  717. return result;
  718. }
  719. //***********************************************************************
  720. // Overloading of the NEGATE operator (2's complement)
  721. //***********************************************************************
  722. public static BigInteger operator -(BigInteger bi1)
  723. {
  724. // handle neg of zero separately since it'll cause an overflow
  725. // if we proceed.
  726. if(bi1.dataLength == 1 && bi1.data[0] == 0)
  727. return (new BigInteger());
  728. BigInteger result = new BigInteger(bi1);
  729. // 1's complement
  730. for(int i = 0; i < maxLength; i++)
  731. result.data[i] = (uint)(~(bi1.data[i]));
  732. // add one to result of 1's complement
  733. long val, carry = 1;
  734. int index = 0;
  735. while(carry != 0 && index < maxLength)
  736. {
  737. val = (long)(result.data[index]);
  738. val++;
  739. result.data[index] = (uint)(val & 0xFFFFFFFF);
  740. carry = val >> 32;
  741. index++;
  742. }
  743. if((bi1.data[maxLength-1] & 0x80000000) == (result.data[maxLength-1] & 0x80000000))
  744. throw (new ArithmeticException("Overflow in negation.\n"));
  745. result.dataLength = maxLength;
  746. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  747. result.dataLength--;
  748. return result;
  749. }
  750. //***********************************************************************
  751. // Overloading of equality operator
  752. //***********************************************************************
  753. public static bool operator ==(BigInteger bi1, BigInteger bi2)
  754. {
  755. return bi1.Equals(bi2);
  756. }
  757. public static bool operator !=(BigInteger bi1, BigInteger bi2)
  758. {
  759. return !(bi1.Equals(bi2));
  760. }
  761. public override bool Equals(object o)
  762. {
  763. BigInteger bi = (BigInteger)o;
  764. if(this.dataLength != bi.dataLength)
  765. return false;
  766. for(int i = 0; i < this.dataLength; i++)
  767. {
  768. if(this.data[i] != bi.data[i])
  769. return false;
  770. }
  771. return true;
  772. }
  773. public override int GetHashCode()
  774. {
  775. return this.ToString().GetHashCode();
  776. }
  777. //***********************************************************************
  778. // Overloading of inequality operator
  779. //***********************************************************************
  780. public static bool operator >(BigInteger bi1, BigInteger bi2)
  781. {
  782. int pos = maxLength - 1;
  783. // bi1 is negative, bi2 is positive
  784. if((bi1.data[pos] & 0x80000000) != 0 && (bi2.data[pos] & 0x80000000) == 0)
  785. return false;
  786. // bi1 is positive, bi2 is negative
  787. else if((bi1.data[pos] & 0x80000000) == 0 && (bi2.data[pos] & 0x80000000) != 0)
  788. return true;
  789. // same sign
  790. int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  791. for(pos = len - 1; pos >= 0 && bi1.data[pos] == bi2.data[pos]; pos--);
  792. if(pos >= 0)
  793. {
  794. if(bi1.data[pos] > bi2.data[pos])
  795. return true;
  796. return false;
  797. }
  798. return false;
  799. }
  800. public static bool operator <(BigInteger bi1, BigInteger bi2)
  801. {
  802. int pos = maxLength - 1;
  803. // bi1 is negative, bi2 is positive
  804. if((bi1.data[pos] & 0x80000000) != 0 && (bi2.data[pos] & 0x80000000) == 0)
  805. return true;
  806. // bi1 is positive, bi2 is negative
  807. else if((bi1.data[pos] & 0x80000000) == 0 && (bi2.data[pos] & 0x80000000) != 0)
  808. return false;
  809. // same sign
  810. int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  811. for(pos = len - 1; pos >= 0 && bi1.data[pos] == bi2.data[pos]; pos--);
  812. if(pos >= 0)
  813. {
  814. if(bi1.data[pos] < bi2.data[pos])
  815. return true;
  816. return false;
  817. }
  818. return false;
  819. }
  820. public static bool operator >=(BigInteger bi1, BigInteger bi2)
  821. {
  822. return (bi1 == bi2 || bi1 > bi2);
  823. }
  824. public static bool operator <=(BigInteger bi1, BigInteger bi2)
  825. {
  826. return (bi1 == bi2 || bi1 < bi2);
  827. }
  828. //***********************************************************************
  829. // Private function that supports the division of two numbers with
  830. // a divisor that has more than 1 digit.
  831. //
  832. // Algorithm taken from [1]
  833. //***********************************************************************
  834. private static void multiByteDivide(BigInteger bi1, BigInteger bi2,
  835. BigInteger outQuotient, BigInteger outRemainder)
  836. {
  837. uint[] result = new uint[maxLength];
  838. int remainderLen = bi1.dataLength + 1;
  839. uint[] remainder = new uint[remainderLen];
  840. uint mask = 0x80000000;
  841. uint val = bi2.data[bi2.dataLength - 1];
  842. int shift = 0, resultPos = 0;
  843. while(mask != 0 && (val & mask) == 0)
  844. {
  845. shift++; mask >>= 1;
  846. }
  847. //Console.WriteLine("shift = {0}", shift);
  848. //Console.WriteLine("Before bi1 Len = {0}, bi2 Len = {1}", bi1.dataLength, bi2.dataLength);
  849. for(int i = 0; i < bi1.dataLength; i++)
  850. remainder[i] = bi1.data[i];
  851. shiftLeft(remainder, shift);
  852. bi2 = bi2 << shift;
  853. /*
  854. Console.WriteLine("bi1 Len = {0}, bi2 Len = {1}", bi1.dataLength, bi2.dataLength);
  855. Console.WriteLine("dividend = " + bi1 + "\ndivisor = " + bi2);
  856. for(int q = remainderLen - 1; q >= 0; q--)
  857. Console.Write("{0:x2}", remainder[q]);
  858. Console.WriteLine();
  859. */
  860. int j = remainderLen - bi2.dataLength;
  861. int pos = remainderLen - 1;
  862. ulong firstDivisorByte = bi2.data[bi2.dataLength-1];
  863. ulong secondDivisorByte = bi2.data[bi2.dataLength-2];
  864. int divisorLen = bi2.dataLength + 1;
  865. uint[] dividendPart = new uint[divisorLen];
  866. while(j > 0)
  867. {
  868. ulong dividend = ((ulong)remainder[pos] << 32) + (ulong)remainder[pos-1];
  869. //Console.WriteLine("dividend = {0}", dividend);
  870. ulong q_hat = dividend / firstDivisorByte;
  871. ulong r_hat = dividend % firstDivisorByte;
  872. //Console.WriteLine("q_hat = {0:X}, r_hat = {1:X}", q_hat, r_hat);
  873. bool done = false;
  874. while(!done)
  875. {
  876. done = true;
  877. if(q_hat == 0x100000000 ||
  878. (q_hat * secondDivisorByte) > ((r_hat << 32) + remainder[pos-2]))
  879. {
  880. q_hat--;
  881. r_hat += firstDivisorByte;
  882. if(r_hat < 0x100000000)
  883. done = false;
  884. }
  885. }
  886. for(int h = 0; h < divisorLen; h++)
  887. dividendPart[h] = remainder[pos-h];
  888. BigInteger kk = new BigInteger(dividendPart);
  889. BigInteger ss = bi2 * (long)q_hat;
  890. //Console.WriteLine("ss before = " + ss);
  891. while(ss > kk)
  892. {
  893. q_hat--;
  894. ss -= bi2;
  895. //Console.WriteLine(ss);
  896. }
  897. BigInteger yy = kk - ss;
  898. //Console.WriteLine("ss = " + ss);
  899. //Console.WriteLine("kk = " + kk);
  900. //Console.WriteLine("yy = " + yy);
  901. for(int h = 0; h < divisorLen; h++)
  902. remainder[pos-h] = yy.data[bi2.dataLength-h];
  903. /*
  904. Console.WriteLine("dividend = ");
  905. for(int q = remainderLen - 1; q >= 0; q--)
  906. Console.Write("{0:x2}", remainder[q]);
  907. Console.WriteLine("\n************ q_hat = {0:X}\n", q_hat);
  908. */
  909. result[resultPos++] = (uint)q_hat;
  910. pos--;
  911. j--;
  912. }
  913. outQuotient.dataLength = resultPos;
  914. int y = 0;
  915. for(int x = outQuotient.dataLength - 1; x >= 0; x--, y++)
  916. outQuotient.data[y] = result[x];
  917. for(; y < maxLength; y++)
  918. outQuotient.data[y] = 0;
  919. while(outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength-1] == 0)
  920. outQuotient.dataLength--;
  921. if(outQuotient.dataLength == 0)
  922. outQuotient.dataLength = 1;
  923. outRemainder.dataLength = shiftRight(remainder, shift);
  924. for(y = 0; y < outRemainder.dataLength; y++)
  925. outRemainder.data[y] = remainder[y];
  926. for(; y < maxLength; y++)
  927. outRemainder.data[y] = 0;
  928. }
  929. //***********************************************************************
  930. // Private function that supports the division of two numbers with
  931. // a divisor that has only 1 digit.
  932. //***********************************************************************
  933. private static void singleByteDivide(BigInteger bi1, BigInteger bi2,
  934. BigInteger outQuotient, BigInteger outRemainder)
  935. {
  936. uint[] result = new uint[maxLength];
  937. int resultPos = 0;
  938. // copy dividend to reminder
  939. for(int i = 0; i < maxLength; i++)
  940. outRemainder.data[i] = bi1.data[i];
  941. outRemainder.dataLength = bi1.dataLength;
  942. while(outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength-1] == 0)
  943. outRemainder.dataLength--;
  944. ulong divisor = (ulong)bi2.data[0];
  945. int pos = outRemainder.dataLength - 1;
  946. ulong dividend = (ulong)outRemainder.data[pos];
  947. //Console.WriteLine("divisor = " + divisor + " dividend = " + dividend);
  948. //Console.WriteLine("divisor = " + bi2 + "\ndividend = " + bi1);
  949. if(dividend >= divisor)
  950. {
  951. ulong quotient = dividend / divisor;
  952. result[resultPos++] = (uint)quotient;
  953. outRemainder.data[pos] = (uint)(dividend % divisor);
  954. }
  955. pos--;
  956. while(pos >= 0)
  957. {
  958. //Console.WriteLine(pos);
  959. dividend = ((ulong)outRemainder.data[pos+1] << 32) + (ulong)outRemainder.data[pos];
  960. ulong quotient = dividend / divisor;
  961. result[resultPos++] = (uint)quotient;
  962. outRemainder.data[pos+1] = 0;
  963. outRemainder.data[pos--] = (uint)(dividend % divisor);
  964. //Console.WriteLine(">>>> " + bi1);
  965. }
  966. outQuotient.dataLength = resultPos;
  967. int j = 0;
  968. for(int i = outQuotient.dataLength - 1; i >= 0; i--, j++)
  969. outQuotient.data[j] = result[i];
  970. for(; j < maxLength; j++)
  971. outQuotient.data[j] = 0;
  972. while(outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength-1] == 0)
  973. outQuotient.dataLength--;
  974. if(outQuotient.dataLength == 0)
  975. outQuotient.dataLength = 1;
  976. while(outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength-1] == 0)
  977. outRemainder.dataLength--;
  978. }
  979. //***********************************************************************
  980. // Overloading of division operator
  981. //***********************************************************************
  982. public static BigInteger operator /(BigInteger bi1, BigInteger bi2)
  983. {
  984. BigInteger quotient = new BigInteger();
  985. BigInteger remainder = new BigInteger();
  986. int lastPos = maxLength-1;
  987. bool divisorNeg = false, dividendNeg = false;
  988. if((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative
  989. {
  990. bi1 = -bi1;
  991. dividendNeg = true;
  992. }
  993. if((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative
  994. {
  995. bi2 = -bi2;
  996. divisorNeg = true;
  997. }
  998. if(bi1 < bi2)
  999. {
  1000. return quotient;
  1001. }
  1002. else
  1003. {
  1004. if(bi2.dataLength == 1)
  1005. singleByteDivide(bi1, bi2, quotient, remainder);
  1006. else
  1007. multiByteDivide(bi1, bi2, quotient, remainder);
  1008. if(dividendNeg != divisorNeg)
  1009. return -quotient;
  1010. return quotient;
  1011. }
  1012. }
  1013. //***********************************************************************
  1014. // Overloading of modulus operator
  1015. //***********************************************************************
  1016. public static BigInteger operator %(BigInteger bi1, BigInteger bi2)
  1017. {
  1018. BigInteger quotient = new BigInteger();
  1019. BigInteger remainder = new BigInteger(bi1);
  1020. int lastPos = maxLength-1;
  1021. bool dividendNeg = false;
  1022. if((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative
  1023. {
  1024. bi1 = -bi1;
  1025. dividendNeg = true;
  1026. }
  1027. if((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative
  1028. bi2 = -bi2;
  1029. if(bi1 < bi2)
  1030. {
  1031. return remainder;
  1032. }
  1033. else
  1034. {
  1035. if(bi2.dataLength == 1)
  1036. singleByteDivide(bi1, bi2, quotient, remainder);
  1037. else
  1038. multiByteDivide(bi1, bi2, quotient, remainder);
  1039. if(dividendNeg)
  1040. return -remainder;
  1041. return remainder;
  1042. }
  1043. }
  1044. //***********************************************************************
  1045. // Overloading of bitwise AND operator
  1046. //***********************************************************************
  1047. public static BigInteger operator &(BigInteger bi1, BigInteger bi2)
  1048. {
  1049. BigInteger result = new BigInteger();
  1050. int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  1051. for(int i = 0; i < len; i++)
  1052. {
  1053. uint sum = (uint)(bi1.data[i] & bi2.data[i]);
  1054. result.data[i] = sum;
  1055. }
  1056. result.dataLength = maxLength;
  1057. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  1058. result.dataLength--;
  1059. return result;
  1060. }
  1061. //***********************************************************************
  1062. // Overloading of bitwise OR operator
  1063. //***********************************************************************
  1064. public static BigInteger operator |(BigInteger bi1, BigInteger bi2)
  1065. {
  1066. BigInteger result = new BigInteger();
  1067. int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  1068. for(int i = 0; i < len; i++)
  1069. {
  1070. uint sum = (uint)(bi1.data[i] | bi2.data[i]);
  1071. result.data[i] = sum;
  1072. }
  1073. result.dataLength = maxLength;
  1074. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  1075. result.dataLength--;
  1076. return result;
  1077. }
  1078. //***********************************************************************
  1079. // Overloading of bitwise XOR operator
  1080. //***********************************************************************
  1081. public static BigInteger operator ^(BigInteger bi1, BigInteger bi2)
  1082. {
  1083. BigInteger result = new BigInteger();
  1084. int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength;
  1085. for(int i = 0; i < len; i++)
  1086. {
  1087. uint sum = (uint)(bi1.data[i] ^ bi2.data[i]);
  1088. result.data[i] = sum;
  1089. }
  1090. result.dataLength = maxLength;
  1091. while(result.dataLength > 1 && result.data[result.dataLength-1] == 0)
  1092. result.dataLength--;
  1093. return result;
  1094. }
  1095. //***********************************************************************
  1096. // Returns max(this, bi)
  1097. //***********************************************************************
  1098. public BigInteger max(BigInteger bi)
  1099. {
  1100. if(this > bi)
  1101. return (new BigInteger(this));
  1102. else
  1103. return (new BigInteger(bi));
  1104. }
  1105. //***********************************************************************
  1106. // Returns min(this, bi)
  1107. //***********************************************************************
  1108. public BigInteger min(BigInteger bi)
  1109. {
  1110. if(this < bi)
  1111. return (new BigInteger(this));
  1112. else
  1113. return (new BigInteger(bi));
  1114. }
  1115. //***********************************************************************
  1116. // Returns the absolute value
  1117. //***********************************************************************
  1118. public BigInteger abs()
  1119. {
  1120. if((this.data[maxLength - 1] & 0x80000000) != 0)
  1121. return (-this);
  1122. else
  1123. return (new BigInteger(this));
  1124. }
  1125. //***********************************************************************
  1126. // Returns a string representing the BigInteger in base 10.
  1127. //***********************************************************************
  1128. public override string ToString()
  1129. {
  1130. return ToString(10);
  1131. }
  1132. //***********************************************************************
  1133. // Returns a string representing the BigInteger in sign-and-magnitude
  1134. // format in the specified radix.
  1135. //
  1136. // Example
  1137. // -------
  1138. // If the value of BigInteger is -255 in base 10, then
  1139. // ToString(16) returns "-FF"
  1140. //
  1141. //***********************************************************************
  1142. public string ToString(int radix)
  1143. {
  1144. if(radix < 2 || radix > 36)
  1145. throw (new ArgumentException("Radix must be >= 2 and <= 36"));
  1146. string charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1147. string result = "";
  1148. BigInteger a = this;
  1149. bool negative = false;
  1150. if((a.data[maxLength-1] & 0x80000000) != 0)
  1151. {
  1152. negative = true;
  1153. try
  1154. {
  1155. a = -a;
  1156. }
  1157. catch(Exception) {}
  1158. }
  1159. BigInteger quotient = new BigInteger();
  1160. BigInteger remainder = new BigInteger();
  1161. BigInteger biRadix = new BigInteger(radix);
  1162. if(a.dataLength == 1 && a.data[0] == 0)
  1163. result = "0";
  1164. else
  1165. {
  1166. while(a.dataLength > 1 || (a.dataLength == 1 && a.data[0] != 0))
  1167. {
  1168. singleByteDivide(a, biRadix, quotient, remainder);
  1169. if(remainder.data[0] < 10)
  1170. result = remainder.data[0] + result;
  1171. else
  1172. result = charSet[(int)remainder.data[0] - 10] + result;
  1173. a = quotient;
  1174. }
  1175. if(negative)
  1176. result = "-" + result;
  1177. }
  1178. return result;
  1179. }
  1180. //***********************************************************************
  1181. // Returns a hex string showing the contains of the BigInteger
  1182. //
  1183. // Examples
  1184. // -------
  1185. // 1) If the value of BigInteger is 255 in base 10, then
  1186. // ToHexString() returns "FF"
  1187. //
  1188. // 2) If the value of BigInteger is -255 in base 10, then
  1189. // ToHexString() returns ".....FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01",
  1190. // which is the 2's complement representation of -255.
  1191. //
  1192. //***********************************************************************
  1193. public string ToHexString()
  1194. {
  1195. string result = data[dataLength - 1].ToString("X");
  1196. for(int i = dataLength - 2; i >= 0; i--)
  1197. {
  1198. result += data[i].ToString("X8");
  1199. }
  1200. return result;
  1201. }
  1202. //***********************************************************************
  1203. // Modulo Exponentiation
  1204. //***********************************************************************
  1205. public BigInteger modPow(BigInteger exp, BigInteger n)
  1206. {
  1207. if((exp.data[maxLength-1] & 0x80000000) != 0)
  1208. throw (new ArithmeticException("Positive exponents only."));
  1209. BigInteger resultNum = 1;
  1210. BigInteger tempNum;
  1211. bool thisNegative = false;
  1212. if((this.data[maxLength-1] & 0x80000000) != 0) // negative this
  1213. {
  1214. tempNum = -this % n;
  1215. thisNegative = true;
  1216. }
  1217. else
  1218. tempNum = this % n; // ensures (tempNum * tempNum) < b^(2k)
  1219. if((n.data[maxLength-1] & 0x80000000) != 0) // negative n
  1220. n = -n;
  1221. // calculate constant = b^(2k) / m
  1222. BigInteger constant = new BigInteger();
  1223. int i = n.dataLength << 1;
  1224. constant.data[i] = 0x00000001;
  1225. constant.dataLength = i + 1;
  1226. constant = constant / n;
  1227. int totalBits = exp.bitCount();
  1228. int count = 0;
  1229. // perform squaring and multiply exponentiation
  1230. for(int pos = 0; pos < exp.dataLength; pos++)
  1231. {
  1232. uint mask = 0x01;
  1233. //Console.WriteLine("pos = " + pos);
  1234. for(int index = 0; index < 32; index++)
  1235. {
  1236. if((exp.data[pos] & mask) != 0)
  1237. resultNum = BarrettReduction(resultNum * tempNum, n, constant);
  1238. mask <<= 1;
  1239. tempNum = BarrettReduction(tempNum * tempNum, n, constant);
  1240. if(tempNum.dataLength == 1 && tempNum.data[0] == 1)
  1241. {
  1242. if(thisNegative && (exp.data[0] & 0x1) != 0) //odd exp
  1243. return -resultNum;
  1244. return resultNum;
  1245. }
  1246. count++;
  1247. if(count == totalBits)
  1248. break;
  1249. }
  1250. }
  1251. if(thisNegative && (exp.data[0] & 0x1) != 0) //odd exp
  1252. return -resultNum;
  1253. return resultNum;
  1254. }
  1255. //***********************************************************************
  1256. // Fast calculation of modular reduction using Barrett's reduction.
  1257. // Requires x < b^(2k), where b is the base. In this case, base is
  1258. // 2^32 (uint).
  1259. //
  1260. // Reference [4]
  1261. //***********************************************************************
  1262. private BigInteger BarrettReduction(BigInteger x, BigInteger n, BigInteger constant)
  1263. {
  1264. int k = n.dataLength,
  1265. kPlusOne = k+1,
  1266. kMinusOne = k-1;
  1267. BigInteger q1 = new BigInteger();
  1268. // q1 = x / b^(k-1)
  1269. for(int i = kMinusOne, j = 0; i < x.dataLength; i++, j++)
  1270. q1.data[j] = x.data[i];
  1271. q1.dataLength = x.dataLength - kMinusOne;
  1272. if(q1.dataLength <= 0)
  1273. q1.dataLength = 1;
  1274. BigInteger q2 = q1 * constant;
  1275. BigInteger q3 = new BigInteger();
  1276. // q3 = q2 / b^(k+1)
  1277. for(int i = kPlusOne, j = 0; i < q2.dataLength; i++, j++)
  1278. q3.data[j] = q2.data[i];
  1279. q3.dataLength = q2.dataLength - kPlusOne;
  1280. if(q3.dataLength <= 0)
  1281. q3.dataLength = 1;
  1282. // r1 = x mod b^(k+1)
  1283. // i.e. keep the lowest (k+1) words
  1284. BigInteger r1 = new BigInteger();
  1285. int lengthToCopy = (x.dataLength > kPlusOne) ? kPlusOne : x.dataLength;
  1286. for(int i = 0; i < lengthToCopy; i++)
  1287. r1.data[i] = x.data[i];
  1288. r1.dataLength = lengthToCopy;
  1289. // r2 = (q3 * n) mod b^(k+1)
  1290. // partial multiplication of q3 and n
  1291. BigInteger r2 = new BigInteger();
  1292. for(int i = 0; i < q3.dataLength; i++)
  1293. {
  1294. if(q3.data[i] == 0) continue;
  1295. ulong mcarry = 0;
  1296. int t = i;
  1297. for(int j = 0; j < n.dataLength && t < kPlusOne; j++, t++)
  1298. {
  1299. // t = i + j
  1300. ulong val = ((ulong)q3.data[i] * (ulong)n.data[j]) +
  1301. (ulong)r2.data[t] + mcarry;
  1302. r2.data[t] = (uint)(val & 0xFFFFFFFF);
  1303. mcarry = (val >> 32);
  1304. }
  1305. if(t < kPlusOne)
  1306. r2.data[t] = (uint)mcarry;
  1307. }
  1308. r2.dataLength = kPlusOne;
  1309. while(r2.dataLength > 1 && r2.data[r2.dataLength-1] == 0)
  1310. r2.dataLength--;
  1311. r1 -= r2;
  1312. if((r1.data[maxLength-1] & 0x80000000) != 0) // negative
  1313. {
  1314. BigInteger val = new BigInteger();
  1315. val.data[kPlusOne] = 0x00000001;
  1316. val.dataLength = kPlusOne + 1;
  1317. r1 += val;
  1318. }
  1319. while(r1 >= n)
  1320. r1 -= n;
  1321. return r1;
  1322. }
  1323. //***********************************************************************
  1324. // Returns gcd(this, bi)
  1325. //***********************************************************************
  1326. public BigInteger gcd(BigInteger bi)
  1327. {
  1328. BigInteger x;
  1329. BigInteger y;
  1330. if((data[maxLength-1] & 0x80000000) != 0) // negative
  1331. x = -this;
  1332. else
  1333. x = this;
  1334. if((bi.data[maxLength-1] & 0x80000000) != 0) // negative
  1335. y = -bi;
  1336. else
  1337. y = bi;
  1338. BigInteger g = y;
  1339. while(x.dataLength > 1 || (x.dataLength == 1 && x.data[0] != 0))
  1340. {
  1341. g = x;
  1342. x = y % x;
  1343. y = g;
  1344. }
  1345. return g;
  1346. }
  1347. //***********************************************************************
  1348. // Populates "this" with the specified amount of random bits
  1349. //***********************************************************************
  1350. public void genRandomBits(int bits, Random rand)
  1351. {
  1352. int dwords = bits >> 5;
  1353. int remBits = bits & 0x1F;
  1354. if(remBits != 0)
  1355. dwords++;
  1356. if(dwords > maxLength)
  1357. throw (new ArithmeticException("Number of required bits > maxLength."));
  1358. for(int i = 0; i < dwords; i++)
  1359. data[i] = (uint)(rand.NextDouble() * 0x100000000);
  1360. for(int i = dwords; i < maxLength; i++)
  1361. data[i] = 0;
  1362. if(remBits != 0)
  1363. {
  1364. uint mask = (uint)(0x01 << (remBits-1));
  1365. data[dwords-1] |= mask;
  1366. mask = (uint)(0xFFFFFFFF >> (32 - remBits));
  1367. data[dwords-1] &= mask;
  1368. }
  1369. else
  1370. data[dwords-1] |= 0x80000000;
  1371. dataLength = dwords;
  1372. if(dataLength == 0)
  1373. dataLength = 1;
  1374. }
  1375. //***********************************************************************
  1376. // Returns the position of the most significant bit in the BigInteger.
  1377. //
  1378. // Eg. The result is 0, if the value of BigInteger is 0...0000 0000
  1379. // The result is 1, if the value of BigInteger is 0...0000 0001
  1380. // The result is 2, if the value of BigInteger is 0...0000 0010
  1381. // The result is 2, if the value of BigInteger is 0...0000 0011
  1382. //
  1383. //***********************************************************************
  1384. public int bitCount()
  1385. {
  1386. while(dataLength > 1 && data[dataLength-1] == 0)
  1387. dataLength--;
  1388. uint value = data[dataLength - 1];
  1389. uint mask = 0x80000000;
  1390. int bits = 32;
  1391. while(bits > 0 && (value & mask) == 0)
  1392. {
  1393. bits--;
  1394. mask >>= 1;
  1395. }
  1396. bits += ((dataLength - 1) << 5);
  1397. return bits;
  1398. }
  1399. //***********************************************************************
  1400. // Probabilistic prime test based on Fermat's little theorem
  1401. //
  1402. // for any a < p (p does not divide a) if
  1403. // a^(p-1) mod p != 1 then p is not prime.
  1404. //
  1405. // Otherwise, p is probably prime (pseudoprime to the chosen base).
  1406. //
  1407. // Returns
  1408. // -------
  1409. // True if "this" is a pseudoprime to randomly chosen
  1410. // bases. The number of chosen bases is given by the "confidence"
  1411. // parameter.
  1412. //
  1413. // False if "this" is definitely NOT prime.
  1414. //
  1415. // Note - this method is fast but fails for Carmichael numbers except
  1416. // when the randomly chosen base is a factor of the number.
  1417. //
  1418. //***********************************************************************
  1419. public bool FermatLittleTest(int confidence)
  1420. {
  1421. BigInteger thisVal;
  1422. if((this.data[maxLength-1] & 0x80000000) != 0) // negative
  1423. thisVal = -this;
  1424. else
  1425. thisVal = this;
  1426. if(thisVal.dataLength == 1)
  1427. {
  1428. // test small numbers
  1429. if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
  1430. return false;
  1431. else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
  1432. return true;
  1433. }
  1434. if((thisVal.data[0] & 0x1) == 0) // even numbers
  1435. return false;
  1436. int bits = thisVal.bitCount();
  1437. BigInteger a = new BigInteger();
  1438. BigInteger p_sub1 = thisVal - (new BigInteger(1));
  1439. Random rand = new Random();
  1440. for(int round = 0; round < confidence; round++)
  1441. {
  1442. bool done = false;
  1443. while(!done) // generate a < n
  1444. {
  1445. int testBits = 0;
  1446. // make sure "a" has at least 2 bits
  1447. while(testBits < 2)
  1448. testBits = (int)(rand.NextDouble() * bits);
  1449. a.genRandomBits(testBits, rand);
  1450. int byteLen = a.dataLength;
  1451. // make sure "a" is not 0
  1452. if(byteLen > 1 || (byteLen == 1 && a.data[0] != 1))
  1453. done = true;
  1454. }
  1455. // check whether a factor exists (fix for version 1.03)
  1456. BigInteger gcdTest = a.gcd(thisVal);
  1457. if(gcdTest.dataLength == 1 && gcdTest.data[0] != 1)
  1458. return false;
  1459. // calculate a^(p-1) mod p
  1460. BigInteger expResult = a.modPow(p_sub1, thisVal);
  1461. int resultLen = expResult.dataLength;
  1462. // is NOT prime is a^(p-1) mod p != 1
  1463. if(resultLen > 1 || (resultLen == 1 && expResult.data[0] != 1))
  1464. {
  1465. //Console.WriteLine("a = " + a.ToString());
  1466. return false;
  1467. }
  1468. }
  1469. return true;
  1470. }
  1471. //***********************************************************************
  1472. // Probabilistic prime test based on Rabin-Miller's
  1473. //
  1474. // for any p > 0 with p - 1 = 2^s * t
  1475. //
  1476. // p is probably prime (strong pseudoprime) if for any a < p,
  1477. // 1) a^t mod p = 1 or
  1478. // 2) a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1
  1479. //
  1480. // Otherwise, p is composite.
  1481. //
  1482. // Returns
  1483. // -------
  1484. // True if "this" is a strong pseudoprime to randomly chosen
  1485. // bases. The number of chosen bases is given by the "confidence"
  1486. // parameter.
  1487. //
  1488. // False if "this" is definitely NOT prime.
  1489. //
  1490. //***********************************************************************
  1491. public bool RabinMillerTest(int confidence)
  1492. {
  1493. BigInteger thisVal;
  1494. if((this.data[maxLength-1] & 0x80000000) != 0) // negative
  1495. thisVal = -this;
  1496. else
  1497. thisVal = this;
  1498. if(thisVal.dataLength == 1)
  1499. {
  1500. // test small numbers
  1501. if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
  1502. return false;
  1503. else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
  1504. return true;
  1505. }
  1506. if((thisVal.data[0] & 0x1) == 0) // even numbers
  1507. return false;
  1508. // calculate values of s and t
  1509. BigInteger p_sub1 = thisVal - (new BigInteger(1));
  1510. int s = 0;
  1511. for(int index = 0; index < p_sub1.dataLength; index++)
  1512. {
  1513. uint mask = 0x01;
  1514. for(int i = 0; i < 32; i++)
  1515. {
  1516. if((p_sub1.data[index] & mask) != 0)
  1517. {
  1518. index = p_sub1.dataLength; // to break the outer loop
  1519. break;
  1520. }
  1521. mask <<= 1;
  1522. s++;
  1523. }
  1524. }
  1525. BigInteger t = p_sub1 >> s;
  1526. int bits = thisVal.bitCount();
  1527. BigInteger a = new BigInteger();
  1528. Random rand = new Random();
  1529. for(int round = 0; round < confidence; round++)
  1530. {
  1531. bool done = false;
  1532. while(!done) // generate a < n
  1533. {
  1534. int testBits = 0;
  1535. // make sure "a" has at least 2 bits
  1536. while(testBits < 2)
  1537. testBits = (int)(rand.NextDouble() * bits);
  1538. a.genRandomBits(testBits, rand);
  1539. int byteLen = a.dataLength;
  1540. // make sure "a" is not 0
  1541. if(byteLen > 1 || (byteLen == 1 && a.data[0] != 1))
  1542. done = true;
  1543. }
  1544. // check whether a factor exists (fix for version 1.03)
  1545. BigInteger gcdTest = a.gcd(thisVal);
  1546. if(gcdTest.dataLength == 1 && gcdTest.data[0] != 1)
  1547. return false;
  1548. BigInteger b = a.modPow(t, thisVal);
  1549. /*
  1550. Console.WriteLine("a = " + a.ToString(10));
  1551. Console.WriteLine("b = " + b.ToString(10));
  1552. Console.WriteLine("t = " + t.ToString(10));
  1553. Console.WriteLine("s = " + s);
  1554. */
  1555. bool result = false;
  1556. if(b.dataLength == 1 && b.data[0] == 1) // a^t mod p = 1
  1557. result = true;
  1558. for(int j = 0; result == false && j < s; j++)
  1559. {
  1560. if(b == p_sub1) // a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1
  1561. {
  1562. result = true;
  1563. break;
  1564. }
  1565. b = (b * b) % thisVal;
  1566. }
  1567. if(result == false)
  1568. return false;
  1569. }
  1570. return true;
  1571. }
  1572. //***********************************************************************
  1573. // Probabilistic prime test based on Solovay-Strassen (Euler Criterion)
  1574. //
  1575. // p is probably prime if for any a < p (a is not multiple of p),
  1576. // a^((p-1)/2) mod p = J(a, p)
  1577. //
  1578. // where J is the Jacobi symbol.
  1579. //
  1580. // Otherwise, p is composite.
  1581. //
  1582. // Returns
  1583. // -------
  1584. // True if "this" is a Euler pseudoprime to randomly chosen
  1585. // bases. The number of chosen bases is given by the "confidence"
  1586. // parameter.
  1587. //
  1588. // False if "this" is definitely NOT prime.
  1589. //
  1590. //***********************************************************************
  1591. public bool SolovayStrassenTest(int confidence)
  1592. {
  1593. BigInteger thisVal;
  1594. if((this.data[maxLength-1] & 0x80000000) != 0) // negative
  1595. thisVal = -this;
  1596. else
  1597. thisVal = this;
  1598. if(thisVal.dataLength == 1)
  1599. {
  1600. // test small numbers
  1601. if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
  1602. return false;
  1603. else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
  1604. return true;
  1605. }
  1606. if((thisVal.data[0] & 0x1) == 0) // even numbers
  1607. return false;
  1608. int bits = thisVal.bitCount();
  1609. BigInteger a = new BigInteger();
  1610. BigInteger p_sub1 = thisVal - 1;
  1611. BigInteger p_sub1_shift = p_sub1 >> 1;
  1612. Random rand = new Random();
  1613. for(int round = 0; round < confidence; round++)
  1614. {
  1615. bool done = false;
  1616. while(!done) // generate a < n
  1617. {
  1618. int testBits = 0;
  1619. // make sure "a" has at least 2 bits
  1620. while(testBits < 2)
  1621. testBits = (int)(rand.NextDouble() * bits);
  1622. a.genRandomBits(testBits, rand);
  1623. int byteLen = a.dataLength;
  1624. // make sure "a" is not 0
  1625. if(byteLen > 1 || (byteLen == 1 && a.data[0] != 1))
  1626. done = true;
  1627. }
  1628. // check whether a factor exists (fix for version 1.03)
  1629. BigInteger gcdTest = a.gcd(thisVal);
  1630. if(gcdTest.dataLength == 1 && gcdTest.data[0] != 1)
  1631. return false;
  1632. // calculate a^((p-1)/2) mod p
  1633. BigInteger expResult = a.modPow(p_sub1_shift, thisVal);
  1634. if(expResult == p_sub1)
  1635. expResult = -1;
  1636. // calculate Jacobi symbol
  1637. BigInteger jacob = Jacobi(a, thisVal);
  1638. //Console.WriteLine("a = " + a.ToString(10) + " b = " + thisVal.ToString(10));
  1639. //Console.WriteLine("expResult = " + expResult.ToString(10) + " Jacob = " + jacob.ToString(10));
  1640. // if they are different then it is not prime
  1641. if(expResult != jacob)
  1642. return false;
  1643. }
  1644. return true;
  1645. }
  1646. //***********************************************************************
  1647. // Implementation of the Lucas Strong Pseudo Prime test.
  1648. //
  1649. // Let n be an odd number with gcd(n,D) = 1, and n - J(D, n) = 2^s * d
  1650. // with d odd and s >= 0.
  1651. //
  1652. // If Ud mod n = 0 or V2^r*d mod n = 0 for some 0 <= r < s, then n
  1653. // is a strong Lucas pseudoprime with parameters (P, Q). We select
  1654. // P and Q based on Selfridge.
  1655. //
  1656. // Returns True if number is a strong Lucus pseudo prime.
  1657. // Otherwise, returns False indicating that number is composite.
  1658. //***********************************************************************
  1659. public bool LucasStrongTest()
  1660. {
  1661. BigInteger thisVal;
  1662. if((this.data[maxLength-1] & 0x80000000) != 0) // negative
  1663. thisVal = -this;
  1664. else
  1665. thisVal = this;
  1666. if(thisVal.dataLength == 1)
  1667. {
  1668. // test small numbers
  1669. if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
  1670. return false;
  1671. else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
  1672. return true;
  1673. }
  1674. if((thisVal.data[0] & 0x1) == 0) // even numbers
  1675. return false;
  1676. return LucasStrongTestHelper(thisVal);
  1677. }
  1678. private bool LucasStrongTestHelper(BigInteger thisVal)
  1679. {
  1680. // Do the test (selects D based on Selfridge)
  1681. // Let D be the first element of the sequence
  1682. // 5, -7, 9, -11, 13, ... for which J(D,n) = -1
  1683. // Let P = 1, Q = (1-D) / 4
  1684. long D = 5, sign = -1, dCount = 0;
  1685. bool done = false;
  1686. while(!done)
  1687. {
  1688. int Jresult = BigInteger.Jacobi(D, thisVal);
  1689. if(Jresult == -1)
  1690. done = true; // J(D, this) = 1
  1691. else
  1692. {
  1693. if(Jresult == 0 && Math.Abs(D) < thisVal) // divisor found
  1694. return false;
  1695. if(dCount == 20)
  1696. {
  1697. // check for square
  1698. BigInteger root = thisVal.sqrt();
  1699. if(root * root == thisVal)
  1700. return false;
  1701. }
  1702. //Console.WriteLine(D);
  1703. D = (Math.Abs(D) + 2) * sign;
  1704. sign = -sign;
  1705. }
  1706. dCount++;
  1707. }
  1708. long Q = (1 - D) >> 2;
  1709. /*
  1710. Console.WriteLine("D = " + D);
  1711. Console.WriteLine("Q = " + Q);
  1712. Console.WriteLine("(n,D) = " + thisVal.gcd(D));
  1713. Console.WriteLine("(n,Q) = " + thisVal.gcd(Q));
  1714. Console.WriteLine("J(D|n) = " + BigInteger.Jacobi(D, thisVal));
  1715. */
  1716. BigInteger p_add1 = thisVal + 1;
  1717. int s = 0;
  1718. for(int index = 0; index < p_add1.dataLength; index++)
  1719. {
  1720. uint mask = 0x01;
  1721. for(int i = 0; i < 32; i++)
  1722. {
  1723. if((p_add1.data[index] & mask) != 0)
  1724. {
  1725. index = p_add1.dataLength; // to break the outer loop
  1726. break;
  1727. }
  1728. mask <<= 1;
  1729. s++;
  1730. }
  1731. }
  1732. BigInteger t = p_add1 >> s;
  1733. // calculate constant = b^(2k) / m
  1734. // for Barrett Reduction
  1735. BigInteger constant = new BigInteger();
  1736. int nLen = thisVal.dataLength << 1;
  1737. constant.data[nLen] = 0x00000001;
  1738. constant.dataLength = nLen + 1;
  1739. constant = constant / thisVal;
  1740. BigInteger[] lucas = LucasSequenceHelper(1, Q, t, thisVal, constant, 0);
  1741. bool isPrime = false;
  1742. if((lucas[0].dataLength == 1 && lucas[0].data[0] == 0) ||
  1743. (lucas[1].dataLength == 1 && lucas[1].data[0] == 0))
  1744. {
  1745. // u(t) = 0 or V(t) = 0
  1746. isPrime = true;
  1747. }
  1748. for(int i = 1; i < s; i++)
  1749. {
  1750. if(!isPrime)
  1751. {
  1752. // doubling of index
  1753. lucas[1] = thisVal.BarrettReduction(lucas[1] * lucas[1], thisVal, constant);
  1754. lucas[1] = (lucas[1] - (lucas[2] << 1)) % thisVal;
  1755. //lucas[1] = ((lucas[1] * lucas[1]) - (lucas[2] << 1)) % thisVal;
  1756. if((lucas[1].dataLength == 1 && lucas[1].data[0] == 0))
  1757. isPrime = true;
  1758. }
  1759. lucas[2] = thisVal.BarrettReduction(lucas[2] * lucas[2], thisVal, constant); //Q^k
  1760. }
  1761. if(isPrime) // additional checks for composite numbers
  1762. {
  1763. // If n is prime and gcd(n, Q) == 1, then
  1764. // Q^((n+1)/2) = Q * Q^((n-1)/2) is congruent to (Q * J(Q, n)) mod n
  1765. BigInteger g = thisVal.gcd(Q);
  1766. if(g.dataLength == 1 && g.data[0] == 1) // gcd(this, Q) == 1
  1767. {
  1768. if((lucas[2].data[maxLength-1] & 0x80000000) != 0)
  1769. lucas[2] += thisVal;
  1770. BigInteger temp = (Q * BigInteger.Jacobi(Q, thisVal)) % thisVal;
  1771. if((temp.data[maxLength-1] & 0x80000000) != 0)
  1772. temp += thisVal;
  1773. if(lucas[2] != temp)
  1774. isPrime = false;
  1775. }
  1776. }
  1777. return isPrime;
  1778. }
  1779. //***********************************************************************
  1780. // Determines whether a number is probably prime, using the Rabin-Miller's
  1781. // test. Before applying the test, the number is tested for divisibility
  1782. // by primes < 2000
  1783. //
  1784. // Returns true if number is probably prime.
  1785. //***********************************************************************
  1786. public bool isProbablePrime(int confidence)
  1787. {
  1788. BigInteger thisVal;
  1789. if((this.data[maxLength-1] & 0x80000000) != 0) // negative
  1790. thisVal = -this;
  1791. else
  1792. thisVal = this;
  1793. // test for divisibility by primes < 2000
  1794. for(int p = 0; p < primesBelow2000.Length; p++)
  1795. {
  1796. BigInteger divisor = primesBelow2000[p];
  1797. if(divisor >= thisVal)
  1798. break;
  1799. BigInteger resultNum = thisVal % divisor;
  1800. if(resultNum.IntValue() == 0)
  1801. {
  1802. /*
  1803. Console.WriteLine("Not prime! Divisible by {0}\n",
  1804. primesBelow2000[p]);
  1805. */
  1806. return false;
  1807. }
  1808. }
  1809. if(thisVal.RabinMillerTest(confidence))
  1810. return true;
  1811. else
  1812. {
  1813. //Console.WriteLine("Not prime! Failed primality test\n");
  1814. return false;
  1815. }
  1816. }
  1817. //***********************************************************************
  1818. // Determines whether this BigInteger is probably prime using a
  1819. // combination of base 2 strong pseudoprime test and Lucas strong
  1820. // pseudoprime test.
  1821. //
  1822. // The sequence of the primality test is as follows,
  1823. //
  1824. // 1) Trial divisions are carried out using prime numbers below 2000.
  1825. // if any of the primes divides this BigInteger, then it is not prime.
  1826. //
  1827. // 2) Perform base 2 strong pseudoprime test. If this BigInteger is a
  1828. // base 2 strong pseudoprime, proceed on to the next step.
  1829. //
  1830. // 3) Perform strong Lucas pseudoprime test.
  1831. //
  1832. // Returns True if this BigInteger is both a base 2 strong pseudoprime
  1833. // and a strong Lucas pseudoprime.
  1834. //
  1835. // For a detailed discussion of this primality test, see [6].
  1836. //
  1837. //***********************************************************************
  1838. public bool isProbablePrime()
  1839. {
  1840. BigInteger thisVal;
  1841. if((this.data[maxLength-1] & 0x80000000) != 0) // negative
  1842. thisVal = -this;
  1843. else
  1844. thisVal = this;
  1845. if(thisVal.dataLength == 1)
  1846. {
  1847. // test small numbers
  1848. if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
  1849. return false;
  1850. else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
  1851. return true;
  1852. }
  1853. if((thisVal.data[0] & 0x1) == 0) // even numbers
  1854. return false;
  1855. // test for divisibility by primes < 2000
  1856. for(int p = 0; p < primesBelow2000.Length; p++)
  1857. {
  1858. BigInteger divisor = primesBelow2000[p];
  1859. if(divisor >= thisVal)
  1860. break;
  1861. BigInteger resultNum = thisVal % divisor;
  1862. if(resultNum.IntValue() == 0)
  1863. {
  1864. //Console.WriteLine("Not prime! Divisible by {0}\n",
  1865. // primesBelow2000[p]);
  1866. return false;
  1867. }
  1868. }
  1869. // Perform BASE 2 Rabin-Miller Test
  1870. // calculate values of s and t
  1871. BigInteger p_sub1 = thisVal - (new BigInteger(1));
  1872. int s = 0;
  1873. for(int index = 0; index < p_sub1.dataLength; index++)
  1874. {
  1875. uint mask = 0x01;
  1876. for(int i = 0; i < 32; i++)
  1877. {
  1878. if((p_sub1.data[index] & mask) != 0)
  1879. {
  1880. index = p_sub1.dataLength; // to break the outer loop
  1881. break;
  1882. }
  1883. mask <<= 1;
  1884. s++;
  1885. }
  1886. }
  1887. BigInteger t = p_sub1 >> s;
  1888. int bits = thisVal.bitCount();
  1889. BigInteger a = 2;
  1890. // b = a^t mod p
  1891. BigInteger b = a.modPow(t, thisVal);
  1892. bool result = false;
  1893. if(b.dataLength == 1 && b.data[0] == 1) // a^t mod p = 1
  1894. result = true;
  1895. for(int j = 0; result == false && j < s; j++)
  1896. {
  1897. if(b == p_sub1) // a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1
  1898. {
  1899. result = true;
  1900. break;
  1901. }
  1902. b = (b * b) % thisVal;
  1903. }
  1904. // if number is strong pseudoprime to base 2, then do a strong lucas test
  1905. if(result)
  1906. result = LucasStrongTestHelper(thisVal);
  1907. return result;
  1908. }
  1909. //***********************************************************************
  1910. // Returns the lowest 4 bytes of the BigInteger as an int.
  1911. //***********************************************************************
  1912. public int IntValue()
  1913. {
  1914. return (int)data[0];
  1915. }
  1916. //***********************************************************************
  1917. // Returns the lowest 8 bytes of the BigInteger as a long.
  1918. //***********************************************************************
  1919. public long LongValue()
  1920. {
  1921. long val = 0;
  1922. val = (long)data[0];
  1923. try
  1924. { // exception if maxLength = 1
  1925. val |= (long)data[1] << 32;
  1926. }
  1927. catch(Exception)
  1928. {
  1929. if((data[0] & 0x80000000) != 0) // negative
  1930. val = (int)data[0];
  1931. }
  1932. return val;
  1933. }
  1934. //***********************************************************************
  1935. // Computes the Jacobi Symbol for a and b.
  1936. // Algorithm adapted from [3] and [4] with some optimizations
  1937. //***********************************************************************
  1938. public static int Jacobi(BigInteger a, BigInteger b)
  1939. {
  1940. // Jacobi defined only for odd integers
  1941. if((b.data[0] & 0x1) == 0)
  1942. throw (new ArgumentException("Jacobi defined only for odd integers."));
  1943. if(a >= b) a %= b;
  1944. if(a.dataLength == 1 && a.data[0] == 0) return 0; // a == 0
  1945. if(a.dataLength == 1 && a.data[0] == 1) return 1; // a == 1
  1946. if(a < 0)
  1947. {
  1948. if( (((b-1).data[0]) & 0x2) == 0) //if( (((b-1) >> 1).data[0] & 0x1) == 0)
  1949. return Jacobi(-a, b);
  1950. else
  1951. return -Jacobi(-a, b);
  1952. }
  1953. int e = 0;
  1954. for(int index = 0; index < a.dataLength; index++)
  1955. {
  1956. uint mask = 0x01;
  1957. for(int i = 0; i < 32; i++)
  1958. {
  1959. if((a.data[index] & mask) != 0)
  1960. {
  1961. index = a.dataLength; // to break the outer loop
  1962. break;
  1963. }
  1964. mask <<= 1;
  1965. e++;
  1966. }
  1967. }
  1968. BigInteger a1 = a >> e;
  1969. int s = 1;
  1970. if((e & 0x1) != 0 && ((b.data[0] & 0x7) == 3 || (b.data[0] & 0x7) == 5))
  1971. s = -1;
  1972. if((b.data[0] & 0x3) == 3 && (a1.data[0] & 0x3) == 3)
  1973. s = -s;
  1974. if(a1.dataLength == 1 && a1.data[0] == 1)
  1975. return s;
  1976. else
  1977. return (s * Jacobi(b % a1, a1));
  1978. }
  1979. //***********************************************************************
  1980. // Generates a positive BigInteger that is probably prime.
  1981. //***********************************************************************
  1982. public static BigInteger genPseudoPrime(int bits, int confidence, Random rand)
  1983. {
  1984. BigInteger result = new BigInteger();
  1985. bool done = false;
  1986. while(!done)
  1987. {
  1988. result.genRandomBits(bits, rand);
  1989. result.data[0] |= 0x01; // make it odd
  1990. // prime test
  1991. done = result.isProbablePrime(confidence);
  1992. }
  1993. return result;
  1994. }
  1995. //***********************************************************************
  1996. // Generates a random number with the specified number of bits such
  1997. // that gcd(number, this) = 1
  1998. //***********************************************************************
  1999. public BigInteger genCoPrime(int bits, Random rand)
  2000. {
  2001. bool done = false;
  2002. BigInteger result = new BigInteger();
  2003. while(!done)
  2004. {
  2005. result.genRandomBits(bits, rand);
  2006. //Console.WriteLine(result.ToString(16));
  2007. // gcd test
  2008. BigInteger g = result.gcd(this);
  2009. if(g.dataLength == 1 && g.data[0] == 1)
  2010. done = true;
  2011. }
  2012. return result;
  2013. }
  2014. //***********************************************************************
  2015. // Returns the modulo inverse of this. Throws ArithmeticException if
  2016. // the inverse does not exist. (i.e. gcd(this, modulus) != 1)
  2017. //***********************************************************************
  2018. public BigInteger modInverse(BigInteger modulus)
  2019. {
  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 = this;
  2026. while(b.dataLength > 1 || (b.dataLength == 1 && b.data[0] != 0))
  2027. {
  2028. BigInteger quotient = new BigInteger();
  2029. BigInteger remainder = new BigInteger();
  2030. if(step > 1)
  2031. {
  2032. BigInteger pval = (p[0] - (p[1] * q[0])) % modulus;
  2033. p[0] = p[1];
  2034. p[1] = pval;
  2035. }
  2036. if(b.dataLength == 1)
  2037. singleByteDivide(a, b, quotient, remainder);
  2038. else
  2039. multiByteDivide(a, b, quotient, remainder);
  2040. /*
  2041. Console.WriteLine(quotient.dataLength);
  2042. Console.WriteLine("{0} = {1}({2}) + {3} p = {4}", a.ToString(10),
  2043. b.ToString(10), quotient.ToString(10), remainder.ToString(10),
  2044. p[1].ToString(10));
  2045. */
  2046. q[0] = q[1];
  2047. r[0] = r[1];
  2048. q[1] = quotient; r[1] = remainder;
  2049. a = b;
  2050. b = remainder;
  2051. step++;
  2052. }
  2053. if(r[0].dataLength > 1 || (r[0].dataLength == 1 && r[0].data[0] != 1))
  2054. throw (new ArithmeticException("No inverse!"));
  2055. BigInteger result = ((p[0] - (p[1] * q[0])) % modulus);
  2056. if((result.data[maxLength - 1] & 0x80000000) != 0)
  2057. result += modulus; // get the least positive modulus
  2058. return result;
  2059. }
  2060. //***********************************************************************
  2061. // Returns the value of the BigInteger as a byte array. The lowest
  2062. // index contains the MSB.
  2063. //***********************************************************************
  2064. public byte[] getBytes()
  2065. {
  2066. int numBits = bitCount();
  2067. int numBytes = numBits >> 3;
  2068. if((numBits & 0x7) != 0)
  2069. numBytes++;
  2070. byte[] result = new byte[numBytes];
  2071. //Console.WriteLine(result.Length);
  2072. int pos = 0;
  2073. uint tempVal, val = data[dataLength - 1];
  2074. if((tempVal = (val >> 24 & 0xFF)) != 0)
  2075. result[pos++] = (byte)tempVal;
  2076. if((tempVal = (val >> 16 & 0xFF)) != 0)
  2077. result[pos++] = (byte)tempVal;
  2078. if((tempVal = (val >> 8 & 0xFF)) != 0)
  2079. result[pos++] = (byte)tempVal;
  2080. if((tempVal = (val & 0xFF)) != 0)
  2081. result[pos++] = (byte)tempVal;
  2082. for(int i = dataLength - 2; i >= 0; i--, pos += 4)
  2083. {
  2084. val = data[i];
  2085. result[pos+3] = (byte)(val & 0xFF);
  2086. val >>= 8;
  2087. result[pos+2] = (byte)(val & 0xFF);
  2088. val >>= 8;
  2089. result[pos+1] = (byte)(val & 0xFF);
  2090. val >>= 8;
  2091. result[pos] = (byte)(val & 0xFF);
  2092. }
  2093. return result;
  2094. }
  2095. //***********************************************************************
  2096. // Sets the value of the specified bit to 1
  2097. // The Least Significant Bit position is 0.
  2098. //***********************************************************************
  2099. public void setBit(uint bitNum)
  2100. {
  2101. uint bytePos = bitNum >> 5; // divide by 32
  2102. byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits
  2103. uint mask = (uint)1 << bitPos;
  2104. this.data[bytePos] |= mask;
  2105. if(bytePos >= this.dataLength)
  2106. this.dataLength = (int)bytePos + 1;
  2107. }
  2108. //***********************************************************************
  2109. // Sets the value of the specified bit to 0
  2110. // The Least Significant Bit position is 0.
  2111. //***********************************************************************
  2112. public void unsetBit(uint bitNum)
  2113. {
  2114. uint bytePos = bitNum >> 5;
  2115. if(bytePos < this.dataLength)
  2116. {
  2117. byte bitPos = (byte)(bitNum & 0x1F);
  2118. uint mask = (uint)1 << bitPos;
  2119. uint mask2 = 0xFFFFFFFF ^ mask;
  2120. this.data[bytePos] &= mask2;
  2121. if(this.dataLength > 1 && this.data[this.dataLength - 1] == 0)
  2122. this.dataLength--;
  2123. }
  2124. }
  2125. //***********************************************************************
  2126. // Returns a value that is equivalent to the integer square root
  2127. // of the BigInteger.
  2128. //
  2129. // The integer square root of "this" is defined as the largest integer n
  2130. // such that (n * n) <= this
  2131. //
  2132. //***********************************************************************
  2133. public BigInteger sqrt()
  2134. {
  2135. uint numBits = (uint)this.bitCount();
  2136. if((numBits & 0x1) != 0) // odd number of bits
  2137. numBits = (numBits >> 1) + 1;
  2138. else
  2139. numBits = (numBits >> 1);
  2140. uint bytePos = numBits >> 5;
  2141. byte bitPos = (byte)(numBits & 0x1F);
  2142. uint mask;
  2143. BigInteger result = new BigInteger();
  2144. if(bitPos == 0)
  2145. mask = 0x80000000;
  2146. else
  2147. {
  2148. mask = (uint)1 << bitPos;
  2149. bytePos++;
  2150. }
  2151. result.dataLength = (int)bytePos;
  2152. for(int i = (int)bytePos - 1; i >= 0; i--)
  2153. {
  2154. while(mask != 0)
  2155. {
  2156. // guess
  2157. result.data[i] ^= mask;
  2158. // undo the guess if its square is larger than this
  2159. if((result * result) > this)
  2160. result.data[i] ^= mask;
  2161. mask >>= 1;
  2162. }
  2163. mask = 0x80000000;
  2164. }
  2165. return result;
  2166. }
  2167. //***********************************************************************
  2168. // Returns the k_th number in the Lucas Sequence reduced modulo n.
  2169. //
  2170. // Uses index doubling to speed up the process. For example, to calculate V(k),
  2171. // we maintain two numbers in the sequence V(n) and V(n+1).
  2172. //
  2173. // To obtain V(2n), we use the identity
  2174. // V(2n) = (V(n) * V(n)) - (2 * Q^n)
  2175. // To obtain V(2n+1), we first write it as
  2176. // V(2n+1) = V((n+1) + n)
  2177. // and use the identity
  2178. // V(m+n) = V(m) * V(n) - Q * V(m-n)
  2179. // Hence,
  2180. // V((n+1) + n) = V(n+1) * V(n) - Q^n * V((n+1) - n)
  2181. // = V(n+1) * V(n) - Q^n * V(1)
  2182. // = V(n+1) * V(n) - Q^n * P
  2183. //
  2184. // We use k in its binary expansion and perform index doubling for each
  2185. // bit position. For each bit position that is set, we perform an
  2186. // index doubling followed by an index addition. This means that for V(n),
  2187. // we need to update it to V(2n+1). For V(n+1), we need to update it to
  2188. // V((2n+1)+1) = V(2*(n+1))
  2189. //
  2190. // This function returns
  2191. // [0] = U(k)
  2192. // [1] = V(k)
  2193. // [2] = Q^n
  2194. //
  2195. // Where U(0) = 0 % n, U(1) = 1 % n
  2196. // V(0) = 2 % n, V(1) = P % n
  2197. //***********************************************************************
  2198. public static BigInteger[] LucasSequence(BigInteger P, BigInteger Q,
  2199. BigInteger k, BigInteger n)
  2200. {
  2201. if(k.dataLength == 1 && k.data[0] == 0)
  2202. {
  2203. BigInteger[] result = new BigInteger[3];
  2204. result[0] = 0; result[1] = 2 % n; result[2] = 1 % n;
  2205. return result;
  2206. }
  2207. // calculate constant = b^(2k) / m
  2208. // for Barrett Reduction
  2209. BigInteger constant = new BigInteger();
  2210. int nLen = n.dataLength << 1;
  2211. constant.data[nLen] = 0x00000001;
  2212. constant.dataLength = nLen + 1;
  2213. constant = constant / n;
  2214. // calculate values of s and t
  2215. int s = 0;
  2216. for(int index = 0; index < k.dataLength; index++)
  2217. {
  2218. uint mask = 0x01;
  2219. for(int i = 0; i < 32; i++)
  2220. {
  2221. if((k.data[index] & mask) != 0)
  2222. {
  2223. index = k.dataLength; // to break the outer loop
  2224. break;
  2225. }
  2226. mask <<= 1;
  2227. s++;
  2228. }
  2229. }
  2230. BigInteger t = k >> s;
  2231. //Console.WriteLine("s = " + s + " t = " + t);
  2232. return LucasSequenceHelper(P, Q, t, n, constant, s);
  2233. }
  2234. //***********************************************************************
  2235. // Performs the calculation of the kth term in the Lucas Sequence.
  2236. // For details of the algorithm, see reference [9].
  2237. //
  2238. // k must be odd. i.e LSB == 1
  2239. //***********************************************************************
  2240. private static BigInteger[] LucasSequenceHelper(BigInteger P, BigInteger Q,
  2241. BigInteger k, BigInteger n,
  2242. BigInteger constant, int s)
  2243. {
  2244. BigInteger[] result = new BigInteger[3];
  2245. if((k.data[0] & 0x00000001) == 0)
  2246. throw (new ArgumentException("Argument k must be odd."));
  2247. int numbits = k.bitCount();
  2248. uint mask = (uint)0x1 << ((numbits & 0x1F) - 1);
  2249. // v = v0, v1 = v1, u1 = u1, Q_k = Q^0
  2250. BigInteger v = 2 % n, Q_k = 1 % n,
  2251. v1 = P % n, u1 = Q_k;
  2252. bool flag = true;
  2253. for(int i = k.dataLength - 1; i >= 0 ; i--) // iterate on the binary expansion of k
  2254. {
  2255. //Console.WriteLine("round");
  2256. while(mask != 0)
  2257. {
  2258. if(i == 0 && mask == 0x00000001) // last bit
  2259. break;
  2260. if((k.data[i] & mask) != 0) // bit is set
  2261. {
  2262. // index doubling with addition
  2263. u1 = (u1 * v1) % n;
  2264. v = ((v * v1) - (P * Q_k)) % n;
  2265. v1 = n.BarrettReduction(v1 * v1, n, constant);
  2266. v1 = (v1 - ((Q_k * Q) << 1)) % n;
  2267. if(flag)
  2268. flag = false;
  2269. else
  2270. Q_k = n.BarrettReduction(Q_k * Q_k, n, constant);
  2271. Q_k = (Q_k * Q) % n;
  2272. }
  2273. else
  2274. {
  2275. // index doubling
  2276. u1 = ((u1 * v) - Q_k) % n;
  2277. v1 = ((v * v1) - (P * Q_k)) % n;
  2278. v = n.BarrettReduction(v * v, n, constant);
  2279. v = (v - (Q_k << 1)) % n;
  2280. if(flag)
  2281. {
  2282. Q_k = Q % n;
  2283. flag = false;
  2284. }
  2285. else
  2286. Q_k = n.BarrettReduction(Q_k * Q_k, n, constant);
  2287. }
  2288. mask >>= 1;
  2289. }
  2290. mask = 0x80000000;
  2291. }
  2292. // at this point u1 = u(n+1) and v = v(n)
  2293. // since the last bit always 1, we need to transform u1 to u(2n+1) and v to v(2n+1)
  2294. u1 = ((u1 * v) - Q_k) % n;
  2295. v = ((v * v1) - (P * Q_k)) % n;
  2296. if(flag)
  2297. flag = false;
  2298. else
  2299. Q_k = n.BarrettReduction(Q_k * Q_k, n, constant);
  2300. Q_k = (Q_k * Q) % n;
  2301. for(int i = 0; i < s; i++)
  2302. {
  2303. // index doubling
  2304. u1 = (u1 * v) % n;
  2305. v = ((v * v) - (Q_k << 1)) % n;
  2306. if(flag)
  2307. {
  2308. Q_k = Q % n;
  2309. flag = false;
  2310. }
  2311. else
  2312. Q_k = n.BarrettReduction(Q_k * Q_k, n, constant);
  2313. }
  2314. result[0] = u1;
  2315. result[1] = v;
  2316. result[2] = Q_k;
  2317. return result;
  2318. }
  2319. //***********************************************************************
  2320. // Tests the correct implementation of the /, %, * and + operators
  2321. //***********************************************************************
  2322. public static void MulDivTest(int rounds)
  2323. {
  2324. Random rand = new Random();
  2325. byte[] val = new byte[64];
  2326. byte[] val2 = new byte[64];
  2327. for(int count = 0; count < rounds; count++)
  2328. {
  2329. // generate 2 numbers of random length
  2330. int t1 = 0;
  2331. while(t1 == 0)
  2332. t1 = (int)(rand.NextDouble() * 65);
  2333. int t2 = 0;
  2334. while(t2 == 0)
  2335. t2 = (int)(rand.NextDouble() * 65);
  2336. bool done = false;
  2337. while(!done)
  2338. {
  2339. for(int i = 0; i < 64; i++)
  2340. {
  2341. if(i < t1)
  2342. val[i] = (byte)(rand.NextDouble() * 256);
  2343. else
  2344. val[i] = 0;
  2345. if(val[i] != 0)
  2346. done = true;
  2347. }
  2348. }
  2349. done = false;
  2350. while(!done)
  2351. {
  2352. for(int i = 0; i < 64; i++)
  2353. {
  2354. if(i < t2)
  2355. val2[i] = (byte)(rand.NextDouble() * 256);
  2356. else
  2357. val2[i] = 0;
  2358. if(val2[i] != 0)
  2359. done = true;
  2360. }
  2361. }
  2362. while(val[0] == 0)
  2363. val[0] = (byte)(rand.NextDouble() * 256);
  2364. while(val2[0] == 0)
  2365. val2[0] = (byte)(rand.NextDouble() * 256);
  2366. Console.WriteLine(count);
  2367. BigInteger bn1 = new BigInteger(val, t1);
  2368. BigInteger bn2 = new BigInteger(val2, t2);
  2369. // Determine the quotient and remainder by dividing
  2370. // the first number by the second.
  2371. BigInteger bn3 = bn1 / bn2;
  2372. BigInteger bn4 = bn1 % bn2;
  2373. // Recalculate the number
  2374. BigInteger bn5 = (bn3 * bn2) + bn4;
  2375. // Make sure they're the same
  2376. if(bn5 != bn1)
  2377. {
  2378. Console.WriteLine("Error at " + count);
  2379. Console.WriteLine(bn1 + "\n");
  2380. Console.WriteLine(bn2 + "\n");
  2381. Console.WriteLine(bn3 + "\n");
  2382. Console.WriteLine(bn4 + "\n");
  2383. Console.WriteLine(bn5 + "\n");
  2384. return;
  2385. }
  2386. }
  2387. }
  2388. //***********************************************************************
  2389. // Tests the correct implementation of the modulo exponential function
  2390. // using RSA encryption and decryption (using pre-computed encryption and
  2391. // decryption keys).
  2392. //***********************************************************************
  2393. public static void RSATest(int rounds)
  2394. {
  2395. Random rand = new Random(1);
  2396. byte[] val = new byte[64];
  2397. // private and public key
  2398. BigInteger bi_e = new BigInteger("a932b948feed4fb2b692609bd22164fc9edb59fae7880cc1eaff7b3c9626b7e5b241c27a974833b2622ebe09beb451917663d47232488f23a117fc97720f1e7", 16);
  2399. BigInteger bi_d = new BigInteger("4adf2f7a89da93248509347d2ae506d683dd3a16357e859a980c4f77a4e2f7a01fae289f13a851df6e9db5adaa60bfd2b162bbbe31f7c8f828261a6839311929d2cef4f864dde65e556ce43c89bbbf9f1ac5511315847ce9cc8dc92470a747b8792d6a83b0092d2e5ebaf852c85cacf34278efa99160f2f8aa7ee7214de07b7", 16);
  2400. BigInteger bi_n = new BigInteger("e8e77781f36a7b3188d711c2190b560f205a52391b3479cdb99fa010745cbeba5f2adc08e1de6bf38398a0487c4a73610d94ec36f17f3f46ad75e17bc1adfec99839589f45f95ccc94cb2a5c500b477eb3323d8cfab0c8458c96f0147a45d27e45a4d11d54d77684f65d48f15fafcc1ba208e71e921b9bd9017c16a5231af7f", 16);
  2401. Console.WriteLine("e =\n" + bi_e.ToString(10));
  2402. Console.WriteLine("\nd =\n" + bi_d.ToString(10));
  2403. Console.WriteLine("\nn =\n" + bi_n.ToString(10) + "\n");
  2404. for(int count = 0; count < rounds; count++)
  2405. {
  2406. // generate data of random length
  2407. int t1 = 0;
  2408. while(t1 == 0)
  2409. t1 = (int)(rand.NextDouble() * 65);
  2410. bool done = false;
  2411. while(!done)
  2412. {
  2413. for(int i = 0; i < 64; i++)
  2414. {
  2415. if(i < t1)
  2416. val[i] = (byte)(rand.NextDouble() * 256);
  2417. else
  2418. val[i] = 0;
  2419. if(val[i] != 0)
  2420. done = true;
  2421. }
  2422. }
  2423. while(val[0] == 0)
  2424. val[0] = (byte)(rand.NextDouble() * 256);
  2425. Console.Write("Round = " + count);
  2426. // encrypt and decrypt data
  2427. BigInteger bi_data = new BigInteger(val, t1);
  2428. BigInteger bi_encrypted = bi_data.modPow(bi_e, bi_n);
  2429. BigInteger bi_decrypted = bi_encrypted.modPow(bi_d, bi_n);
  2430. // compare
  2431. if(bi_decrypted != bi_data)
  2432. {
  2433. Console.WriteLine("\nError at round " + count);
  2434. Console.WriteLine(bi_data + "\n");
  2435. return;
  2436. }
  2437. Console.WriteLine(" <PASSED>.");
  2438. }
  2439. }
  2440. //***********************************************************************
  2441. // Tests the correct implementation of the modulo exponential and
  2442. // inverse modulo functions using RSA encryption and decryption. The two
  2443. // pseudoprimes p and q are fixed, but the two RSA keys are generated
  2444. // for each round of testing.
  2445. //***********************************************************************
  2446. public static void RSATest2(int rounds)
  2447. {
  2448. Random rand = new Random();
  2449. byte[] val = new byte[64];
  2450. byte[] pseudoPrime1 = {
  2451. (byte)0x85, (byte)0x84, (byte)0x64, (byte)0xFD, (byte)0x70, (byte)0x6A,
  2452. (byte)0x9F, (byte)0xF0, (byte)0x94, (byte)0x0C, (byte)0x3E, (byte)0x2C,
  2453. (byte)0x74, (byte)0x34, (byte)0x05, (byte)0xC9, (byte)0x55, (byte)0xB3,
  2454. (byte)0x85, (byte)0x32, (byte)0x98, (byte)0x71, (byte)0xF9, (byte)0x41,
  2455. (byte)0x21, (byte)0x5F, (byte)0x02, (byte)0x9E, (byte)0xEA, (byte)0x56,
  2456. (byte)0x8D, (byte)0x8C, (byte)0x44, (byte)0xCC, (byte)0xEE, (byte)0xEE,
  2457. (byte)0x3D, (byte)0x2C, (byte)0x9D, (byte)0x2C, (byte)0x12, (byte)0x41,
  2458. (byte)0x1E, (byte)0xF1, (byte)0xC5, (byte)0x32, (byte)0xC3, (byte)0xAA,
  2459. (byte)0x31, (byte)0x4A, (byte)0x52, (byte)0xD8, (byte)0xE8, (byte)0xAF,
  2460. (byte)0x42, (byte)0xF4, (byte)0x72, (byte)0xA1, (byte)0x2A, (byte)0x0D,
  2461. (byte)0x97, (byte)0xB1, (byte)0x31, (byte)0xB3,
  2462. };
  2463. byte[] pseudoPrime2 = {
  2464. (byte)0x99, (byte)0x98, (byte)0xCA, (byte)0xB8, (byte)0x5E, (byte)0xD7,
  2465. (byte)0xE5, (byte)0xDC, (byte)0x28, (byte)0x5C, (byte)0x6F, (byte)0x0E,
  2466. (byte)0x15, (byte)0x09, (byte)0x59, (byte)0x6E, (byte)0x84, (byte)0xF3,
  2467. (byte)0x81, (byte)0xCD, (byte)0xDE, (byte)0x42, (byte)0xDC, (byte)0x93,
  2468. (byte)0xC2, (byte)0x7A, (byte)0x62, (byte)0xAC, (byte)0x6C, (byte)0xAF,
  2469. (byte)0xDE, (byte)0x74, (byte)0xE3, (byte)0xCB, (byte)0x60, (byte)0x20,
  2470. (byte)0x38, (byte)0x9C, (byte)0x21, (byte)0xC3, (byte)0xDC, (byte)0xC8,
  2471. (byte)0xA2, (byte)0x4D, (byte)0xC6, (byte)0x2A, (byte)0x35, (byte)0x7F,
  2472. (byte)0xF3, (byte)0xA9, (byte)0xE8, (byte)0x1D, (byte)0x7B, (byte)0x2C,
  2473. (byte)0x78, (byte)0xFA, (byte)0xB8, (byte)0x02, (byte)0x55, (byte)0x80,
  2474. (byte)0x9B, (byte)0xC2, (byte)0xA5, (byte)0xCB,
  2475. };
  2476. BigInteger bi_p = new BigInteger(pseudoPrime1);
  2477. BigInteger bi_q = new BigInteger(pseudoPrime2);
  2478. BigInteger bi_pq = (bi_p-1)*(bi_q-1);
  2479. BigInteger bi_n = bi_p * bi_q;
  2480. for(int count = 0; count < rounds; count++)
  2481. {
  2482. // generate private and public key
  2483. BigInteger bi_e = bi_pq.genCoPrime(512, rand);
  2484. BigInteger bi_d = bi_e.modInverse(bi_pq);
  2485. Console.WriteLine("\ne =\n" + bi_e.ToString(10));
  2486. Console.WriteLine("\nd =\n" + bi_d.ToString(10));
  2487. Console.WriteLine("\nn =\n" + bi_n.ToString(10) + "\n");
  2488. // generate data of random length
  2489. int t1 = 0;
  2490. while(t1 == 0)
  2491. t1 = (int)(rand.NextDouble() * 65);
  2492. bool done = false;
  2493. while(!done)
  2494. {
  2495. for(int i = 0; i < 64; i++)
  2496. {
  2497. if(i < t1)
  2498. val[i] = (byte)(rand.NextDouble() * 256);
  2499. else
  2500. val[i] = 0;
  2501. if(val[i] != 0)
  2502. done = true;
  2503. }
  2504. }
  2505. while(val[0] == 0)
  2506. val[0] = (byte)(rand.NextDouble() * 256);
  2507. Console.Write("Round = " + count);
  2508. // encrypt and decrypt data
  2509. BigInteger bi_data = new BigInteger(val, t1);
  2510. BigInteger bi_encrypted = bi_data.modPow(bi_e, bi_n);
  2511. BigInteger bi_decrypted = bi_encrypted.modPow(bi_d, bi_n);
  2512. // compare
  2513. if(bi_decrypted != bi_data)
  2514. {
  2515. Console.WriteLine("\nError at round " + count);
  2516. Console.WriteLine(bi_data + "\n");
  2517. return;
  2518. }
  2519. Console.WriteLine(" <PASSED>.");
  2520. }
  2521. }
  2522. //***********************************************************************
  2523. // Tests the correct implementation of sqrt() method.
  2524. //***********************************************************************
  2525. public static void SqrtTest(int rounds)
  2526. {
  2527. Random rand = new Random();
  2528. for(int count = 0; count < rounds; count++)
  2529. {
  2530. // generate data of random length
  2531. int t1 = 0;
  2532. while(t1 == 0)
  2533. t1 = (int)(rand.NextDouble() * 1024);
  2534. Console.Write("Round = " + count);
  2535. BigInteger a = new BigInteger();
  2536. a.genRandomBits(t1, rand);
  2537. BigInteger b = a.sqrt();
  2538. BigInteger c = (b+1)*(b+1);
  2539. // check that b is the largest integer such that b*b <= a
  2540. if(c <= a)
  2541. {
  2542. Console.WriteLine("\nError at round " + count);
  2543. Console.WriteLine(a + "\n");
  2544. return;
  2545. }
  2546. Console.WriteLine(" <PASSED>.");
  2547. }
  2548. }
  2549. public static void aMain(string[] args)
  2550. {
  2551. // Known problem -> these two pseudoprimes passes my implementation of
  2552. // primality test but failed in JDK's isProbablePrime test.
  2553. byte[] pseudoPrime1 = { (byte)0x00,
  2554. (byte)0x85, (byte)0x84, (byte)0x64, (byte)0xFD, (byte)0x70, (byte)0x6A,
  2555. (byte)0x9F, (byte)0xF0, (byte)0x94, (byte)0x0C, (byte)0x3E, (byte)0x2C,
  2556. (byte)0x74, (byte)0x34, (byte)0x05, (byte)0xC9, (byte)0x55, (byte)0xB3,
  2557. (byte)0x85, (byte)0x32, (byte)0x98, (byte)0x71, (byte)0xF9, (byte)0x41,
  2558. (byte)0x21, (byte)0x5F, (byte)0x02, (byte)0x9E, (byte)0xEA, (byte)0x56,
  2559. (byte)0x8D, (byte)0x8C, (byte)0x44, (byte)0xCC, (byte)0xEE, (byte)0xEE,
  2560. (byte)0x3D, (byte)0x2C, (byte)0x9D, (byte)0x2C, (byte)0x12, (byte)0x41,
  2561. (byte)0x1E, (byte)0xF1, (byte)0xC5, (byte)0x32, (byte)0xC3, (byte)0xAA,
  2562. (byte)0x31, (byte)0x4A, (byte)0x52, (byte)0xD8, (byte)0xE8, (byte)0xAF,
  2563. (byte)0x42, (byte)0xF4, (byte)0x72, (byte)0xA1, (byte)0x2A, (byte)0x0D,
  2564. (byte)0x97, (byte)0xB1, (byte)0x31, (byte)0xB3,
  2565. };
  2566. byte[] pseudoPrime2 = { (byte)0x00,
  2567. (byte)0x99, (byte)0x98, (byte)0xCA, (byte)0xB8, (byte)0x5E, (byte)0xD7,
  2568. (byte)0xE5, (byte)0xDC, (byte)0x28, (byte)0x5C, (byte)0x6F, (byte)0x0E,
  2569. (byte)0x15, (byte)0x09, (byte)0x59, (byte)0x6E, (byte)0x84, (byte)0xF3,
  2570. (byte)0x81, (byte)0xCD, (byte)0xDE, (byte)0x42, (byte)0xDC, (byte)0x93,
  2571. (byte)0xC2, (byte)0x7A, (byte)0x62, (byte)0xAC, (byte)0x6C, (byte)0xAF,
  2572. (byte)0xDE, (byte)0x74, (byte)0xE3, (byte)0xCB, (byte)0x60, (byte)0x20,
  2573. (byte)0x38, (byte)0x9C, (byte)0x21, (byte)0xC3, (byte)0xDC, (byte)0xC8,
  2574. (byte)0xA2, (byte)0x4D, (byte)0xC6, (byte)0x2A, (byte)0x35, (byte)0x7F,
  2575. (byte)0xF3, (byte)0xA9, (byte)0xE8, (byte)0x1D, (byte)0x7B, (byte)0x2C,
  2576. (byte)0x78, (byte)0xFA, (byte)0xB8, (byte)0x02, (byte)0x55, (byte)0x80,
  2577. (byte)0x9B, (byte)0xC2, (byte)0xA5, (byte)0xCB,
  2578. };
  2579. Console.WriteLine("List of primes < 2000\n---------------------");
  2580. int limit = 100, count = 0;
  2581. for(int i = 0; i < 2000; i++)
  2582. {
  2583. if(i >= limit)
  2584. {
  2585. Console.WriteLine();
  2586. limit += 100;
  2587. }
  2588. BigInteger p = new BigInteger(-i);
  2589. if(p.isProbablePrime())
  2590. {
  2591. Console.Write(i + ", ");
  2592. count++;
  2593. }
  2594. }
  2595. Console.WriteLine("\nCount = " + count);
  2596. BigInteger bi1 = new BigInteger(pseudoPrime1);
  2597. Console.WriteLine("\n\nPrimality testing for\n" + bi1.ToString() + "\n");
  2598. Console.WriteLine("SolovayStrassenTest(5) = " + bi1.SolovayStrassenTest(5));
  2599. Console.WriteLine("RabinMillerTest(5) = " + bi1.RabinMillerTest(5));
  2600. Console.WriteLine("FermatLittleTest(5) = " + bi1.FermatLittleTest(5));
  2601. Console.WriteLine("isProbablePrime() = " + bi1.isProbablePrime());
  2602. Console.Write("\nGenerating 512-bits random pseudoprime. . .");
  2603. Random rand = new Random();
  2604. BigInteger prime = BigInteger.genPseudoPrime(512, 5, rand);
  2605. Console.WriteLine("\n" + prime);
  2606. //int dwStart = System.Environment.TickCount;
  2607. //BigInteger.MulDivTest(100000);
  2608. //BigInteger.RSATest(10);
  2609. //BigInteger.RSATest2(10);
  2610. //Console.WriteLine(System.Environment.TickCount - dwStart);
  2611. }
  2612. }