BigInteger.cs 69 KB

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