BigInteger.cs 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Text;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  10. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math
  11. {
  12. #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
  13. [Serializable]
  14. #endif
  15. public class BigInteger
  16. {
  17. // The first few odd primes
  18. /*
  19. 3 5 7 11 13 17 19 23 29
  20. 31 37 41 43 47 53 59 61 67 71
  21. 73 79 83 89 97 101 103 107 109 113
  22. 127 131 137 139 149 151 157 163 167 173
  23. 179 181 191 193 197 199 211 223 227 229
  24. 233 239 241 251 257 263 269 271 277 281
  25. 283 293 307 311 313 317 331 337 347 349
  26. 353 359 367 373 379 383 389 397 401 409
  27. 419 421 431 433 439 443 449 457 461 463
  28. 467 479 487 491 499 503 509 521 523 541
  29. 547 557 563 569 571 577 587 593 599 601
  30. 607 613 617 619 631 641 643 647 653 659
  31. 661 673 677 683 691 701 709 719 727 733
  32. 739 743 751 757 761 769 773 787 797 809
  33. 811 821 823 827 829 839 853 857 859 863
  34. 877 881 883 887 907 911 919 929 937 941
  35. 947 953 967 971 977 983 991 997 1009
  36. 1013 1019 1021 1031 1033 1039 1049 1051
  37. 1061 1063 1069 1087 1091 1093 1097 1103
  38. 1109 1117 1123 1129 1151 1153 1163 1171
  39. 1181 1187 1193 1201 1213 1217 1223 1229
  40. 1231 1237 1249 1259 1277 1279 1283 1289
  41. */
  42. // Each list has a product < 2^31
  43. internal static readonly int[][] primeLists = new int[][]
  44. {
  45. new int[]{ 3, 5, 7, 11, 13, 17, 19, 23 },
  46. new int[]{ 29, 31, 37, 41, 43 },
  47. new int[]{ 47, 53, 59, 61, 67 },
  48. new int[]{ 71, 73, 79, 83 },
  49. new int[]{ 89, 97, 101, 103 },
  50. new int[]{ 107, 109, 113, 127 },
  51. new int[]{ 131, 137, 139, 149 },
  52. new int[]{ 151, 157, 163, 167 },
  53. new int[]{ 173, 179, 181, 191 },
  54. new int[]{ 193, 197, 199, 211 },
  55. new int[]{ 223, 227, 229 },
  56. new int[]{ 233, 239, 241 },
  57. new int[]{ 251, 257, 263 },
  58. new int[]{ 269, 271, 277 },
  59. new int[]{ 281, 283, 293 },
  60. new int[]{ 307, 311, 313 },
  61. new int[]{ 317, 331, 337 },
  62. new int[]{ 347, 349, 353 },
  63. new int[]{ 359, 367, 373 },
  64. new int[]{ 379, 383, 389 },
  65. new int[]{ 397, 401, 409 },
  66. new int[]{ 419, 421, 431 },
  67. new int[]{ 433, 439, 443 },
  68. new int[]{ 449, 457, 461 },
  69. new int[]{ 463, 467, 479 },
  70. new int[]{ 487, 491, 499 },
  71. new int[]{ 503, 509, 521 },
  72. new int[]{ 523, 541, 547 },
  73. new int[]{ 557, 563, 569 },
  74. new int[]{ 571, 577, 587 },
  75. new int[]{ 593, 599, 601 },
  76. new int[]{ 607, 613, 617 },
  77. new int[]{ 619, 631, 641 },
  78. new int[]{ 643, 647, 653 },
  79. new int[]{ 659, 661, 673 },
  80. new int[]{ 677, 683, 691 },
  81. new int[]{ 701, 709, 719 },
  82. new int[]{ 727, 733, 739 },
  83. new int[]{ 743, 751, 757 },
  84. new int[]{ 761, 769, 773 },
  85. new int[]{ 787, 797, 809 },
  86. new int[]{ 811, 821, 823 },
  87. new int[]{ 827, 829, 839 },
  88. new int[]{ 853, 857, 859 },
  89. new int[]{ 863, 877, 881 },
  90. new int[]{ 883, 887, 907 },
  91. new int[]{ 911, 919, 929 },
  92. new int[]{ 937, 941, 947 },
  93. new int[]{ 953, 967, 971 },
  94. new int[]{ 977, 983, 991 },
  95. new int[]{ 997, 1009, 1013 },
  96. new int[]{ 1019, 1021, 1031 },
  97. new int[]{ 1033, 1039, 1049 },
  98. new int[]{ 1051, 1061, 1063 },
  99. new int[]{ 1069, 1087, 1091 },
  100. new int[]{ 1093, 1097, 1103 },
  101. new int[]{ 1109, 1117, 1123 },
  102. new int[]{ 1129, 1151, 1153 },
  103. new int[]{ 1163, 1171, 1181 },
  104. new int[]{ 1187, 1193, 1201 },
  105. new int[]{ 1213, 1217, 1223 },
  106. new int[]{ 1229, 1231, 1237 },
  107. new int[]{ 1249, 1259, 1277 },
  108. new int[]{ 1279, 1283, 1289 },
  109. };
  110. internal static readonly int[] primeProducts;
  111. private const long IMASK = 0xFFFFFFFFL;
  112. private const ulong UIMASK = 0xFFFFFFFFUL;
  113. private static readonly int[] ZeroMagnitude = new int[0];
  114. private static readonly byte[] ZeroEncoding = new byte[0];
  115. private static readonly BigInteger[] SMALL_CONSTANTS = new BigInteger[17];
  116. public static readonly BigInteger Zero;
  117. public static readonly BigInteger One;
  118. public static readonly BigInteger Two;
  119. public static readonly BigInteger Three;
  120. public static readonly BigInteger Four;
  121. public static readonly BigInteger Ten;
  122. //private readonly static byte[] BitCountTable =
  123. //{
  124. // 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  125. // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  126. // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  127. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  128. // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  129. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  130. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  131. // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  132. // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  133. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  134. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  135. // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  136. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  137. // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  138. // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  139. // 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
  140. //};
  141. private readonly static byte[] BitLengthTable =
  142. {
  143. 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  144. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  145. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  146. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  147. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  153. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  154. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  155. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  156. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  157. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  158. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
  159. };
  160. // TODO Parse radix-2 64 bits at a time and radix-8 63 bits at a time
  161. private const int chunk2 = 1, chunk8 = 1, chunk10 = 19, chunk16 = 16;
  162. private static readonly BigInteger radix2, radix2E, radix8, radix8E, radix10, radix10E, radix16, radix16E;
  163. private static readonly SecureRandom RandomSource = new SecureRandom();
  164. /*
  165. * These are the threshold bit-lengths (of an exponent) where we increase the window size.
  166. * They are calculated according to the expected savings in multiplications.
  167. * Some squares will also be saved on average, but we offset these against the extra storage costs.
  168. */
  169. private static readonly int[] ExpWindowThresholds = { 7, 25, 81, 241, 673, 1793, 4609, Int32.MaxValue };
  170. private const int BitsPerByte = 8;
  171. private const int BitsPerInt = 32;
  172. private const int BytesPerInt = 4;
  173. static BigInteger()
  174. {
  175. Zero = new BigInteger(0, ZeroMagnitude, false);
  176. Zero.nBits = 0; Zero.nBitLength = 0;
  177. SMALL_CONSTANTS[0] = Zero;
  178. for (uint i = 1; i < SMALL_CONSTANTS.Length; ++i)
  179. {
  180. SMALL_CONSTANTS[i] = CreateUValueOf(i);
  181. }
  182. One = SMALL_CONSTANTS[1];
  183. Two = SMALL_CONSTANTS[2];
  184. Three = SMALL_CONSTANTS[3];
  185. Four = SMALL_CONSTANTS[4];
  186. Ten = SMALL_CONSTANTS[10];
  187. radix2 = ValueOf(2);
  188. radix2E = radix2.Pow(chunk2);
  189. radix8 = ValueOf(8);
  190. radix8E = radix8.Pow(chunk8);
  191. radix10 = ValueOf(10);
  192. radix10E = radix10.Pow(chunk10);
  193. radix16 = ValueOf(16);
  194. radix16E = radix16.Pow(chunk16);
  195. primeProducts = new int[primeLists.Length];
  196. for (int i = 0; i < primeLists.Length; ++i)
  197. {
  198. int[] primeList = primeLists[i];
  199. int product = primeList[0];
  200. for (int j = 1; j < primeList.Length; ++j)
  201. {
  202. product *= primeList[j];
  203. }
  204. primeProducts[i] = product;
  205. }
  206. }
  207. private int[] magnitude; // array of ints with [0] being the most significant
  208. private int sign; // -1 means -ve; +1 means +ve; 0 means 0;
  209. private int nBits = -1; // cache BitCount() value
  210. private int nBitLength = -1; // cache BitLength() value
  211. private int mQuote = 0; // -m^(-1) mod b, b = 2^32 (see Montgomery mult.), 0 when uninitialised
  212. private static int GetByteLength(
  213. int nBits)
  214. {
  215. return (nBits + BitsPerByte - 1) / BitsPerByte;
  216. }
  217. public static BigInteger Arbitrary(int sizeInBits)
  218. {
  219. return new BigInteger(sizeInBits, RandomSource);
  220. }
  221. private BigInteger(
  222. int signum,
  223. int[] mag,
  224. bool checkMag)
  225. {
  226. if (checkMag)
  227. {
  228. int i = 0;
  229. while (i < mag.Length && mag[i] == 0)
  230. {
  231. ++i;
  232. }
  233. if (i == mag.Length)
  234. {
  235. this.sign = 0;
  236. this.magnitude = ZeroMagnitude;
  237. }
  238. else
  239. {
  240. this.sign = signum;
  241. if (i == 0)
  242. {
  243. this.magnitude = mag;
  244. }
  245. else
  246. {
  247. // strip leading 0 words
  248. this.magnitude = new int[mag.Length - i];
  249. Array.Copy(mag, i, this.magnitude, 0, this.magnitude.Length);
  250. }
  251. }
  252. }
  253. else
  254. {
  255. this.sign = signum;
  256. this.magnitude = mag;
  257. }
  258. }
  259. public BigInteger(
  260. string value)
  261. : this(value, 10)
  262. {
  263. }
  264. public BigInteger(
  265. string str,
  266. int radix)
  267. {
  268. if (str.Length == 0)
  269. throw new FormatException("Zero length BigInteger");
  270. NumberStyles style;
  271. int chunk;
  272. BigInteger r;
  273. BigInteger rE;
  274. switch (radix)
  275. {
  276. case 2:
  277. // Is there anyway to restrict to binary digits?
  278. style = NumberStyles.Integer;
  279. chunk = chunk2;
  280. r = radix2;
  281. rE = radix2E;
  282. break;
  283. case 8:
  284. // Is there anyway to restrict to octal digits?
  285. style = NumberStyles.Integer;
  286. chunk = chunk8;
  287. r = radix8;
  288. rE = radix8E;
  289. break;
  290. case 10:
  291. // This style seems to handle spaces and minus sign already (our processing redundant?)
  292. style = NumberStyles.Integer;
  293. chunk = chunk10;
  294. r = radix10;
  295. rE = radix10E;
  296. break;
  297. case 16:
  298. // TODO Should this be HexNumber?
  299. style = NumberStyles.AllowHexSpecifier;
  300. chunk = chunk16;
  301. r = radix16;
  302. rE = radix16E;
  303. break;
  304. default:
  305. throw new FormatException("Only bases 2, 8, 10, or 16 allowed");
  306. }
  307. int index = 0;
  308. sign = 1;
  309. if (str[0] == '-')
  310. {
  311. if (str.Length == 1)
  312. throw new FormatException("Zero length BigInteger");
  313. sign = -1;
  314. index = 1;
  315. }
  316. // strip leading zeros from the string str
  317. while (index < str.Length && Int32.Parse(str[index].ToString(), style) == 0)
  318. {
  319. index++;
  320. }
  321. if (index >= str.Length)
  322. {
  323. // zero value - we're done
  324. sign = 0;
  325. magnitude = ZeroMagnitude;
  326. return;
  327. }
  328. //////
  329. // could we work out the max number of ints required to store
  330. // str.Length digits in the given base, then allocate that
  331. // storage in one hit?, then Generate the magnitude in one hit too?
  332. //////
  333. BigInteger b = Zero;
  334. int next = index + chunk;
  335. if (next <= str.Length)
  336. {
  337. do
  338. {
  339. string s = str.Substring(index, chunk);
  340. ulong i = ulong.Parse(s, style);
  341. BigInteger bi = CreateUValueOf(i);
  342. switch (radix)
  343. {
  344. case 2:
  345. // TODO Need this because we are parsing in radix 10 above
  346. if (i >= 2)
  347. throw new FormatException("Bad character in radix 2 string: " + s);
  348. // TODO Parse 64 bits at a time
  349. b = b.ShiftLeft(1);
  350. break;
  351. case 8:
  352. // TODO Need this because we are parsing in radix 10 above
  353. if (i >= 8)
  354. throw new FormatException("Bad character in radix 8 string: " + s);
  355. // TODO Parse 63 bits at a time
  356. b = b.ShiftLeft(3);
  357. break;
  358. case 16:
  359. b = b.ShiftLeft(64);
  360. break;
  361. default:
  362. b = b.Multiply(rE);
  363. break;
  364. }
  365. b = b.Add(bi);
  366. index = next;
  367. next += chunk;
  368. }
  369. while (next <= str.Length);
  370. }
  371. if (index < str.Length)
  372. {
  373. string s = str.Substring(index);
  374. ulong i = ulong.Parse(s, style);
  375. BigInteger bi = CreateUValueOf(i);
  376. if (b.sign > 0)
  377. {
  378. if (radix == 2)
  379. {
  380. // NB: Can't reach here since we are parsing one char at a time
  381. Debug.Assert(false);
  382. // TODO Parse all bits at once
  383. // b = b.ShiftLeft(s.Length);
  384. }
  385. else if (radix == 8)
  386. {
  387. // NB: Can't reach here since we are parsing one char at a time
  388. Debug.Assert(false);
  389. // TODO Parse all bits at once
  390. // b = b.ShiftLeft(s.Length * 3);
  391. }
  392. else if (radix == 16)
  393. {
  394. b = b.ShiftLeft(s.Length << 2);
  395. }
  396. else
  397. {
  398. b = b.Multiply(r.Pow(s.Length));
  399. }
  400. b = b.Add(bi);
  401. }
  402. else
  403. {
  404. b = bi;
  405. }
  406. }
  407. // Note: This is the previous (slower) algorithm
  408. // while (index < value.Length)
  409. // {
  410. // char c = value[index];
  411. // string s = c.ToString();
  412. // int i = Int32.Parse(s, style);
  413. //
  414. // b = b.Multiply(r).Add(ValueOf(i));
  415. // index++;
  416. // }
  417. magnitude = b.magnitude;
  418. }
  419. public BigInteger(
  420. byte[] bytes)
  421. : this(bytes, 0, bytes.Length)
  422. {
  423. }
  424. public BigInteger(
  425. byte[] bytes,
  426. int offset,
  427. int length)
  428. {
  429. if (length == 0)
  430. throw new FormatException("Zero length BigInteger");
  431. // TODO Move this processing into MakeMagnitude (provide sign argument)
  432. if ((sbyte)bytes[offset] < 0)
  433. {
  434. this.sign = -1;
  435. int end = offset + length;
  436. int iBval;
  437. // strip leading sign bytes
  438. for (iBval = offset; iBval < end && ((sbyte)bytes[iBval] == -1); iBval++)
  439. {
  440. }
  441. if (iBval >= end)
  442. {
  443. this.magnitude = One.magnitude;
  444. }
  445. else
  446. {
  447. int numBytes = end - iBval;
  448. byte[] inverse = new byte[numBytes];
  449. int index = 0;
  450. while (index < numBytes)
  451. {
  452. inverse[index++] = (byte)~bytes[iBval++];
  453. }
  454. Debug.Assert(iBval == end);
  455. while (inverse[--index] == byte.MaxValue)
  456. {
  457. inverse[index] = byte.MinValue;
  458. }
  459. inverse[index]++;
  460. this.magnitude = MakeMagnitude(inverse, 0, inverse.Length);
  461. }
  462. }
  463. else
  464. {
  465. // strip leading zero bytes and return magnitude bytes
  466. this.magnitude = MakeMagnitude(bytes, offset, length);
  467. this.sign = this.magnitude.Length > 0 ? 1 : 0;
  468. }
  469. }
  470. private static int[] MakeMagnitude(
  471. byte[] bytes,
  472. int offset,
  473. int length)
  474. {
  475. int end = offset + length;
  476. // strip leading zeros
  477. int firstSignificant;
  478. for (firstSignificant = offset; firstSignificant < end
  479. && bytes[firstSignificant] == 0; firstSignificant++)
  480. {
  481. }
  482. if (firstSignificant >= end)
  483. {
  484. return ZeroMagnitude;
  485. }
  486. int nInts = (end - firstSignificant + 3) / BytesPerInt;
  487. int bCount = (end - firstSignificant) % BytesPerInt;
  488. if (bCount == 0)
  489. {
  490. bCount = BytesPerInt;
  491. }
  492. if (nInts < 1)
  493. {
  494. return ZeroMagnitude;
  495. }
  496. int[] mag = new int[nInts];
  497. int v = 0;
  498. int magnitudeIndex = 0;
  499. for (int i = firstSignificant; i < end; ++i)
  500. {
  501. v <<= 8;
  502. v |= bytes[i] & 0xff;
  503. bCount--;
  504. if (bCount <= 0)
  505. {
  506. mag[magnitudeIndex] = v;
  507. magnitudeIndex++;
  508. bCount = BytesPerInt;
  509. v = 0;
  510. }
  511. }
  512. if (magnitudeIndex < mag.Length)
  513. {
  514. mag[magnitudeIndex] = v;
  515. }
  516. return mag;
  517. }
  518. public BigInteger(
  519. int sign,
  520. byte[] bytes)
  521. : this(sign, bytes, 0, bytes.Length)
  522. {
  523. }
  524. public BigInteger(
  525. int sign,
  526. byte[] bytes,
  527. int offset,
  528. int length)
  529. {
  530. if (sign < -1 || sign > 1)
  531. throw new FormatException("Invalid sign value");
  532. if (sign == 0)
  533. {
  534. this.sign = 0;
  535. this.magnitude = ZeroMagnitude;
  536. }
  537. else
  538. {
  539. // copy bytes
  540. this.magnitude = MakeMagnitude(bytes, offset, length);
  541. this.sign = this.magnitude.Length < 1 ? 0 : sign;
  542. }
  543. }
  544. public BigInteger(
  545. int sizeInBits,
  546. Random random)
  547. {
  548. if (sizeInBits < 0)
  549. throw new ArgumentException("sizeInBits must be non-negative");
  550. this.nBits = -1;
  551. this.nBitLength = -1;
  552. if (sizeInBits == 0)
  553. {
  554. this.sign = 0;
  555. this.magnitude = ZeroMagnitude;
  556. return;
  557. }
  558. int nBytes = GetByteLength(sizeInBits);
  559. byte[] b = new byte[nBytes];
  560. random.NextBytes(b);
  561. // strip off any excess bits in the MSB
  562. int xBits = BitsPerByte * nBytes - sizeInBits;
  563. b[0] &= (byte)(255U >> xBits);
  564. this.magnitude = MakeMagnitude(b, 0, b.Length);
  565. this.sign = this.magnitude.Length < 1 ? 0 : 1;
  566. }
  567. public BigInteger(
  568. int bitLength,
  569. int certainty,
  570. Random random)
  571. {
  572. if (bitLength < 2)
  573. throw new ArithmeticException("bitLength < 2");
  574. this.sign = 1;
  575. this.nBitLength = bitLength;
  576. if (bitLength == 2)
  577. {
  578. this.magnitude = random.Next(2) == 0
  579. ? Two.magnitude
  580. : Three.magnitude;
  581. return;
  582. }
  583. int nBytes = GetByteLength(bitLength);
  584. byte[] b = new byte[nBytes];
  585. int xBits = BitsPerByte * nBytes - bitLength;
  586. byte mask = (byte)(255U >> xBits);
  587. byte lead = (byte)(1 << (7 - xBits));
  588. for (;;)
  589. {
  590. random.NextBytes(b);
  591. // strip off any excess bits in the MSB
  592. b[0] &= mask;
  593. // ensure the leading bit is 1 (to meet the strength requirement)
  594. b[0] |= lead;
  595. // ensure the trailing bit is 1 (i.e. must be odd)
  596. b[nBytes - 1] |= 1;
  597. this.magnitude = MakeMagnitude(b, 0, b.Length);
  598. this.nBits = -1;
  599. this.mQuote = 0;
  600. if (certainty < 1)
  601. break;
  602. if (CheckProbablePrime(certainty, random, true))
  603. break;
  604. for (int j = 1; j < (magnitude.Length - 1); ++j)
  605. {
  606. this.magnitude[j] ^= random.Next();
  607. if (CheckProbablePrime(certainty, random, true))
  608. return;
  609. }
  610. }
  611. }
  612. public BigInteger Abs()
  613. {
  614. return sign >= 0 ? this : Negate();
  615. }
  616. /**
  617. * return a = a + b - b preserved.
  618. */
  619. private static int[] AddMagnitudes(
  620. int[] a,
  621. int[] b)
  622. {
  623. int tI = a.Length - 1;
  624. int vI = b.Length - 1;
  625. long m = 0;
  626. while (vI >= 0)
  627. {
  628. m += ((long)(uint)a[tI] + (long)(uint)b[vI--]);
  629. a[tI--] = (int)m;
  630. m = (long)((ulong)m >> 32);
  631. }
  632. if (m != 0)
  633. {
  634. while (tI >= 0 && ++a[tI--] == 0)
  635. {
  636. }
  637. }
  638. return a;
  639. }
  640. public BigInteger Add(
  641. BigInteger value)
  642. {
  643. if (this.sign == 0)
  644. return value;
  645. if (this.sign != value.sign)
  646. {
  647. if (value.sign == 0)
  648. return this;
  649. if (value.sign < 0)
  650. return Subtract(value.Negate());
  651. return value.Subtract(Negate());
  652. }
  653. return AddToMagnitude(value.magnitude);
  654. }
  655. private BigInteger AddToMagnitude(
  656. int[] magToAdd)
  657. {
  658. int[] big, small;
  659. if (this.magnitude.Length < magToAdd.Length)
  660. {
  661. big = magToAdd;
  662. small = this.magnitude;
  663. }
  664. else
  665. {
  666. big = this.magnitude;
  667. small = magToAdd;
  668. }
  669. // Conservatively avoid over-allocation when no overflow possible
  670. uint limit = uint.MaxValue;
  671. if (big.Length == small.Length)
  672. limit -= (uint) small[0];
  673. bool possibleOverflow = (uint) big[0] >= limit;
  674. int[] bigCopy;
  675. if (possibleOverflow)
  676. {
  677. bigCopy = new int[big.Length + 1];
  678. big.CopyTo(bigCopy, 1);
  679. }
  680. else
  681. {
  682. bigCopy = (int[]) big.Clone();
  683. }
  684. bigCopy = AddMagnitudes(bigCopy, small);
  685. return new BigInteger(this.sign, bigCopy, possibleOverflow);
  686. }
  687. public BigInteger And(
  688. BigInteger value)
  689. {
  690. if (this.sign == 0 || value.sign == 0)
  691. {
  692. return Zero;
  693. }
  694. int[] aMag = this.sign > 0
  695. ? this.magnitude
  696. : Add(One).magnitude;
  697. int[] bMag = value.sign > 0
  698. ? value.magnitude
  699. : value.Add(One).magnitude;
  700. bool resultNeg = sign < 0 && value.sign < 0;
  701. int resultLength = System.Math.Max(aMag.Length, bMag.Length);
  702. int[] resultMag = new int[resultLength];
  703. int aStart = resultMag.Length - aMag.Length;
  704. int bStart = resultMag.Length - bMag.Length;
  705. for (int i = 0; i < resultMag.Length; ++i)
  706. {
  707. int aWord = i >= aStart ? aMag[i - aStart] : 0;
  708. int bWord = i >= bStart ? bMag[i - bStart] : 0;
  709. if (this.sign < 0)
  710. {
  711. aWord = ~aWord;
  712. }
  713. if (value.sign < 0)
  714. {
  715. bWord = ~bWord;
  716. }
  717. resultMag[i] = aWord & bWord;
  718. if (resultNeg)
  719. {
  720. resultMag[i] = ~resultMag[i];
  721. }
  722. }
  723. BigInteger result = new BigInteger(1, resultMag, true);
  724. // TODO Optimise this case
  725. if (resultNeg)
  726. {
  727. result = result.Not();
  728. }
  729. return result;
  730. }
  731. public BigInteger AndNot(
  732. BigInteger val)
  733. {
  734. return And(val.Not());
  735. }
  736. public int BitCount
  737. {
  738. get
  739. {
  740. if (nBits == -1)
  741. {
  742. if (sign < 0)
  743. {
  744. // TODO Optimise this case
  745. nBits = Not().BitCount;
  746. }
  747. else
  748. {
  749. int sum = 0;
  750. for (int i = 0; i < magnitude.Length; ++i)
  751. {
  752. sum += BitCnt(magnitude[i]);
  753. }
  754. nBits = sum;
  755. }
  756. }
  757. return nBits;
  758. }
  759. }
  760. public static int BitCnt(int i)
  761. {
  762. uint u = (uint)i;
  763. u = u - ((u >> 1) & 0x55555555);
  764. u = (u & 0x33333333) + ((u >> 2) & 0x33333333);
  765. u = (u + (u >> 4)) & 0x0f0f0f0f;
  766. u += (u >> 8);
  767. u += (u >> 16);
  768. u &= 0x3f;
  769. return (int)u;
  770. }
  771. private static int CalcBitLength(int sign, int indx, int[] mag)
  772. {
  773. for (;;)
  774. {
  775. if (indx >= mag.Length)
  776. return 0;
  777. if (mag[indx] != 0)
  778. break;
  779. ++indx;
  780. }
  781. // bit length for everything after the first int
  782. int bitLength = 32 * ((mag.Length - indx) - 1);
  783. // and determine bitlength of first int
  784. int firstMag = mag[indx];
  785. bitLength += BitLen(firstMag);
  786. // Check for negative powers of two
  787. if (sign < 0 && ((firstMag & -firstMag) == firstMag))
  788. {
  789. do
  790. {
  791. if (++indx >= mag.Length)
  792. {
  793. --bitLength;
  794. break;
  795. }
  796. }
  797. while (mag[indx] == 0);
  798. }
  799. return bitLength;
  800. }
  801. public int BitLength
  802. {
  803. get
  804. {
  805. if (nBitLength == -1)
  806. {
  807. nBitLength = sign == 0
  808. ? 0
  809. : CalcBitLength(sign, 0, magnitude);
  810. }
  811. return nBitLength;
  812. }
  813. }
  814. //
  815. // BitLen(value) is the number of bits in value.
  816. //
  817. internal static int BitLen(int w)
  818. {
  819. uint v = (uint)w;
  820. uint t = v >> 24;
  821. if (t != 0)
  822. return 24 + BitLengthTable[t];
  823. t = v >> 16;
  824. if (t != 0)
  825. return 16 + BitLengthTable[t];
  826. t = v >> 8;
  827. if (t != 0)
  828. return 8 + BitLengthTable[t];
  829. return BitLengthTable[v];
  830. }
  831. private bool QuickPow2Check()
  832. {
  833. return sign > 0 && nBits == 1;
  834. }
  835. public int CompareTo(
  836. object obj)
  837. {
  838. return CompareTo((BigInteger)obj);
  839. }
  840. /**
  841. * unsigned comparison on two arrays - note the arrays may
  842. * start with leading zeros.
  843. */
  844. private static int CompareTo(
  845. int xIndx,
  846. int[] x,
  847. int yIndx,
  848. int[] y)
  849. {
  850. while (xIndx != x.Length && x[xIndx] == 0)
  851. {
  852. xIndx++;
  853. }
  854. while (yIndx != y.Length && y[yIndx] == 0)
  855. {
  856. yIndx++;
  857. }
  858. return CompareNoLeadingZeroes(xIndx, x, yIndx, y);
  859. }
  860. private static int CompareNoLeadingZeroes(
  861. int xIndx,
  862. int[] x,
  863. int yIndx,
  864. int[] y)
  865. {
  866. int diff = (x.Length - y.Length) - (xIndx - yIndx);
  867. if (diff != 0)
  868. {
  869. return diff < 0 ? -1 : 1;
  870. }
  871. // lengths of magnitudes the same, test the magnitude values
  872. while (xIndx < x.Length)
  873. {
  874. uint v1 = (uint)x[xIndx++];
  875. uint v2 = (uint)y[yIndx++];
  876. if (v1 != v2)
  877. return v1 < v2 ? -1 : 1;
  878. }
  879. return 0;
  880. }
  881. public int CompareTo(
  882. BigInteger value)
  883. {
  884. return sign < value.sign ? -1
  885. : sign > value.sign ? 1
  886. : sign == 0 ? 0
  887. : sign * CompareNoLeadingZeroes(0, magnitude, 0, value.magnitude);
  888. }
  889. /**
  890. * return z = x / y - done in place (z value preserved, x contains the
  891. * remainder)
  892. */
  893. private int[] Divide(
  894. int[] x,
  895. int[] y)
  896. {
  897. int xStart = 0;
  898. while (xStart < x.Length && x[xStart] == 0)
  899. {
  900. ++xStart;
  901. }
  902. int yStart = 0;
  903. while (yStart < y.Length && y[yStart] == 0)
  904. {
  905. ++yStart;
  906. }
  907. Debug.Assert(yStart < y.Length);
  908. int xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y);
  909. int[] count;
  910. if (xyCmp > 0)
  911. {
  912. int yBitLength = CalcBitLength(1, yStart, y);
  913. int xBitLength = CalcBitLength(1, xStart, x);
  914. int shift = xBitLength - yBitLength;
  915. int[] iCount;
  916. int iCountStart = 0;
  917. int[] c;
  918. int cStart = 0;
  919. int cBitLength = yBitLength;
  920. if (shift > 0)
  921. {
  922. // iCount = ShiftLeft(One.magnitude, shift);
  923. iCount = new int[(shift >> 5) + 1];
  924. iCount[0] = 1 << (shift % 32);
  925. c = ShiftLeft(y, shift);
  926. cBitLength += shift;
  927. }
  928. else
  929. {
  930. iCount = new int[] { 1 };
  931. int len = y.Length - yStart;
  932. c = new int[len];
  933. Array.Copy(y, yStart, c, 0, len);
  934. }
  935. count = new int[iCount.Length];
  936. for (;;)
  937. {
  938. if (cBitLength < xBitLength
  939. || CompareNoLeadingZeroes(xStart, x, cStart, c) >= 0)
  940. {
  941. Subtract(xStart, x, cStart, c);
  942. AddMagnitudes(count, iCount);
  943. while (x[xStart] == 0)
  944. {
  945. if (++xStart == x.Length)
  946. return count;
  947. }
  948. //xBitLength = CalcBitLength(xStart, x);
  949. xBitLength = 32 * (x.Length - xStart - 1) + BitLen(x[xStart]);
  950. if (xBitLength <= yBitLength)
  951. {
  952. if (xBitLength < yBitLength)
  953. return count;
  954. xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y);
  955. if (xyCmp <= 0)
  956. break;
  957. }
  958. }
  959. shift = cBitLength - xBitLength;
  960. // NB: The case where c[cStart] is 1-bit is harmless
  961. if (shift == 1)
  962. {
  963. uint firstC = (uint) c[cStart] >> 1;
  964. uint firstX = (uint) x[xStart];
  965. if (firstC > firstX)
  966. ++shift;
  967. }
  968. if (shift < 2)
  969. {
  970. ShiftRightOneInPlace(cStart, c);
  971. --cBitLength;
  972. ShiftRightOneInPlace(iCountStart, iCount);
  973. }
  974. else
  975. {
  976. ShiftRightInPlace(cStart, c, shift);
  977. cBitLength -= shift;
  978. ShiftRightInPlace(iCountStart, iCount, shift);
  979. }
  980. //cStart = c.Length - ((cBitLength + 31) / 32);
  981. while (c[cStart] == 0)
  982. {
  983. ++cStart;
  984. }
  985. while (iCount[iCountStart] == 0)
  986. {
  987. ++iCountStart;
  988. }
  989. }
  990. }
  991. else
  992. {
  993. count = new int[1];
  994. }
  995. if (xyCmp == 0)
  996. {
  997. AddMagnitudes(count, One.magnitude);
  998. Array.Clear(x, xStart, x.Length - xStart);
  999. }
  1000. return count;
  1001. }
  1002. public BigInteger Divide(
  1003. BigInteger val)
  1004. {
  1005. if (val.sign == 0)
  1006. throw new ArithmeticException("Division by zero error");
  1007. if (sign == 0)
  1008. return Zero;
  1009. if (val.QuickPow2Check()) // val is power of two
  1010. {
  1011. BigInteger result = this.Abs().ShiftRight(val.Abs().BitLength - 1);
  1012. return val.sign == this.sign ? result : result.Negate();
  1013. }
  1014. int[] mag = (int[]) this.magnitude.Clone();
  1015. return new BigInteger(this.sign * val.sign, Divide(mag, val.magnitude), true);
  1016. }
  1017. public BigInteger[] DivideAndRemainder(
  1018. BigInteger val)
  1019. {
  1020. if (val.sign == 0)
  1021. throw new ArithmeticException("Division by zero error");
  1022. BigInteger[] biggies = new BigInteger[2];
  1023. if (sign == 0)
  1024. {
  1025. biggies[0] = Zero;
  1026. biggies[1] = Zero;
  1027. }
  1028. else if (val.QuickPow2Check()) // val is power of two
  1029. {
  1030. int e = val.Abs().BitLength - 1;
  1031. BigInteger quotient = this.Abs().ShiftRight(e);
  1032. int[] remainder = this.LastNBits(e);
  1033. biggies[0] = val.sign == this.sign ? quotient : quotient.Negate();
  1034. biggies[1] = new BigInteger(this.sign, remainder, true);
  1035. }
  1036. else
  1037. {
  1038. int[] remainder = (int[]) this.magnitude.Clone();
  1039. int[] quotient = Divide(remainder, val.magnitude);
  1040. biggies[0] = new BigInteger(this.sign * val.sign, quotient, true);
  1041. biggies[1] = new BigInteger(this.sign, remainder, true);
  1042. }
  1043. return biggies;
  1044. }
  1045. public override bool Equals(
  1046. object obj)
  1047. {
  1048. if (obj == this)
  1049. return true;
  1050. BigInteger biggie = obj as BigInteger;
  1051. if (biggie == null)
  1052. return false;
  1053. return sign == biggie.sign && IsEqualMagnitude(biggie);
  1054. }
  1055. private bool IsEqualMagnitude(BigInteger x)
  1056. {
  1057. int[] xMag = x.magnitude;
  1058. if (magnitude.Length != x.magnitude.Length)
  1059. return false;
  1060. for (int i = 0; i < magnitude.Length; i++)
  1061. {
  1062. if (magnitude[i] != x.magnitude[i])
  1063. return false;
  1064. }
  1065. return true;
  1066. }
  1067. public BigInteger Gcd(
  1068. BigInteger value)
  1069. {
  1070. if (value.sign == 0)
  1071. return Abs();
  1072. if (sign == 0)
  1073. return value.Abs();
  1074. BigInteger r;
  1075. BigInteger u = this;
  1076. BigInteger v = value;
  1077. while (v.sign != 0)
  1078. {
  1079. r = u.Mod(v);
  1080. u = v;
  1081. v = r;
  1082. }
  1083. return u;
  1084. }
  1085. public override int GetHashCode()
  1086. {
  1087. int hc = magnitude.Length;
  1088. if (magnitude.Length > 0)
  1089. {
  1090. hc ^= magnitude[0];
  1091. if (magnitude.Length > 1)
  1092. {
  1093. hc ^= magnitude[magnitude.Length - 1];
  1094. }
  1095. }
  1096. return sign < 0 ? ~hc : hc;
  1097. }
  1098. // TODO Make public?
  1099. private BigInteger Inc()
  1100. {
  1101. if (this.sign == 0)
  1102. return One;
  1103. if (this.sign < 0)
  1104. return new BigInteger(-1, doSubBigLil(this.magnitude, One.magnitude), true);
  1105. return AddToMagnitude(One.magnitude);
  1106. }
  1107. public int IntValue
  1108. {
  1109. get
  1110. {
  1111. if (sign == 0)
  1112. return 0;
  1113. int n = magnitude.Length;
  1114. int v = magnitude[n - 1];
  1115. return sign < 0 ? -v : v;
  1116. }
  1117. }
  1118. public int IntValueExact
  1119. {
  1120. get
  1121. {
  1122. if (BitLength > 31)
  1123. throw new ArithmeticException("BigInteger out of int range");
  1124. return IntValue;
  1125. }
  1126. }
  1127. /**
  1128. * return whether or not a BigInteger is probably prime with a
  1129. * probability of 1 - (1/2)**certainty.
  1130. * <p>From Knuth Vol 2, pg 395.</p>
  1131. */
  1132. public bool IsProbablePrime(int certainty)
  1133. {
  1134. return IsProbablePrime(certainty, false);
  1135. }
  1136. internal bool IsProbablePrime(int certainty, bool randomlySelected)
  1137. {
  1138. if (certainty <= 0)
  1139. return true;
  1140. BigInteger n = Abs();
  1141. if (!n.TestBit(0))
  1142. return n.Equals(Two);
  1143. if (n.Equals(One))
  1144. return false;
  1145. return n.CheckProbablePrime(certainty, RandomSource, randomlySelected);
  1146. }
  1147. private bool CheckProbablePrime(int certainty, Random random, bool randomlySelected)
  1148. {
  1149. Debug.Assert(certainty > 0);
  1150. Debug.Assert(CompareTo(Two) > 0);
  1151. Debug.Assert(TestBit(0));
  1152. // Try to reduce the penalty for really small numbers
  1153. int numLists = System.Math.Min(BitLength - 1, primeLists.Length);
  1154. for (int i = 0; i < numLists; ++i)
  1155. {
  1156. int test = Remainder(primeProducts[i]);
  1157. int[] primeList = primeLists[i];
  1158. for (int j = 0; j < primeList.Length; ++j)
  1159. {
  1160. int prime = primeList[j];
  1161. int qRem = test % prime;
  1162. if (qRem == 0)
  1163. {
  1164. // We may find small numbers in the list
  1165. return BitLength < 16 && IntValue == prime;
  1166. }
  1167. }
  1168. }
  1169. // TODO Special case for < 10^16 (RabinMiller fixed list)
  1170. // if (BitLength < 30)
  1171. // {
  1172. // RabinMiller against 2, 3, 5, 7, 11, 13, 23 is sufficient
  1173. // }
  1174. // TODO Is it worth trying to create a hybrid of these two?
  1175. return RabinMillerTest(certainty, random, randomlySelected);
  1176. // return SolovayStrassenTest(certainty, random);
  1177. // bool rbTest = RabinMillerTest(certainty, random);
  1178. // bool ssTest = SolovayStrassenTest(certainty, random);
  1179. //
  1180. // Debug.Assert(rbTest == ssTest);
  1181. //
  1182. // return rbTest;
  1183. }
  1184. public bool RabinMillerTest(int certainty, Random random)
  1185. {
  1186. return RabinMillerTest(certainty, random, false);
  1187. }
  1188. internal bool RabinMillerTest(int certainty, Random random, bool randomlySelected)
  1189. {
  1190. int bits = BitLength;
  1191. Debug.Assert(certainty > 0);
  1192. Debug.Assert(bits > 2);
  1193. Debug.Assert(TestBit(0));
  1194. int iterations = ((certainty - 1) / 2) + 1;
  1195. if (randomlySelected)
  1196. {
  1197. int itersFor100Cert = bits >= 1024 ? 4
  1198. : bits >= 512 ? 8
  1199. : bits >= 256 ? 16
  1200. : 50;
  1201. if (certainty < 100)
  1202. {
  1203. iterations = System.Math.Min(itersFor100Cert, iterations);
  1204. }
  1205. else
  1206. {
  1207. iterations -= 50;
  1208. iterations += itersFor100Cert;
  1209. }
  1210. }
  1211. // let n = 1 + d . 2^s
  1212. BigInteger n = this;
  1213. int s = n.GetLowestSetBitMaskFirst(-1 << 1);
  1214. Debug.Assert(s >= 1);
  1215. BigInteger r = n.ShiftRight(s);
  1216. // NOTE: Avoid conversion to/from Montgomery form and check for R/-R as result instead
  1217. BigInteger montRadix = One.ShiftLeft(32 * n.magnitude.Length).Remainder(n);
  1218. BigInteger minusMontRadix = n.Subtract(montRadix);
  1219. do
  1220. {
  1221. BigInteger a;
  1222. do
  1223. {
  1224. a = new BigInteger(n.BitLength, random);
  1225. }
  1226. while (a.sign == 0 || a.CompareTo(n) >= 0
  1227. || a.IsEqualMagnitude(montRadix) || a.IsEqualMagnitude(minusMontRadix));
  1228. BigInteger y = ModPowMonty(a, r, n, false);
  1229. if (!y.Equals(montRadix))
  1230. {
  1231. int j = 0;
  1232. while (!y.Equals(minusMontRadix))
  1233. {
  1234. if (++j == s)
  1235. return false;
  1236. y = ModPowMonty(y, Two, n, false);
  1237. if (y.Equals(montRadix))
  1238. return false;
  1239. }
  1240. }
  1241. }
  1242. while (--iterations > 0);
  1243. return true;
  1244. }
  1245. // private bool SolovayStrassenTest(
  1246. // int certainty,
  1247. // Random random)
  1248. // {
  1249. // Debug.Assert(certainty > 0);
  1250. // Debug.Assert(CompareTo(Two) > 0);
  1251. // Debug.Assert(TestBit(0));
  1252. //
  1253. // BigInteger n = this;
  1254. // BigInteger nMinusOne = n.Subtract(One);
  1255. // BigInteger e = nMinusOne.ShiftRight(1);
  1256. //
  1257. // do
  1258. // {
  1259. // BigInteger a;
  1260. // do
  1261. // {
  1262. // a = new BigInteger(nBitLength, random);
  1263. // }
  1264. // // NB: Spec says 0 < x < n, but 1 is trivial
  1265. // while (a.CompareTo(One) <= 0 || a.CompareTo(n) >= 0);
  1266. //
  1267. //
  1268. // // TODO Check this is redundant given the way Jacobi() works?
  1269. //// if (!a.Gcd(n).Equals(One))
  1270. //// return false;
  1271. //
  1272. // int x = Jacobi(a, n);
  1273. //
  1274. // if (x == 0)
  1275. // return false;
  1276. //
  1277. // BigInteger check = a.ModPow(e, n);
  1278. //
  1279. // if (x == 1 && !check.Equals(One))
  1280. // return false;
  1281. //
  1282. // if (x == -1 && !check.Equals(nMinusOne))
  1283. // return false;
  1284. //
  1285. // --certainty;
  1286. // }
  1287. // while (certainty > 0);
  1288. //
  1289. // return true;
  1290. // }
  1291. //
  1292. // private static int Jacobi(
  1293. // BigInteger a,
  1294. // BigInteger b)
  1295. // {
  1296. // Debug.Assert(a.sign >= 0);
  1297. // Debug.Assert(b.sign > 0);
  1298. // Debug.Assert(b.TestBit(0));
  1299. // Debug.Assert(a.CompareTo(b) < 0);
  1300. //
  1301. // int totalS = 1;
  1302. // for (;;)
  1303. // {
  1304. // if (a.sign == 0)
  1305. // return 0;
  1306. //
  1307. // if (a.Equals(One))
  1308. // break;
  1309. //
  1310. // int e = a.GetLowestSetBit();
  1311. //
  1312. // int bLsw = b.magnitude[b.magnitude.Length - 1];
  1313. // if ((e & 1) != 0 && ((bLsw & 7) == 3 || (bLsw & 7) == 5))
  1314. // totalS = -totalS;
  1315. //
  1316. // // TODO Confirm this is faster than later a1.Equals(One) test
  1317. // if (a.BitLength == e + 1)
  1318. // break;
  1319. // BigInteger a1 = a.ShiftRight(e);
  1320. //// if (a1.Equals(One))
  1321. //// break;
  1322. //
  1323. // int a1Lsw = a1.magnitude[a1.magnitude.Length - 1];
  1324. // if ((bLsw & 3) == 3 && (a1Lsw & 3) == 3)
  1325. // totalS = -totalS;
  1326. //
  1327. //// a = b.Mod(a1);
  1328. // a = b.Remainder(a1);
  1329. // b = a1;
  1330. // }
  1331. // return totalS;
  1332. // }
  1333. public long LongValue
  1334. {
  1335. get
  1336. {
  1337. if (sign == 0)
  1338. return 0;
  1339. int n = magnitude.Length;
  1340. long v = magnitude[n - 1] & IMASK;
  1341. if (n > 1)
  1342. {
  1343. v |= (magnitude[n - 2] & IMASK) << 32;
  1344. }
  1345. return sign < 0 ? -v : v;
  1346. }
  1347. }
  1348. public long LongValueExact
  1349. {
  1350. get
  1351. {
  1352. if (BitLength > 63)
  1353. throw new ArithmeticException("BigInteger out of long range");
  1354. return LongValue;
  1355. }
  1356. }
  1357. public BigInteger Max(
  1358. BigInteger value)
  1359. {
  1360. return CompareTo(value) > 0 ? this : value;
  1361. }
  1362. public BigInteger Min(
  1363. BigInteger value)
  1364. {
  1365. return CompareTo(value) < 0 ? this : value;
  1366. }
  1367. public BigInteger Mod(
  1368. BigInteger m)
  1369. {
  1370. if (m.sign < 1)
  1371. throw new ArithmeticException("Modulus must be positive");
  1372. BigInteger biggie = Remainder(m);
  1373. return (biggie.sign >= 0 ? biggie : biggie.Add(m));
  1374. }
  1375. public BigInteger ModInverse(
  1376. BigInteger m)
  1377. {
  1378. if (m.sign < 1)
  1379. throw new ArithmeticException("Modulus must be positive");
  1380. // TODO Too slow at the moment
  1381. // // "Fast Key Exchange with Elliptic Curve Systems" R.Schoeppel
  1382. // if (m.TestBit(0))
  1383. // {
  1384. // //The Almost Inverse Algorithm
  1385. // int k = 0;
  1386. // BigInteger B = One, C = Zero, F = this, G = m, tmp;
  1387. //
  1388. // for (;;)
  1389. // {
  1390. // // While F is even, do F=F/u, C=C*u, k=k+1.
  1391. // int zeroes = F.GetLowestSetBit();
  1392. // if (zeroes > 0)
  1393. // {
  1394. // F = F.ShiftRight(zeroes);
  1395. // C = C.ShiftLeft(zeroes);
  1396. // k += zeroes;
  1397. // }
  1398. //
  1399. // // If F = 1, then return B,k.
  1400. // if (F.Equals(One))
  1401. // {
  1402. // BigInteger half = m.Add(One).ShiftRight(1);
  1403. // BigInteger halfK = half.ModPow(BigInteger.ValueOf(k), m);
  1404. // return B.Multiply(halfK).Mod(m);
  1405. // }
  1406. //
  1407. // if (F.CompareTo(G) < 0)
  1408. // {
  1409. // tmp = G; G = F; F = tmp;
  1410. // tmp = B; B = C; C = tmp;
  1411. // }
  1412. //
  1413. // F = F.Add(G);
  1414. // B = B.Add(C);
  1415. // }
  1416. // }
  1417. if (m.QuickPow2Check())
  1418. {
  1419. return ModInversePow2(m);
  1420. }
  1421. BigInteger d = this.Remainder(m);
  1422. BigInteger x;
  1423. BigInteger gcd = ExtEuclid(d, m, out x);
  1424. if (!gcd.Equals(One))
  1425. throw new ArithmeticException("Numbers not relatively prime.");
  1426. if (x.sign < 0)
  1427. {
  1428. x = x.Add(m);
  1429. }
  1430. return x;
  1431. }
  1432. private BigInteger ModInversePow2(BigInteger m)
  1433. {
  1434. Debug.Assert(m.SignValue > 0);
  1435. Debug.Assert(m.BitCount == 1);
  1436. if (!TestBit(0))
  1437. {
  1438. throw new ArithmeticException("Numbers not relatively prime.");
  1439. }
  1440. int pow = m.BitLength - 1;
  1441. long inv64 = ModInverse64(LongValue);
  1442. if (pow < 64)
  1443. {
  1444. inv64 &= ((1L << pow) - 1);
  1445. }
  1446. BigInteger x = BigInteger.ValueOf(inv64);
  1447. if (pow > 64)
  1448. {
  1449. BigInteger d = this.Remainder(m);
  1450. int bitsCorrect = 64;
  1451. do
  1452. {
  1453. BigInteger t = x.Multiply(d).Remainder(m);
  1454. x = x.Multiply(Two.Subtract(t)).Remainder(m);
  1455. bitsCorrect <<= 1;
  1456. }
  1457. while (bitsCorrect < pow);
  1458. }
  1459. if (x.sign < 0)
  1460. {
  1461. x = x.Add(m);
  1462. }
  1463. return x;
  1464. }
  1465. private static int ModInverse32(int d)
  1466. {
  1467. // Newton's method with initial estimate "correct to 4 bits"
  1468. Debug.Assert((d & 1) != 0);
  1469. int x = d + (((d + 1) & 4) << 1); // d.x == 1 mod 2**4
  1470. Debug.Assert(((d * x) & 15) == 1);
  1471. x *= 2 - d * x; // d.x == 1 mod 2**8
  1472. x *= 2 - d * x; // d.x == 1 mod 2**16
  1473. x *= 2 - d * x; // d.x == 1 mod 2**32
  1474. Debug.Assert(d * x == 1);
  1475. return x;
  1476. }
  1477. private static long ModInverse64(long d)
  1478. {
  1479. // Newton's method with initial estimate "correct to 4 bits"
  1480. Debug.Assert((d & 1L) != 0);
  1481. long x = d + (((d + 1L) & 4L) << 1); // d.x == 1 mod 2**4
  1482. Debug.Assert(((d * x) & 15L) == 1L);
  1483. x *= 2 - d * x; // d.x == 1 mod 2**8
  1484. x *= 2 - d * x; // d.x == 1 mod 2**16
  1485. x *= 2 - d * x; // d.x == 1 mod 2**32
  1486. x *= 2 - d * x; // d.x == 1 mod 2**64
  1487. Debug.Assert(d * x == 1L);
  1488. return x;
  1489. }
  1490. /**
  1491. * Calculate the numbers u1, u2, and u3 such that:
  1492. *
  1493. * u1 * a + u2 * b = u3
  1494. *
  1495. * where u3 is the greatest common divider of a and b.
  1496. * a and b using the extended Euclid algorithm (refer p. 323
  1497. * of The Art of Computer Programming vol 2, 2nd ed).
  1498. * This also seems to have the side effect of calculating
  1499. * some form of multiplicative inverse.
  1500. *
  1501. * @param a First number to calculate gcd for
  1502. * @param b Second number to calculate gcd for
  1503. * @param u1Out the return object for the u1 value
  1504. * @return The greatest common divisor of a and b
  1505. */
  1506. private static BigInteger ExtEuclid(BigInteger a, BigInteger b, out BigInteger u1Out)
  1507. {
  1508. BigInteger u1 = One, v1 = Zero;
  1509. BigInteger u3 = a, v3 = b;
  1510. if (v3.sign > 0)
  1511. {
  1512. for (;;)
  1513. {
  1514. BigInteger[] q = u3.DivideAndRemainder(v3);
  1515. u3 = v3;
  1516. v3 = q[1];
  1517. BigInteger oldU1 = u1;
  1518. u1 = v1;
  1519. if (v3.sign <= 0)
  1520. break;
  1521. v1 = oldU1.Subtract(v1.Multiply(q[0]));
  1522. }
  1523. }
  1524. u1Out = u1;
  1525. return u3;
  1526. }
  1527. private static void ZeroOut(
  1528. int[] x)
  1529. {
  1530. Array.Clear(x, 0, x.Length);
  1531. }
  1532. public BigInteger ModPow(BigInteger e, BigInteger m)
  1533. {
  1534. if (m.sign < 1)
  1535. throw new ArithmeticException("Modulus must be positive");
  1536. if (m.Equals(One))
  1537. return Zero;
  1538. if (e.sign == 0)
  1539. return One;
  1540. if (sign == 0)
  1541. return Zero;
  1542. bool negExp = e.sign < 0;
  1543. if (negExp)
  1544. e = e.Negate();
  1545. BigInteger result = this.Mod(m);
  1546. if (!e.Equals(One))
  1547. {
  1548. if ((m.magnitude[m.magnitude.Length - 1] & 1) == 0)
  1549. {
  1550. result = ModPowBarrett(result, e, m);
  1551. }
  1552. else
  1553. {
  1554. result = ModPowMonty(result, e, m, true);
  1555. }
  1556. }
  1557. if (negExp)
  1558. result = result.ModInverse(m);
  1559. return result;
  1560. }
  1561. private static BigInteger ModPowBarrett(BigInteger b, BigInteger e, BigInteger m)
  1562. {
  1563. int k = m.magnitude.Length;
  1564. BigInteger mr = One.ShiftLeft((k + 1) << 5);
  1565. BigInteger yu = One.ShiftLeft(k << 6).Divide(m);
  1566. // Sliding window from MSW to LSW
  1567. int extraBits = 0, expLength = e.BitLength;
  1568. while (expLength > ExpWindowThresholds[extraBits])
  1569. {
  1570. ++extraBits;
  1571. }
  1572. int numPowers = 1 << extraBits;
  1573. BigInteger[] oddPowers = new BigInteger[numPowers];
  1574. oddPowers[0] = b;
  1575. BigInteger b2 = ReduceBarrett(b.Square(), m, mr, yu);
  1576. for (int i = 1; i < numPowers; ++i)
  1577. {
  1578. oddPowers[i] = ReduceBarrett(oddPowers[i - 1].Multiply(b2), m, mr, yu);
  1579. }
  1580. int[] windowList = GetWindowList(e.magnitude, extraBits);
  1581. Debug.Assert(windowList.Length > 0);
  1582. int window = windowList[0];
  1583. int mult = window & 0xFF, lastZeroes = window >> 8;
  1584. BigInteger y;
  1585. if (mult == 1)
  1586. {
  1587. y = b2;
  1588. --lastZeroes;
  1589. }
  1590. else
  1591. {
  1592. y = oddPowers[mult >> 1];
  1593. }
  1594. int windowPos = 1;
  1595. while ((window = windowList[windowPos++]) != -1)
  1596. {
  1597. mult = window & 0xFF;
  1598. int bits = lastZeroes + BitLengthTable[mult];
  1599. for (int j = 0; j < bits; ++j)
  1600. {
  1601. y = ReduceBarrett(y.Square(), m, mr, yu);
  1602. }
  1603. y = ReduceBarrett(y.Multiply(oddPowers[mult >> 1]), m, mr, yu);
  1604. lastZeroes = window >> 8;
  1605. }
  1606. for (int i = 0; i < lastZeroes; ++i)
  1607. {
  1608. y = ReduceBarrett(y.Square(), m, mr, yu);
  1609. }
  1610. return y;
  1611. }
  1612. private static BigInteger ReduceBarrett(BigInteger x, BigInteger m, BigInteger mr, BigInteger yu)
  1613. {
  1614. int xLen = x.BitLength, mLen = m.BitLength;
  1615. if (xLen < mLen)
  1616. return x;
  1617. if (xLen - mLen > 1)
  1618. {
  1619. int k = m.magnitude.Length;
  1620. BigInteger q1 = x.DivideWords(k - 1);
  1621. BigInteger q2 = q1.Multiply(yu); // TODO Only need partial multiplication here
  1622. BigInteger q3 = q2.DivideWords(k + 1);
  1623. BigInteger r1 = x.RemainderWords(k + 1);
  1624. BigInteger r2 = q3.Multiply(m); // TODO Only need partial multiplication here
  1625. BigInteger r3 = r2.RemainderWords(k + 1);
  1626. x = r1.Subtract(r3);
  1627. if (x.sign < 0)
  1628. {
  1629. x = x.Add(mr);
  1630. }
  1631. }
  1632. while (x.CompareTo(m) >= 0)
  1633. {
  1634. x = x.Subtract(m);
  1635. }
  1636. return x;
  1637. }
  1638. private static BigInteger ModPowMonty(BigInteger b, BigInteger e, BigInteger m, bool convert)
  1639. {
  1640. int n = m.magnitude.Length;
  1641. int powR = 32 * n;
  1642. bool smallMontyModulus = m.BitLength + 2 <= powR;
  1643. uint mDash = (uint)m.GetMQuote();
  1644. // tmp = this * R mod m
  1645. if (convert)
  1646. {
  1647. b = b.ShiftLeft(powR).Remainder(m);
  1648. }
  1649. int[] yAccum = new int[n + 1];
  1650. int[] zVal = b.magnitude;
  1651. Debug.Assert(zVal.Length <= n);
  1652. if (zVal.Length < n)
  1653. {
  1654. int[] tmp = new int[n];
  1655. zVal.CopyTo(tmp, n - zVal.Length);
  1656. zVal = tmp;
  1657. }
  1658. // Sliding window from MSW to LSW
  1659. int extraBits = 0;
  1660. // Filter the common case of small RSA exponents with few bits set
  1661. if (e.magnitude.Length > 1 || e.BitCount > 2)
  1662. {
  1663. int expLength = e.BitLength;
  1664. while (expLength > ExpWindowThresholds[extraBits])
  1665. {
  1666. ++extraBits;
  1667. }
  1668. }
  1669. int numPowers = 1 << extraBits;
  1670. int[][] oddPowers = new int[numPowers][];
  1671. oddPowers[0] = zVal;
  1672. int[] zSquared = Arrays.Clone(zVal);
  1673. SquareMonty(yAccum, zSquared, m.magnitude, mDash, smallMontyModulus);
  1674. for (int i = 1; i < numPowers; ++i)
  1675. {
  1676. oddPowers[i] = Arrays.Clone(oddPowers[i - 1]);
  1677. MultiplyMonty(yAccum, oddPowers[i], zSquared, m.magnitude, mDash, smallMontyModulus);
  1678. }
  1679. int[] windowList = GetWindowList(e.magnitude, extraBits);
  1680. Debug.Assert(windowList.Length > 1);
  1681. int window = windowList[0];
  1682. int mult = window & 0xFF, lastZeroes = window >> 8;
  1683. int[] yVal;
  1684. if (mult == 1)
  1685. {
  1686. yVal = zSquared;
  1687. --lastZeroes;
  1688. }
  1689. else
  1690. {
  1691. yVal = Arrays.Clone(oddPowers[mult >> 1]);
  1692. }
  1693. int windowPos = 1;
  1694. while ((window = windowList[windowPos++]) != -1)
  1695. {
  1696. mult = window & 0xFF;
  1697. int bits = lastZeroes + BitLengthTable[mult];
  1698. for (int j = 0; j < bits; ++j)
  1699. {
  1700. SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus);
  1701. }
  1702. MultiplyMonty(yAccum, yVal, oddPowers[mult >> 1], m.magnitude, mDash, smallMontyModulus);
  1703. lastZeroes = window >> 8;
  1704. }
  1705. for (int i = 0; i < lastZeroes; ++i)
  1706. {
  1707. SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus);
  1708. }
  1709. if (convert)
  1710. {
  1711. // Return y * R^(-1) mod m
  1712. MontgomeryReduce(yVal, m.magnitude, mDash);
  1713. }
  1714. else if (smallMontyModulus && CompareTo(0, yVal, 0, m.magnitude) >= 0)
  1715. {
  1716. Subtract(0, yVal, 0, m.magnitude);
  1717. }
  1718. return new BigInteger(1, yVal, true);
  1719. }
  1720. private static int[] GetWindowList(int[] mag, int extraBits)
  1721. {
  1722. int v = mag[0];
  1723. Debug.Assert(v != 0);
  1724. int leadingBits = BitLen(v);
  1725. int resultSize = (((mag.Length - 1) << 5) + leadingBits) / (1 + extraBits) + 2;
  1726. int[] result = new int[resultSize];
  1727. int resultPos = 0;
  1728. int bitPos = 33 - leadingBits;
  1729. v <<= bitPos;
  1730. int mult = 1, multLimit = 1 << extraBits;
  1731. int zeroes = 0;
  1732. int i = 0;
  1733. for (; ; )
  1734. {
  1735. for (; bitPos < 32; ++bitPos)
  1736. {
  1737. if (mult < multLimit)
  1738. {
  1739. mult = (mult << 1) | (int)((uint)v >> 31);
  1740. }
  1741. else if (v < 0)
  1742. {
  1743. result[resultPos++] = CreateWindowEntry(mult, zeroes);
  1744. mult = 1;
  1745. zeroes = 0;
  1746. }
  1747. else
  1748. {
  1749. ++zeroes;
  1750. }
  1751. v <<= 1;
  1752. }
  1753. if (++i == mag.Length)
  1754. {
  1755. result[resultPos++] = CreateWindowEntry(mult, zeroes);
  1756. break;
  1757. }
  1758. v = mag[i];
  1759. bitPos = 0;
  1760. }
  1761. result[resultPos] = -1;
  1762. return result;
  1763. }
  1764. private static int CreateWindowEntry(int mult, int zeroes)
  1765. {
  1766. while ((mult & 1) == 0)
  1767. {
  1768. mult >>= 1;
  1769. ++zeroes;
  1770. }
  1771. return mult | (zeroes << 8);
  1772. }
  1773. /**
  1774. * return w with w = x * x - w is assumed to have enough space.
  1775. */
  1776. private static int[] Square(
  1777. int[] w,
  1778. int[] x)
  1779. {
  1780. // Note: this method allows w to be only (2 * x.Length - 1) words if result will fit
  1781. // if (w.Length != 2 * x.Length)
  1782. // throw new ArgumentException("no I don't think so...");
  1783. ulong c;
  1784. int wBase = w.Length - 1;
  1785. for (int i = x.Length - 1; i > 0; --i)
  1786. {
  1787. ulong v = (uint)x[i];
  1788. c = v * v + (uint)w[wBase];
  1789. w[wBase] = (int)c;
  1790. c >>= 32;
  1791. for (int j = i - 1; j >= 0; --j)
  1792. {
  1793. ulong prod = v * (uint)x[j];
  1794. c += ((uint)w[--wBase] & UIMASK) + ((uint)prod << 1);
  1795. w[wBase] = (int)c;
  1796. c = (c >> 32) + (prod >> 31);
  1797. }
  1798. c += (uint)w[--wBase];
  1799. w[wBase] = (int)c;
  1800. if (--wBase >= 0)
  1801. {
  1802. w[wBase] = (int)(c >> 32);
  1803. }
  1804. else
  1805. {
  1806. Debug.Assert((c >> 32) == 0);
  1807. }
  1808. wBase += i;
  1809. }
  1810. c = (uint)x[0];
  1811. c = c * c + (uint)w[wBase];
  1812. w[wBase] = (int)c;
  1813. if (--wBase >= 0)
  1814. {
  1815. w[wBase] += (int)(c >> 32);
  1816. }
  1817. else
  1818. {
  1819. Debug.Assert((c >> 32) == 0);
  1820. }
  1821. return w;
  1822. }
  1823. /**
  1824. * return x with x = y * z - x is assumed to have enough space.
  1825. */
  1826. private static int[] Multiply(int[] x, int[] y, int[] z)
  1827. {
  1828. int i = z.Length;
  1829. if (i < 1)
  1830. return x;
  1831. int xBase = x.Length - y.Length;
  1832. do
  1833. {
  1834. long a = z[--i] & IMASK;
  1835. long val = 0;
  1836. if (a != 0)
  1837. {
  1838. for (int j = y.Length - 1; j >= 0; j--)
  1839. {
  1840. val += a * (y[j] & IMASK) + (x[xBase + j] & IMASK);
  1841. x[xBase + j] = (int)val;
  1842. val = (long)((ulong)val >> 32);
  1843. }
  1844. }
  1845. --xBase;
  1846. if (xBase >= 0)
  1847. {
  1848. x[xBase] = (int)val;
  1849. }
  1850. else
  1851. {
  1852. Debug.Assert(val == 0);
  1853. }
  1854. }
  1855. while (i > 0);
  1856. return x;
  1857. }
  1858. /**
  1859. * Calculate mQuote = -m^(-1) mod b with b = 2^32 (32 = word size)
  1860. */
  1861. private int GetMQuote()
  1862. {
  1863. if (mQuote != 0)
  1864. {
  1865. return mQuote; // already calculated
  1866. }
  1867. Debug.Assert(this.sign > 0);
  1868. int d = -magnitude[magnitude.Length - 1];
  1869. Debug.Assert((d & 1) != 0);
  1870. return mQuote = ModInverse32(d);
  1871. }
  1872. private static void MontgomeryReduce(int[] x, int[] m, uint mDash) // mDash = -m^(-1) mod b
  1873. {
  1874. // NOTE: Not a general purpose reduction (which would allow x up to twice the bitlength of m)
  1875. Debug.Assert(x.Length == m.Length);
  1876. int n = m.Length;
  1877. for (int i = n - 1; i >= 0; --i)
  1878. {
  1879. uint x0 = (uint)x[n - 1];
  1880. ulong t = x0 * mDash;
  1881. ulong carry = t * (uint)m[n - 1] + x0;
  1882. Debug.Assert((uint)carry == 0);
  1883. carry >>= 32;
  1884. for (int j = n - 2; j >= 0; --j)
  1885. {
  1886. carry += t * (uint)m[j] + (uint)x[j];
  1887. x[j + 1] = (int)carry;
  1888. carry >>= 32;
  1889. }
  1890. x[0] = (int)carry;
  1891. Debug.Assert(carry >> 32 == 0);
  1892. }
  1893. if (CompareTo(0, x, 0, m) >= 0)
  1894. {
  1895. Subtract(0, x, 0, m);
  1896. }
  1897. }
  1898. /**
  1899. * Montgomery multiplication: a = x * y * R^(-1) mod m
  1900. * <br/>
  1901. * Based algorithm 14.36 of Handbook of Applied Cryptography.
  1902. * <br/>
  1903. * <li> m, x, y should have length n </li>
  1904. * <li> a should have length (n + 1) </li>
  1905. * <li> b = 2^32, R = b^n </li>
  1906. * <br/>
  1907. * The result is put in x
  1908. * <br/>
  1909. * NOTE: the indices of x, y, m, a different in HAC and in Java
  1910. */
  1911. private static void MultiplyMonty(int[] a, int[] x, int[] y, int[] m, uint mDash, bool smallMontyModulus)
  1912. // mDash = -m^(-1) mod b
  1913. {
  1914. int n = m.Length;
  1915. if (n == 1)
  1916. {
  1917. x[0] = (int)MultiplyMontyNIsOne((uint)x[0], (uint)y[0], (uint)m[0], mDash);
  1918. return;
  1919. }
  1920. uint y0 = (uint)y[n - 1];
  1921. int aMax;
  1922. {
  1923. ulong xi = (uint)x[n - 1];
  1924. ulong carry = xi * y0;
  1925. ulong t = (uint)carry * mDash;
  1926. ulong prod2 = t * (uint)m[n - 1];
  1927. carry += (uint)prod2;
  1928. Debug.Assert((uint)carry == 0);
  1929. carry = (carry >> 32) + (prod2 >> 32);
  1930. for (int j = n - 2; j >= 0; --j)
  1931. {
  1932. ulong prod1 = xi * (uint)y[j];
  1933. prod2 = t * (uint)m[j];
  1934. carry += (prod1 & UIMASK) + (uint)prod2;
  1935. a[j + 2] = (int)carry;
  1936. carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32);
  1937. }
  1938. a[1] = (int)carry;
  1939. aMax = (int)(carry >> 32);
  1940. }
  1941. for (int i = n - 2; i >= 0; --i)
  1942. {
  1943. uint a0 = (uint)a[n];
  1944. ulong xi = (uint)x[i];
  1945. ulong prod1 = xi * y0;
  1946. ulong carry = (prod1 & UIMASK) + a0;
  1947. ulong t = (uint)carry * mDash;
  1948. ulong prod2 = t * (uint)m[n - 1];
  1949. carry += (uint)prod2;
  1950. Debug.Assert((uint)carry == 0);
  1951. carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32);
  1952. for (int j = n - 2; j >= 0; --j)
  1953. {
  1954. prod1 = xi * (uint)y[j];
  1955. prod2 = t * (uint)m[j];
  1956. carry += (prod1 & UIMASK) + (uint)prod2 + (uint)a[j + 1];
  1957. a[j + 2] = (int)carry;
  1958. carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32);
  1959. }
  1960. carry += (uint)aMax;
  1961. a[1] = (int)carry;
  1962. aMax = (int)(carry >> 32);
  1963. }
  1964. a[0] = aMax;
  1965. if (!smallMontyModulus && CompareTo(0, a, 0, m) >= 0)
  1966. {
  1967. Subtract(0, a, 0, m);
  1968. }
  1969. Array.Copy(a, 1, x, 0, n);
  1970. }
  1971. private static void SquareMonty(int[] a, int[] x, int[] m, uint mDash, bool smallMontyModulus)
  1972. // mDash = -m^(-1) mod b
  1973. {
  1974. int n = m.Length;
  1975. if (n == 1)
  1976. {
  1977. uint xVal = (uint)x[0];
  1978. x[0] = (int)MultiplyMontyNIsOne(xVal, xVal, (uint)m[0], mDash);
  1979. return;
  1980. }
  1981. ulong x0 = (uint)x[n - 1];
  1982. int aMax;
  1983. {
  1984. ulong carry = x0 * x0;
  1985. ulong t = (uint)carry * mDash;
  1986. ulong prod2 = t * (uint)m[n - 1];
  1987. carry += (uint)prod2;
  1988. Debug.Assert((uint)carry == 0);
  1989. carry = (carry >> 32) + (prod2 >> 32);
  1990. for (int j = n - 2; j >= 0; --j)
  1991. {
  1992. ulong prod1 = x0 * (uint)x[j];
  1993. prod2 = t * (uint)m[j];
  1994. carry += (prod2 & UIMASK) + ((uint)prod1 << 1);
  1995. a[j + 2] = (int)carry;
  1996. carry = (carry >> 32) + (prod1 >> 31) + (prod2 >> 32);
  1997. }
  1998. a[1] = (int)carry;
  1999. aMax = (int)(carry >> 32);
  2000. }
  2001. for (int i = n - 2; i >= 0; --i)
  2002. {
  2003. uint a0 = (uint)a[n];
  2004. ulong t = a0 * mDash;
  2005. ulong carry = t * (uint)m[n - 1] + a0;
  2006. Debug.Assert((uint)carry == 0);
  2007. carry >>= 32;
  2008. for (int j = n - 2; j > i; --j)
  2009. {
  2010. carry += t * (uint)m[j] + (uint)a[j + 1];
  2011. a[j + 2] = (int)carry;
  2012. carry >>= 32;
  2013. }
  2014. ulong xi = (uint)x[i];
  2015. {
  2016. ulong prod1 = xi * xi;
  2017. ulong prod2 = t * (uint)m[i];
  2018. carry += (prod1 & UIMASK) + (uint)prod2 + (uint)a[i + 1];
  2019. a[i + 2] = (int)carry;
  2020. carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32);
  2021. }
  2022. for (int j = i - 1; j >= 0; --j)
  2023. {
  2024. ulong prod1 = xi * (uint)x[j];
  2025. ulong prod2 = t * (uint)m[j];
  2026. carry += (prod2 & UIMASK) + ((uint)prod1 << 1) + (uint)a[j + 1];
  2027. a[j + 2] = (int)carry;
  2028. carry = (carry >> 32) + (prod1 >> 31) + (prod2 >> 32);
  2029. }
  2030. carry += (uint)aMax;
  2031. a[1] = (int)carry;
  2032. aMax = (int)(carry >> 32);
  2033. }
  2034. a[0] = aMax;
  2035. if (!smallMontyModulus && CompareTo(0, a, 0, m) >= 0)
  2036. {
  2037. Subtract(0, a, 0, m);
  2038. }
  2039. Array.Copy(a, 1, x, 0, n);
  2040. }
  2041. private static uint MultiplyMontyNIsOne(uint x, uint y, uint m, uint mDash)
  2042. {
  2043. ulong carry = (ulong)x * y;
  2044. uint t = (uint)carry * mDash;
  2045. ulong um = m;
  2046. ulong prod2 = um * t;
  2047. carry += (uint)prod2;
  2048. Debug.Assert((uint)carry == 0);
  2049. carry = (carry >> 32) + (prod2 >> 32);
  2050. if (carry > um)
  2051. {
  2052. carry -= um;
  2053. }
  2054. Debug.Assert(carry < um);
  2055. return (uint)carry;
  2056. }
  2057. public BigInteger Multiply(
  2058. BigInteger val)
  2059. {
  2060. if (val == this)
  2061. return Square();
  2062. if ((sign & val.sign) == 0)
  2063. return Zero;
  2064. if (val.QuickPow2Check()) // val is power of two
  2065. {
  2066. BigInteger result = this.ShiftLeft(val.Abs().BitLength - 1);
  2067. return val.sign > 0 ? result : result.Negate();
  2068. }
  2069. if (this.QuickPow2Check()) // this is power of two
  2070. {
  2071. BigInteger result = val.ShiftLeft(this.Abs().BitLength - 1);
  2072. return this.sign > 0 ? result : result.Negate();
  2073. }
  2074. int resLength = magnitude.Length + val.magnitude.Length;
  2075. int[] res = new int[resLength];
  2076. Multiply(res, this.magnitude, val.magnitude);
  2077. int resSign = sign ^ val.sign ^ 1;
  2078. return new BigInteger(resSign, res, true);
  2079. }
  2080. public BigInteger Square()
  2081. {
  2082. if (sign == 0)
  2083. return Zero;
  2084. if (this.QuickPow2Check())
  2085. return ShiftLeft(Abs().BitLength - 1);
  2086. int resLength = magnitude.Length << 1;
  2087. if ((uint)magnitude[0] >> 16 == 0)
  2088. --resLength;
  2089. int[] res = new int[resLength];
  2090. Square(res, magnitude);
  2091. return new BigInteger(1, res, false);
  2092. }
  2093. public BigInteger Negate()
  2094. {
  2095. if (sign == 0)
  2096. return this;
  2097. return new BigInteger(-sign, magnitude, false);
  2098. }
  2099. public BigInteger NextProbablePrime()
  2100. {
  2101. if (sign < 0)
  2102. throw new ArithmeticException("Cannot be called on value < 0");
  2103. if (CompareTo(Two) < 0)
  2104. return Two;
  2105. BigInteger n = Inc().SetBit(0);
  2106. while (!n.CheckProbablePrime(100, RandomSource, false))
  2107. {
  2108. n = n.Add(Two);
  2109. }
  2110. return n;
  2111. }
  2112. public BigInteger Not()
  2113. {
  2114. return Inc().Negate();
  2115. }
  2116. public BigInteger Pow(int exp)
  2117. {
  2118. if (exp <= 0)
  2119. {
  2120. if (exp < 0)
  2121. throw new ArithmeticException("Negative exponent");
  2122. return One;
  2123. }
  2124. if (sign == 0)
  2125. {
  2126. return this;
  2127. }
  2128. if (QuickPow2Check())
  2129. {
  2130. long powOf2 = (long)exp * (BitLength - 1);
  2131. if (powOf2 > Int32.MaxValue)
  2132. {
  2133. throw new ArithmeticException("Result too large");
  2134. }
  2135. return One.ShiftLeft((int)powOf2);
  2136. }
  2137. BigInteger y = One;
  2138. BigInteger z = this;
  2139. for (;;)
  2140. {
  2141. if ((exp & 0x1) == 1)
  2142. {
  2143. y = y.Multiply(z);
  2144. }
  2145. exp >>= 1;
  2146. if (exp == 0) break;
  2147. z = z.Multiply(z);
  2148. }
  2149. return y;
  2150. }
  2151. public static BigInteger ProbablePrime(
  2152. int bitLength,
  2153. Random random)
  2154. {
  2155. return new BigInteger(bitLength, 100, random);
  2156. }
  2157. private int Remainder(
  2158. int m)
  2159. {
  2160. Debug.Assert(m > 0);
  2161. long acc = 0;
  2162. for (int pos = 0; pos < magnitude.Length; ++pos)
  2163. {
  2164. long posVal = (uint) magnitude[pos];
  2165. acc = (acc << 32 | posVal) % m;
  2166. }
  2167. return (int) acc;
  2168. }
  2169. /**
  2170. * return x = x % y - done in place (y value preserved)
  2171. */
  2172. private static int[] Remainder(
  2173. int[] x,
  2174. int[] y)
  2175. {
  2176. int xStart = 0;
  2177. while (xStart < x.Length && x[xStart] == 0)
  2178. {
  2179. ++xStart;
  2180. }
  2181. int yStart = 0;
  2182. while (yStart < y.Length && y[yStart] == 0)
  2183. {
  2184. ++yStart;
  2185. }
  2186. Debug.Assert(yStart < y.Length);
  2187. int xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y);
  2188. if (xyCmp > 0)
  2189. {
  2190. int yBitLength = CalcBitLength(1, yStart, y);
  2191. int xBitLength = CalcBitLength(1, xStart, x);
  2192. int shift = xBitLength - yBitLength;
  2193. int[] c;
  2194. int cStart = 0;
  2195. int cBitLength = yBitLength;
  2196. if (shift > 0)
  2197. {
  2198. c = ShiftLeft(y, shift);
  2199. cBitLength += shift;
  2200. Debug.Assert(c[0] != 0);
  2201. }
  2202. else
  2203. {
  2204. int len = y.Length - yStart;
  2205. c = new int[len];
  2206. Array.Copy(y, yStart, c, 0, len);
  2207. }
  2208. for (;;)
  2209. {
  2210. if (cBitLength < xBitLength
  2211. || CompareNoLeadingZeroes(xStart, x, cStart, c) >= 0)
  2212. {
  2213. Subtract(xStart, x, cStart, c);
  2214. while (x[xStart] == 0)
  2215. {
  2216. if (++xStart == x.Length)
  2217. return x;
  2218. }
  2219. //xBitLength = CalcBitLength(xStart, x);
  2220. xBitLength = 32 * (x.Length - xStart - 1) + BitLen(x[xStart]);
  2221. if (xBitLength <= yBitLength)
  2222. {
  2223. if (xBitLength < yBitLength)
  2224. return x;
  2225. xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y);
  2226. if (xyCmp <= 0)
  2227. break;
  2228. }
  2229. }
  2230. shift = cBitLength - xBitLength;
  2231. // NB: The case where c[cStart] is 1-bit is harmless
  2232. if (shift == 1)
  2233. {
  2234. uint firstC = (uint) c[cStart] >> 1;
  2235. uint firstX = (uint) x[xStart];
  2236. if (firstC > firstX)
  2237. ++shift;
  2238. }
  2239. if (shift < 2)
  2240. {
  2241. ShiftRightOneInPlace(cStart, c);
  2242. --cBitLength;
  2243. }
  2244. else
  2245. {
  2246. ShiftRightInPlace(cStart, c, shift);
  2247. cBitLength -= shift;
  2248. }
  2249. //cStart = c.Length - ((cBitLength + 31) / 32);
  2250. while (c[cStart] == 0)
  2251. {
  2252. ++cStart;
  2253. }
  2254. }
  2255. }
  2256. if (xyCmp == 0)
  2257. {
  2258. Array.Clear(x, xStart, x.Length - xStart);
  2259. }
  2260. return x;
  2261. }
  2262. public BigInteger Remainder(
  2263. BigInteger n)
  2264. {
  2265. if (n.sign == 0)
  2266. throw new ArithmeticException("Division by zero error");
  2267. if (this.sign == 0)
  2268. return Zero;
  2269. // For small values, use fast remainder method
  2270. if (n.magnitude.Length == 1)
  2271. {
  2272. int val = n.magnitude[0];
  2273. if (val > 0)
  2274. {
  2275. if (val == 1)
  2276. return Zero;
  2277. // TODO Make this func work on uint, and handle val == 1?
  2278. int rem = Remainder(val);
  2279. return rem == 0
  2280. ? Zero
  2281. : new BigInteger(sign, new int[]{ rem }, false);
  2282. }
  2283. }
  2284. if (CompareNoLeadingZeroes(0, magnitude, 0, n.magnitude) < 0)
  2285. return this;
  2286. int[] result;
  2287. if (n.QuickPow2Check()) // n is power of two
  2288. {
  2289. // TODO Move before small values branch above?
  2290. result = LastNBits(n.Abs().BitLength - 1);
  2291. }
  2292. else
  2293. {
  2294. result = (int[]) this.magnitude.Clone();
  2295. result = Remainder(result, n.magnitude);
  2296. }
  2297. return new BigInteger(sign, result, true);
  2298. }
  2299. private int[] LastNBits(
  2300. int n)
  2301. {
  2302. if (n < 1)
  2303. return ZeroMagnitude;
  2304. int numWords = (n + BitsPerInt - 1) / BitsPerInt;
  2305. numWords = System.Math.Min(numWords, this.magnitude.Length);
  2306. int[] result = new int[numWords];
  2307. Array.Copy(this.magnitude, this.magnitude.Length - numWords, result, 0, numWords);
  2308. int excessBits = (numWords << 5) - n;
  2309. if (excessBits > 0)
  2310. {
  2311. result[0] &= (int)(UInt32.MaxValue >> excessBits);
  2312. }
  2313. return result;
  2314. }
  2315. private BigInteger DivideWords(int w)
  2316. {
  2317. Debug.Assert(w >= 0);
  2318. int n = magnitude.Length;
  2319. if (w >= n)
  2320. return Zero;
  2321. int[] mag = new int[n - w];
  2322. Array.Copy(magnitude, 0, mag, 0, n - w);
  2323. return new BigInteger(sign, mag, false);
  2324. }
  2325. private BigInteger RemainderWords(int w)
  2326. {
  2327. Debug.Assert(w >= 0);
  2328. int n = magnitude.Length;
  2329. if (w >= n)
  2330. return this;
  2331. int[] mag = new int[w];
  2332. Array.Copy(magnitude, n - w, mag, 0, w);
  2333. return new BigInteger(sign, mag, false);
  2334. }
  2335. /**
  2336. * do a left shift - this returns a new array.
  2337. */
  2338. private static int[] ShiftLeft(
  2339. int[] mag,
  2340. int n)
  2341. {
  2342. int nInts = (int)((uint)n >> 5);
  2343. int nBits = n & 0x1f;
  2344. int magLen = mag.Length;
  2345. int[] newMag;
  2346. if (nBits == 0)
  2347. {
  2348. newMag = new int[magLen + nInts];
  2349. mag.CopyTo(newMag, 0);
  2350. }
  2351. else
  2352. {
  2353. int i = 0;
  2354. int nBits2 = 32 - nBits;
  2355. int highBits = (int)((uint)mag[0] >> nBits2);
  2356. if (highBits != 0)
  2357. {
  2358. newMag = new int[magLen + nInts + 1];
  2359. newMag[i++] = highBits;
  2360. }
  2361. else
  2362. {
  2363. newMag = new int[magLen + nInts];
  2364. }
  2365. int m = mag[0];
  2366. for (int j = 0; j < magLen - 1; j++)
  2367. {
  2368. int next = mag[j + 1];
  2369. newMag[i++] = (m << nBits) | (int)((uint)next >> nBits2);
  2370. m = next;
  2371. }
  2372. newMag[i] = mag[magLen - 1] << nBits;
  2373. }
  2374. return newMag;
  2375. }
  2376. private static int ShiftLeftOneInPlace(int[] x, int carry)
  2377. {
  2378. Debug.Assert(carry == 0 || carry == 1);
  2379. int pos = x.Length;
  2380. while (--pos >= 0)
  2381. {
  2382. uint val = (uint)x[pos];
  2383. x[pos] = (int)(val << 1) | carry;
  2384. carry = (int)(val >> 31);
  2385. }
  2386. return carry;
  2387. }
  2388. public BigInteger ShiftLeft(
  2389. int n)
  2390. {
  2391. if (sign == 0 || magnitude.Length == 0)
  2392. return Zero;
  2393. if (n == 0)
  2394. return this;
  2395. if (n < 0)
  2396. return ShiftRight(-n);
  2397. BigInteger result = new BigInteger(sign, ShiftLeft(magnitude, n), true);
  2398. if (this.nBits != -1)
  2399. {
  2400. result.nBits = sign > 0
  2401. ? this.nBits
  2402. : this.nBits + n;
  2403. }
  2404. if (this.nBitLength != -1)
  2405. {
  2406. result.nBitLength = this.nBitLength + n;
  2407. }
  2408. return result;
  2409. }
  2410. /**
  2411. * do a right shift - this does it in place.
  2412. */
  2413. private static void ShiftRightInPlace(
  2414. int start,
  2415. int[] mag,
  2416. int n)
  2417. {
  2418. int nInts = (int)((uint)n >> 5) + start;
  2419. int nBits = n & 0x1f;
  2420. int magEnd = mag.Length - 1;
  2421. if (nInts != start)
  2422. {
  2423. int delta = (nInts - start);
  2424. for (int i = magEnd; i >= nInts; i--)
  2425. {
  2426. mag[i] = mag[i - delta];
  2427. }
  2428. for (int i = nInts - 1; i >= start; i--)
  2429. {
  2430. mag[i] = 0;
  2431. }
  2432. }
  2433. if (nBits != 0)
  2434. {
  2435. int nBits2 = 32 - nBits;
  2436. int m = mag[magEnd];
  2437. for (int i = magEnd; i > nInts; --i)
  2438. {
  2439. int next = mag[i - 1];
  2440. mag[i] = (int)((uint)m >> nBits) | (next << nBits2);
  2441. m = next;
  2442. }
  2443. mag[nInts] = (int)((uint)mag[nInts] >> nBits);
  2444. }
  2445. }
  2446. /**
  2447. * do a right shift by one - this does it in place.
  2448. */
  2449. private static void ShiftRightOneInPlace(
  2450. int start,
  2451. int[] mag)
  2452. {
  2453. int i = mag.Length;
  2454. int m = mag[i - 1];
  2455. while (--i > start)
  2456. {
  2457. int next = mag[i - 1];
  2458. mag[i] = ((int)((uint)m >> 1)) | (next << 31);
  2459. m = next;
  2460. }
  2461. mag[start] = (int)((uint)mag[start] >> 1);
  2462. }
  2463. public BigInteger ShiftRight(
  2464. int n)
  2465. {
  2466. if (n == 0)
  2467. return this;
  2468. if (n < 0)
  2469. return ShiftLeft(-n);
  2470. if (n >= BitLength)
  2471. return (this.sign < 0 ? One.Negate() : Zero);
  2472. // int[] res = (int[]) this.magnitude.Clone();
  2473. //
  2474. // ShiftRightInPlace(0, res, n);
  2475. //
  2476. // return new BigInteger(this.sign, res, true);
  2477. int resultLength = (BitLength - n + 31) >> 5;
  2478. int[] res = new int[resultLength];
  2479. int numInts = n >> 5;
  2480. int numBits = n & 31;
  2481. if (numBits == 0)
  2482. {
  2483. Array.Copy(this.magnitude, 0, res, 0, res.Length);
  2484. }
  2485. else
  2486. {
  2487. int numBits2 = 32 - numBits;
  2488. int magPos = this.magnitude.Length - 1 - numInts;
  2489. for (int i = resultLength - 1; i >= 0; --i)
  2490. {
  2491. res[i] = (int)((uint) this.magnitude[magPos--] >> numBits);
  2492. if (magPos >= 0)
  2493. {
  2494. res[i] |= this.magnitude[magPos] << numBits2;
  2495. }
  2496. }
  2497. }
  2498. Debug.Assert(res[0] != 0);
  2499. return new BigInteger(this.sign, res, false);
  2500. }
  2501. public int SignValue
  2502. {
  2503. get { return sign; }
  2504. }
  2505. /**
  2506. * returns x = x - y - we assume x is >= y
  2507. */
  2508. private static int[] Subtract(
  2509. int xStart,
  2510. int[] x,
  2511. int yStart,
  2512. int[] y)
  2513. {
  2514. Debug.Assert(yStart < y.Length);
  2515. Debug.Assert(x.Length - xStart >= y.Length - yStart);
  2516. int iT = x.Length;
  2517. int iV = y.Length;
  2518. long m;
  2519. int borrow = 0;
  2520. do
  2521. {
  2522. m = (x[--iT] & IMASK) - (y[--iV] & IMASK) + borrow;
  2523. x[iT] = (int) m;
  2524. // borrow = (m < 0) ? -1 : 0;
  2525. borrow = (int)(m >> 63);
  2526. }
  2527. while (iV > yStart);
  2528. if (borrow != 0)
  2529. {
  2530. while (--x[--iT] == -1)
  2531. {
  2532. }
  2533. }
  2534. return x;
  2535. }
  2536. public BigInteger Subtract(
  2537. BigInteger n)
  2538. {
  2539. if (n.sign == 0)
  2540. return this;
  2541. if (this.sign == 0)
  2542. return n.Negate();
  2543. if (this.sign != n.sign)
  2544. return Add(n.Negate());
  2545. int compare = CompareNoLeadingZeroes(0, magnitude, 0, n.magnitude);
  2546. if (compare == 0)
  2547. return Zero;
  2548. BigInteger bigun, lilun;
  2549. if (compare < 0)
  2550. {
  2551. bigun = n;
  2552. lilun = this;
  2553. }
  2554. else
  2555. {
  2556. bigun = this;
  2557. lilun = n;
  2558. }
  2559. return new BigInteger(this.sign * compare, doSubBigLil(bigun.magnitude, lilun.magnitude), true);
  2560. }
  2561. private static int[] doSubBigLil(
  2562. int[] bigMag,
  2563. int[] lilMag)
  2564. {
  2565. int[] res = (int[]) bigMag.Clone();
  2566. return Subtract(0, res, 0, lilMag);
  2567. }
  2568. public byte[] ToByteArray()
  2569. {
  2570. return ToByteArray(false);
  2571. }
  2572. public byte[] ToByteArrayUnsigned()
  2573. {
  2574. return ToByteArray(true);
  2575. }
  2576. private byte[] ToByteArray(
  2577. bool unsigned)
  2578. {
  2579. if (sign == 0)
  2580. return unsigned ? ZeroEncoding : new byte[1];
  2581. int nBits = (unsigned && sign > 0)
  2582. ? BitLength
  2583. : BitLength + 1;
  2584. int nBytes = GetByteLength(nBits);
  2585. byte[] bytes = new byte[nBytes];
  2586. int magIndex = magnitude.Length;
  2587. int bytesIndex = bytes.Length;
  2588. if (sign > 0)
  2589. {
  2590. while (magIndex > 1)
  2591. {
  2592. uint mag = (uint) magnitude[--magIndex];
  2593. bytes[--bytesIndex] = (byte) mag;
  2594. bytes[--bytesIndex] = (byte)(mag >> 8);
  2595. bytes[--bytesIndex] = (byte)(mag >> 16);
  2596. bytes[--bytesIndex] = (byte)(mag >> 24);
  2597. }
  2598. uint lastMag = (uint) magnitude[0];
  2599. while (lastMag > byte.MaxValue)
  2600. {
  2601. bytes[--bytesIndex] = (byte) lastMag;
  2602. lastMag >>= 8;
  2603. }
  2604. bytes[--bytesIndex] = (byte) lastMag;
  2605. }
  2606. else // sign < 0
  2607. {
  2608. bool carry = true;
  2609. while (magIndex > 1)
  2610. {
  2611. uint mag = ~((uint) magnitude[--magIndex]);
  2612. if (carry)
  2613. {
  2614. carry = (++mag == uint.MinValue);
  2615. }
  2616. bytes[--bytesIndex] = (byte) mag;
  2617. bytes[--bytesIndex] = (byte)(mag >> 8);
  2618. bytes[--bytesIndex] = (byte)(mag >> 16);
  2619. bytes[--bytesIndex] = (byte)(mag >> 24);
  2620. }
  2621. uint lastMag = (uint) magnitude[0];
  2622. if (carry)
  2623. {
  2624. // Never wraps because magnitude[0] != 0
  2625. --lastMag;
  2626. }
  2627. while (lastMag > byte.MaxValue)
  2628. {
  2629. bytes[--bytesIndex] = (byte) ~lastMag;
  2630. lastMag >>= 8;
  2631. }
  2632. bytes[--bytesIndex] = (byte) ~lastMag;
  2633. if (bytesIndex > 0)
  2634. {
  2635. bytes[--bytesIndex] = byte.MaxValue;
  2636. }
  2637. }
  2638. return bytes;
  2639. }
  2640. public override string ToString()
  2641. {
  2642. return ToString(10);
  2643. }
  2644. public string ToString(int radix)
  2645. {
  2646. // TODO Make this method work for other radices (ideally 2 <= radix <= 36 as in Java)
  2647. switch (radix)
  2648. {
  2649. case 2:
  2650. case 8:
  2651. case 10:
  2652. case 16:
  2653. break;
  2654. default:
  2655. throw new FormatException("Only bases 2, 8, 10, 16 are allowed");
  2656. }
  2657. // NB: Can only happen to internally managed instances
  2658. if (magnitude == null)
  2659. return "null";
  2660. if (sign == 0)
  2661. return "0";
  2662. // NOTE: This *should* be unnecessary, since the magnitude *should* never have leading zero digits
  2663. int firstNonZero = 0;
  2664. while (firstNonZero < magnitude.Length)
  2665. {
  2666. if (magnitude[firstNonZero] != 0)
  2667. {
  2668. break;
  2669. }
  2670. ++firstNonZero;
  2671. }
  2672. if (firstNonZero == magnitude.Length)
  2673. {
  2674. return "0";
  2675. }
  2676. StringBuilder sb = new StringBuilder();
  2677. if (sign == -1)
  2678. {
  2679. sb.Append('-');
  2680. }
  2681. switch (radix)
  2682. {
  2683. case 2:
  2684. {
  2685. int pos = firstNonZero;
  2686. sb.Append(Convert.ToString(magnitude[pos], 2));
  2687. while (++pos < magnitude.Length)
  2688. {
  2689. AppendZeroExtendedString(sb, Convert.ToString(magnitude[pos], 2), 32);
  2690. }
  2691. break;
  2692. }
  2693. case 8:
  2694. {
  2695. int mask = (1 << 30) - 1;
  2696. BigInteger u = this.Abs();
  2697. int bits = u.BitLength;
  2698. IList S = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  2699. while (bits > 30)
  2700. {
  2701. S.Add(Convert.ToString(u.IntValue & mask, 8));
  2702. u = u.ShiftRight(30);
  2703. bits -= 30;
  2704. }
  2705. sb.Append(Convert.ToString(u.IntValue, 8));
  2706. for (int i = S.Count - 1; i >= 0; --i)
  2707. {
  2708. AppendZeroExtendedString(sb, (string)S[i], 10);
  2709. }
  2710. break;
  2711. }
  2712. case 16:
  2713. {
  2714. int pos = firstNonZero;
  2715. sb.Append(Convert.ToString(magnitude[pos], 16));
  2716. while (++pos < magnitude.Length)
  2717. {
  2718. AppendZeroExtendedString(sb, Convert.ToString(magnitude[pos], 16), 8);
  2719. }
  2720. break;
  2721. }
  2722. // TODO This could work for other radices if there is an alternative to Convert.ToString method
  2723. //default:
  2724. case 10:
  2725. {
  2726. BigInteger q = this.Abs();
  2727. if (q.BitLength < 64)
  2728. {
  2729. sb.Append(Convert.ToString(q.LongValue, radix));
  2730. break;
  2731. }
  2732. // TODO Could cache the moduli for each radix (soft reference?)
  2733. IList moduli = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  2734. BigInteger R = BigInteger.ValueOf(radix);
  2735. while (R.CompareTo(q) <= 0)
  2736. {
  2737. moduli.Add(R);
  2738. R = R.Square();
  2739. }
  2740. int scale = moduli.Count;
  2741. sb.EnsureCapacity(sb.Length + (1 << scale));
  2742. ToString(sb, radix, moduli, scale, q);
  2743. break;
  2744. }
  2745. }
  2746. return sb.ToString();
  2747. }
  2748. private static void ToString(StringBuilder sb, int radix, IList moduli, int scale, BigInteger pos)
  2749. {
  2750. if (pos.BitLength < 64)
  2751. {
  2752. string s = Convert.ToString(pos.LongValue, radix);
  2753. if (sb.Length > 1 || (sb.Length == 1 && sb[0] != '-'))
  2754. {
  2755. AppendZeroExtendedString(sb, s, 1 << scale);
  2756. }
  2757. else if (pos.SignValue != 0)
  2758. {
  2759. sb.Append(s);
  2760. }
  2761. return;
  2762. }
  2763. BigInteger[] qr = pos.DivideAndRemainder((BigInteger)moduli[--scale]);
  2764. ToString(sb, radix, moduli, scale, qr[0]);
  2765. ToString(sb, radix, moduli, scale, qr[1]);
  2766. }
  2767. private static void AppendZeroExtendedString(StringBuilder sb, string s, int minLength)
  2768. {
  2769. for (int len = s.Length; len < minLength; ++len)
  2770. {
  2771. sb.Append('0');
  2772. }
  2773. sb.Append(s);
  2774. }
  2775. private static BigInteger CreateUValueOf(
  2776. ulong value)
  2777. {
  2778. int msw = (int)(value >> 32);
  2779. int lsw = (int)value;
  2780. if (msw != 0)
  2781. return new BigInteger(1, new int[] { msw, lsw }, false);
  2782. if (lsw != 0)
  2783. {
  2784. BigInteger n = new BigInteger(1, new int[] { lsw }, false);
  2785. // Check for a power of two
  2786. if ((lsw & -lsw) == lsw)
  2787. {
  2788. n.nBits = 1;
  2789. }
  2790. return n;
  2791. }
  2792. return Zero;
  2793. }
  2794. private static BigInteger CreateValueOf(
  2795. long value)
  2796. {
  2797. if (value < 0)
  2798. {
  2799. if (value == long.MinValue)
  2800. return CreateValueOf(~value).Not();
  2801. return CreateValueOf(-value).Negate();
  2802. }
  2803. return CreateUValueOf((ulong)value);
  2804. }
  2805. public static BigInteger ValueOf(
  2806. long value)
  2807. {
  2808. if (value >= 0 && value < SMALL_CONSTANTS.Length)
  2809. {
  2810. return SMALL_CONSTANTS[value];
  2811. }
  2812. return CreateValueOf(value);
  2813. }
  2814. public int GetLowestSetBit()
  2815. {
  2816. if (this.sign == 0)
  2817. return -1;
  2818. return GetLowestSetBitMaskFirst(-1);
  2819. }
  2820. private int GetLowestSetBitMaskFirst(int firstWordMask)
  2821. {
  2822. int w = magnitude.Length, offset = 0;
  2823. uint word = (uint)(magnitude[--w] & firstWordMask);
  2824. Debug.Assert(magnitude[0] != 0);
  2825. while (word == 0)
  2826. {
  2827. word = (uint)magnitude[--w];
  2828. offset += 32;
  2829. }
  2830. while ((word & 0xFF) == 0)
  2831. {
  2832. word >>= 8;
  2833. offset += 8;
  2834. }
  2835. while ((word & 1) == 0)
  2836. {
  2837. word >>= 1;
  2838. ++offset;
  2839. }
  2840. return offset;
  2841. }
  2842. public bool TestBit(
  2843. int n)
  2844. {
  2845. if (n < 0)
  2846. throw new ArithmeticException("Bit position must not be negative");
  2847. if (sign < 0)
  2848. return !Not().TestBit(n);
  2849. int wordNum = n / 32;
  2850. if (wordNum >= magnitude.Length)
  2851. return false;
  2852. int word = magnitude[magnitude.Length - 1 - wordNum];
  2853. return ((word >> (n % 32)) & 1) > 0;
  2854. }
  2855. public BigInteger Or(
  2856. BigInteger value)
  2857. {
  2858. if (this.sign == 0)
  2859. return value;
  2860. if (value.sign == 0)
  2861. return this;
  2862. int[] aMag = this.sign > 0
  2863. ? this.magnitude
  2864. : Add(One).magnitude;
  2865. int[] bMag = value.sign > 0
  2866. ? value.magnitude
  2867. : value.Add(One).magnitude;
  2868. bool resultNeg = sign < 0 || value.sign < 0;
  2869. int resultLength = System.Math.Max(aMag.Length, bMag.Length);
  2870. int[] resultMag = new int[resultLength];
  2871. int aStart = resultMag.Length - aMag.Length;
  2872. int bStart = resultMag.Length - bMag.Length;
  2873. for (int i = 0; i < resultMag.Length; ++i)
  2874. {
  2875. int aWord = i >= aStart ? aMag[i - aStart] : 0;
  2876. int bWord = i >= bStart ? bMag[i - bStart] : 0;
  2877. if (this.sign < 0)
  2878. {
  2879. aWord = ~aWord;
  2880. }
  2881. if (value.sign < 0)
  2882. {
  2883. bWord = ~bWord;
  2884. }
  2885. resultMag[i] = aWord | bWord;
  2886. if (resultNeg)
  2887. {
  2888. resultMag[i] = ~resultMag[i];
  2889. }
  2890. }
  2891. BigInteger result = new BigInteger(1, resultMag, true);
  2892. // TODO Optimise this case
  2893. if (resultNeg)
  2894. {
  2895. result = result.Not();
  2896. }
  2897. return result;
  2898. }
  2899. public BigInteger Xor(
  2900. BigInteger value)
  2901. {
  2902. if (this.sign == 0)
  2903. return value;
  2904. if (value.sign == 0)
  2905. return this;
  2906. int[] aMag = this.sign > 0
  2907. ? this.magnitude
  2908. : Add(One).magnitude;
  2909. int[] bMag = value.sign > 0
  2910. ? value.magnitude
  2911. : value.Add(One).magnitude;
  2912. // TODO Can just replace with sign != value.sign?
  2913. bool resultNeg = (sign < 0 && value.sign >= 0) || (sign >= 0 && value.sign < 0);
  2914. int resultLength = System.Math.Max(aMag.Length, bMag.Length);
  2915. int[] resultMag = new int[resultLength];
  2916. int aStart = resultMag.Length - aMag.Length;
  2917. int bStart = resultMag.Length - bMag.Length;
  2918. for (int i = 0; i < resultMag.Length; ++i)
  2919. {
  2920. int aWord = i >= aStart ? aMag[i - aStart] : 0;
  2921. int bWord = i >= bStart ? bMag[i - bStart] : 0;
  2922. if (this.sign < 0)
  2923. {
  2924. aWord = ~aWord;
  2925. }
  2926. if (value.sign < 0)
  2927. {
  2928. bWord = ~bWord;
  2929. }
  2930. resultMag[i] = aWord ^ bWord;
  2931. if (resultNeg)
  2932. {
  2933. resultMag[i] = ~resultMag[i];
  2934. }
  2935. }
  2936. BigInteger result = new BigInteger(1, resultMag, true);
  2937. // TODO Optimise this case
  2938. if (resultNeg)
  2939. {
  2940. result = result.Not();
  2941. }
  2942. return result;
  2943. }
  2944. public BigInteger SetBit(
  2945. int n)
  2946. {
  2947. if (n < 0)
  2948. throw new ArithmeticException("Bit address less than zero");
  2949. if (TestBit(n))
  2950. return this;
  2951. // TODO Handle negative values and zero
  2952. if (sign > 0 && n < (BitLength - 1))
  2953. return FlipExistingBit(n);
  2954. return Or(One.ShiftLeft(n));
  2955. }
  2956. public BigInteger ClearBit(
  2957. int n)
  2958. {
  2959. if (n < 0)
  2960. throw new ArithmeticException("Bit address less than zero");
  2961. if (!TestBit(n))
  2962. return this;
  2963. // TODO Handle negative values
  2964. if (sign > 0 && n < (BitLength - 1))
  2965. return FlipExistingBit(n);
  2966. return AndNot(One.ShiftLeft(n));
  2967. }
  2968. public BigInteger FlipBit(
  2969. int n)
  2970. {
  2971. if (n < 0)
  2972. throw new ArithmeticException("Bit address less than zero");
  2973. // TODO Handle negative values and zero
  2974. if (sign > 0 && n < (BitLength - 1))
  2975. return FlipExistingBit(n);
  2976. return Xor(One.ShiftLeft(n));
  2977. }
  2978. private BigInteger FlipExistingBit(
  2979. int n)
  2980. {
  2981. Debug.Assert(sign > 0);
  2982. Debug.Assert(n >= 0);
  2983. Debug.Assert(n < BitLength - 1);
  2984. int[] mag = (int[]) this.magnitude.Clone();
  2985. mag[mag.Length - 1 - (n >> 5)] ^= (1 << (n & 31)); // Flip bit
  2986. //mag[mag.Length - 1 - (n / 32)] ^= (1 << (n % 32));
  2987. return new BigInteger(this.sign, mag, false);
  2988. }
  2989. }
  2990. }
  2991. #pragma warning restore
  2992. #endif