BigInteger.php 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888
  1. <?php
  2. /**
  3. * Pure-PHP arbitrary precision integer arithmetic library.
  4. *
  5. * Supports base-2, base-10, base-16, and base-256 numbers. Uses the GMP or BCMath extensions, if available,
  6. * and an internal implementation, otherwise.
  7. *
  8. * PHP version 5
  9. *
  10. * {@internal (all DocBlock comments regarding implementation - such as the one that follows - refer to the
  11. * {@link self::MODE_INTERNAL self::MODE_INTERNAL} mode)
  12. *
  13. * BigInteger uses base-2**26 to perform operations such as multiplication and division and
  14. * base-2**52 (ie. two base 2**26 digits) to perform addition and subtraction. Because the largest possible
  15. * value when multiplying two base-2**26 numbers together is a base-2**52 number, double precision floating
  16. * point numbers - numbers that should be supported on most hardware and whose significand is 53 bits - are
  17. * used. As a consequence, bitwise operators such as >> and << cannot be used, nor can the modulo operator %,
  18. * which only supports integers. Although this fact will slow this library down, the fact that such a high
  19. * base is being used should more than compensate.
  20. *
  21. * Numbers are stored in {@link http://en.wikipedia.org/wiki/Endianness little endian} format. ie.
  22. * (new \phpseclib\Math\BigInteger(pow(2, 26)))->value = array(0, 1)
  23. *
  24. * Useful resources are as follows:
  25. *
  26. * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)}
  27. * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)}
  28. * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip
  29. *
  30. * Here's an example of how to use this library:
  31. * <code>
  32. * <?php
  33. * $a = new \phpseclib\Math\BigInteger(2);
  34. * $b = new \phpseclib\Math\BigInteger(3);
  35. *
  36. * $c = $a->add($b);
  37. *
  38. * echo $c->toString(); // outputs 5
  39. * ?>
  40. * </code>
  41. *
  42. * @category Math
  43. * @package BigInteger
  44. * @author Jim Wigginton <terrafrost@php.net>
  45. * @copyright 2006 Jim Wigginton
  46. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  47. * @link http://pear.php.net/package/Math_BigInteger
  48. */
  49. namespace phpseclib\Math;
  50. use ParagonIE\ConstantTime\Base64;
  51. use ParagonIE\ConstantTime\Hex;
  52. use phpseclib\Crypt\Random;
  53. use phpseclib\File\ASN1;
  54. /**
  55. * Pure-PHP arbitrary precision integer arithmetic library. Supports base-2, base-10, base-16, and base-256
  56. * numbers.
  57. *
  58. * @package BigInteger
  59. * @author Jim Wigginton <terrafrost@php.net>
  60. * @access public
  61. */
  62. class BigInteger
  63. {
  64. /**#@+
  65. * Reduction constants
  66. *
  67. * @access private
  68. * @see BigInteger::_reduce()
  69. */
  70. /**
  71. * @see BigInteger::_montgomery()
  72. * @see BigInteger::_prepMontgomery()
  73. */
  74. const MONTGOMERY = 0;
  75. /**
  76. * @see BigInteger::_barrett()
  77. */
  78. const BARRETT = 1;
  79. /**
  80. * @see BigInteger::_mod2()
  81. */
  82. const POWEROF2 = 2;
  83. /**
  84. * @see BigInteger::_remainder()
  85. */
  86. const CLASSIC = 3;
  87. /**
  88. * @see BigInteger::__clone()
  89. */
  90. const NONE = 4;
  91. /**#@-*/
  92. /**#@+
  93. * Array constants
  94. *
  95. * Rather than create a thousands and thousands of new BigInteger objects in repeated function calls to add() and
  96. * multiply() or whatever, we'll just work directly on arrays, taking them in as parameters and returning them.
  97. *
  98. * @access private
  99. */
  100. /**
  101. * $result[self::VALUE] contains the value.
  102. */
  103. const VALUE = 0;
  104. /**
  105. * $result[self::SIGN] contains the sign.
  106. */
  107. const SIGN = 1;
  108. /**#@-*/
  109. /**#@+
  110. * @access private
  111. * @see BigInteger::_montgomery()
  112. * @see BigInteger::_barrett()
  113. */
  114. /**
  115. * Cache constants
  116. *
  117. * $cache[self::VARIABLE] tells us whether or not the cached data is still valid.
  118. */
  119. const VARIABLE = 0;
  120. /**
  121. * $cache[self::DATA] contains the cached data.
  122. */
  123. const DATA = 1;
  124. /**#@-*/
  125. /**#@+
  126. * Mode constants.
  127. *
  128. * @access private
  129. * @see BigInteger::__construct()
  130. */
  131. /**
  132. * To use the pure-PHP implementation
  133. */
  134. const MODE_INTERNAL = 1;
  135. /**
  136. * To use the BCMath library
  137. *
  138. * (if enabled; otherwise, the internal implementation will be used)
  139. */
  140. const MODE_BCMATH = 2;
  141. /**
  142. * To use the GMP library
  143. *
  144. * (if present; otherwise, either the BCMath or the internal implementation will be used)
  145. */
  146. const MODE_GMP = 3;
  147. /**#@-*/
  148. /**
  149. * Karatsuba Cutoff
  150. *
  151. * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication?
  152. *
  153. * @access private
  154. */
  155. const KARATSUBA_CUTOFF = 25;
  156. /**#@+
  157. * Static properties used by the pure-PHP implementation.
  158. *
  159. * @see __construct()
  160. */
  161. private static $base;
  162. private static $baseFull;
  163. private static $maxDigit;
  164. private static $msb;
  165. /**
  166. * $max10 in greatest $max10Len satisfying
  167. * $max10 = 10**$max10Len <= 2**$base.
  168. */
  169. private static $max10;
  170. /**
  171. * $max10Len in greatest $max10Len satisfying
  172. * $max10 = 10**$max10Len <= 2**$base.
  173. */
  174. private static $max10Len;
  175. private static $maxDigit2;
  176. /**#@-*/
  177. /**
  178. * Holds the BigInteger's value.
  179. *
  180. * @var array
  181. * @access private
  182. */
  183. private $value;
  184. /**
  185. * Holds the BigInteger's magnitude.
  186. *
  187. * @var bool
  188. * @access private
  189. */
  190. private $is_negative = false;
  191. /**
  192. * Precision
  193. *
  194. * @see self::setPrecision()
  195. * @access private
  196. */
  197. private $precision = -1;
  198. /**
  199. * Precision Bitmask
  200. *
  201. * @see self::setPrecision()
  202. * @access private
  203. */
  204. private $bitmask = false;
  205. /**
  206. * Mode independent value used for serialization.
  207. *
  208. * If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for
  209. * a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value,
  210. * however, $this->hex is only calculated when $this->__sleep() is called.
  211. *
  212. * @see self::__sleep()
  213. * @see self::__wakeup()
  214. * @var string
  215. * @access private
  216. */
  217. private $hex;
  218. /**
  219. * Converts base-2, base-10, base-16, and binary strings (base-256) to BigIntegers.
  220. *
  221. * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using
  222. * two's compliment. The sole exception to this is -10, which is treated the same as 10 is.
  223. *
  224. * Here's an example:
  225. * <code>
  226. * <?php
  227. * $a = new \phpseclib\Math\BigInteger('0x32', 16); // 50 in base-16
  228. *
  229. * echo $a->toString(); // outputs 50
  230. * ?>
  231. * </code>
  232. *
  233. * @param $x base-10 number or base-$base number if $base set.
  234. * @param int $base
  235. * @return \phpseclib\Math\BigInteger
  236. * @access public
  237. */
  238. public function __construct($x = 0, $base = 10)
  239. {
  240. if (!defined('MATH_BIGINTEGER_MODE')) {
  241. switch (true) {
  242. case extension_loaded('gmp'):
  243. define('MATH_BIGINTEGER_MODE', self::MODE_GMP);
  244. break;
  245. case extension_loaded('bcmath'):
  246. define('MATH_BIGINTEGER_MODE', self::MODE_BCMATH);
  247. break;
  248. default:
  249. define('MATH_BIGINTEGER_MODE', self::MODE_INTERNAL);
  250. }
  251. }
  252. if (extension_loaded('openssl') && !defined('MATH_BIGINTEGER_OPENSSL_DISABLE') && !defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) {
  253. define('MATH_BIGINTEGER_OPENSSL_ENABLED', true);
  254. }
  255. if (!defined('PHP_INT_SIZE')) {
  256. define('PHP_INT_SIZE', 4);
  257. }
  258. if (empty(self::$base) && MATH_BIGINTEGER_MODE == self::MODE_INTERNAL) {
  259. switch (PHP_INT_SIZE) {
  260. case 8: // use 64-bit integers if int size is 8 bytes
  261. self::$base = 31;
  262. self::$baseFull = 0x80000000;
  263. self::$maxDigit = 0x7FFFFFFF;
  264. self::$msb = 0x40000000;
  265. self::$max10 = 1000000000;
  266. self::$max10Len = 9;
  267. self::$maxDigit2 = pow(2, 62);
  268. break;
  269. //case 4: // use 64-bit floats if int size is 4 bytes
  270. default:
  271. self::$base = 26;
  272. self::$baseFull = 0x4000000;
  273. self::$maxDigit = 0x3FFFFFF;
  274. self::$msb = 0x2000000;
  275. self::$max10 = 10000000;
  276. self::$max10Len = 7;
  277. self::$maxDigit2 = pow(2, 52); // pow() prevents truncation
  278. }
  279. }
  280. switch (MATH_BIGINTEGER_MODE) {
  281. case self::MODE_GMP:
  282. switch (true) {
  283. case is_resource($x) && get_resource_type($x) == 'GMP integer':
  284. // PHP 5.6 switched GMP from using resources to objects
  285. case $x instanceof \GMP:
  286. $this->value = $x;
  287. return;
  288. }
  289. $this->value = gmp_init(0);
  290. break;
  291. case self::MODE_BCMATH:
  292. $this->value = '0';
  293. break;
  294. default:
  295. $this->value = array();
  296. }
  297. // '0' counts as empty() but when the base is 256 '0' is equal to ord('0') or 48
  298. // '0' is the only value like this per http://php.net/empty
  299. if (empty($x) && (abs($base) != 256 || $x !== '0')) {
  300. return;
  301. }
  302. switch ($base) {
  303. case -256:
  304. if (ord($x[0]) & 0x80) {
  305. $x = ~$x;
  306. $this->is_negative = true;
  307. }
  308. case 256:
  309. switch (MATH_BIGINTEGER_MODE) {
  310. case self::MODE_GMP:
  311. $sign = $this->is_negative ? '-' : '';
  312. $this->value = gmp_init($sign . '0x' . Hex::encode($x));
  313. break;
  314. case self::MODE_BCMATH:
  315. // round $len to the nearest 4 (thanks, DavidMJ!)
  316. $len = (strlen($x) + 3) & 0xFFFFFFFC;
  317. $x = str_pad($x, $len, chr(0), STR_PAD_LEFT);
  318. for ($i = 0; $i < $len; $i+= 4) {
  319. $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32
  320. $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0);
  321. }
  322. if ($this->is_negative) {
  323. $this->value = '-' . $this->value;
  324. }
  325. break;
  326. // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb)
  327. default:
  328. while (strlen($x)) {
  329. $this->value[] = $this->_bytes2int($this->_base256_rshift($x, self::$base));
  330. }
  331. }
  332. if ($this->is_negative) {
  333. if (MATH_BIGINTEGER_MODE != self::MODE_INTERNAL) {
  334. $this->is_negative = false;
  335. }
  336. $temp = $this->add(new static('-1'));
  337. $this->value = $temp->value;
  338. }
  339. break;
  340. case 16:
  341. case -16:
  342. if ($base > 0 && $x[0] == '-') {
  343. $this->is_negative = true;
  344. $x = substr($x, 1);
  345. }
  346. $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x);
  347. $is_negative = false;
  348. if ($base < 0 && hexdec($x[0]) >= 8) {
  349. $this->is_negative = $is_negative = true;
  350. $x = Hex::encode(~Hex::decode($x));
  351. }
  352. switch (MATH_BIGINTEGER_MODE) {
  353. case self::MODE_GMP:
  354. $temp = $this->is_negative ? '-0x' . $x : '0x' . $x;
  355. $this->value = gmp_init($temp);
  356. $this->is_negative = false;
  357. break;
  358. case self::MODE_BCMATH:
  359. $x = (strlen($x) & 1) ? '0' . $x : $x;
  360. $temp = new static(Hex::decode($x), 256);
  361. $this->value = $this->is_negative ? '-' . $temp->value : $temp->value;
  362. $this->is_negative = false;
  363. break;
  364. default:
  365. $x = (strlen($x) & 1) ? '0' . $x : $x;
  366. $temp = new static(Hex::decode($x), 256);
  367. $this->value = $temp->value;
  368. }
  369. if ($is_negative) {
  370. $temp = $this->add(new static('-1'));
  371. $this->value = $temp->value;
  372. }
  373. break;
  374. case 10:
  375. case -10:
  376. // (?<!^)(?:-).*: find any -'s that aren't at the beginning and then any characters that follow that
  377. // (?<=^|-)0*: find any 0's that are preceded by the start of the string or by a - (ie. octals)
  378. // [^-0-9].*: find any non-numeric characters and then any characters that follow that
  379. $x = preg_replace('#(?<!^)(?:-).*|(?<=^|-)0*|[^-0-9].*#', '', $x);
  380. switch (MATH_BIGINTEGER_MODE) {
  381. case self::MODE_GMP:
  382. $this->value = gmp_init($x);
  383. break;
  384. case self::MODE_BCMATH:
  385. // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different
  386. // results then doing it on '-1' does (modInverse does $x[0])
  387. $this->value = $x === '-' ? '0' : (string) $x;
  388. break;
  389. default:
  390. $temp = new static();
  391. $multiplier = new static();
  392. $multiplier->value = array(self::$max10);
  393. if ($x[0] == '-') {
  394. $this->is_negative = true;
  395. $x = substr($x, 1);
  396. }
  397. $x = str_pad($x, strlen($x) + ((self::$max10Len - 1) * strlen($x)) % self::$max10Len, 0, STR_PAD_LEFT);
  398. while (strlen($x)) {
  399. $temp = $temp->multiply($multiplier);
  400. $temp = $temp->add(new static($this->_int2bytes(substr($x, 0, self::$max10Len)), 256));
  401. $x = substr($x, self::$max10Len);
  402. }
  403. $this->value = $temp->value;
  404. }
  405. break;
  406. case 2: // base-2 support originally implemented by Lluis Pamies - thanks!
  407. case -2:
  408. if ($base > 0 && $x[0] == '-') {
  409. $this->is_negative = true;
  410. $x = substr($x, 1);
  411. }
  412. $x = preg_replace('#^([01]*).*#', '$1', $x);
  413. $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT);
  414. $str = '0x';
  415. while (strlen($x)) {
  416. $part = substr($x, 0, 4);
  417. $str.= dechex(bindec($part));
  418. $x = substr($x, 4);
  419. }
  420. if ($this->is_negative) {
  421. $str = '-' . $str;
  422. }
  423. $temp = new static($str, 8 * $base); // ie. either -16 or +16
  424. $this->value = $temp->value;
  425. $this->is_negative = $temp->is_negative;
  426. break;
  427. default:
  428. // base not supported, so we'll let $this == 0
  429. }
  430. }
  431. /**
  432. * Converts a BigInteger to a byte string (eg. base-256).
  433. *
  434. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  435. * saved as two's compliment.
  436. *
  437. * Here's an example:
  438. * <code>
  439. * <?php
  440. * $a = new \phpseclib\Math\BigInteger('65');
  441. *
  442. * echo $a->toBytes(); // outputs chr(65)
  443. * ?>
  444. * </code>
  445. *
  446. * @param bool $twos_compliment
  447. * @return string
  448. * @access public
  449. * @internal Converts a base-2**26 number to base-2**8
  450. */
  451. public function toBytes($twos_compliment = false)
  452. {
  453. if ($twos_compliment) {
  454. $comparison = $this->compare(new static());
  455. if ($comparison == 0) {
  456. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  457. }
  458. $temp = $comparison < 0 ? $this->add(new static(1)) : $this;
  459. $bytes = $temp->toBytes();
  460. if (empty($bytes)) { // eg. if the number we're trying to convert is -1
  461. $bytes = chr(0);
  462. }
  463. if (ord($bytes[0]) & 0x80) {
  464. $bytes = chr(0) . $bytes;
  465. }
  466. return $comparison < 0 ? ~$bytes : $bytes;
  467. }
  468. switch (MATH_BIGINTEGER_MODE) {
  469. case self::MODE_GMP:
  470. if (gmp_cmp($this->value, gmp_init(0)) == 0) {
  471. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  472. }
  473. $temp = gmp_strval(gmp_abs($this->value), 16);
  474. $temp = (strlen($temp) & 1) ? '0' . $temp : $temp;
  475. $temp = Hex::decode($temp);
  476. return $this->precision > 0 ?
  477. substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  478. ltrim($temp, chr(0));
  479. case self::MODE_BCMATH:
  480. if ($this->value === '0') {
  481. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  482. }
  483. $value = '';
  484. $current = $this->value;
  485. if ($current[0] == '-') {
  486. $current = substr($current, 1);
  487. }
  488. while (bccomp($current, '0', 0) > 0) {
  489. $temp = bcmod($current, '16777216');
  490. $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value;
  491. $current = bcdiv($current, '16777216', 0);
  492. }
  493. return $this->precision > 0 ?
  494. substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  495. ltrim($value, chr(0));
  496. }
  497. if (!count($this->value)) {
  498. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  499. }
  500. $result = self::_int2bytes($this->value[count($this->value) - 1]);
  501. for ($i = count($this->value) - 2; $i >= 0; --$i) {
  502. self::_base256_lshift($result, self::$base);
  503. $result = $result | str_pad(self::_int2bytes($this->value[$i]), strlen($result), chr(0), STR_PAD_LEFT);
  504. }
  505. return $this->precision > 0 ?
  506. str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) :
  507. $result;
  508. }
  509. /**
  510. * Converts a BigInteger to a hex string (eg. base-16)).
  511. *
  512. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  513. * saved as two's compliment.
  514. *
  515. * Here's an example:
  516. * <code>
  517. * <?php
  518. * $a = new \phpseclib\Math\BigInteger('65');
  519. *
  520. * echo $a->toHex(); // outputs '41'
  521. * ?>
  522. * </code>
  523. *
  524. * @param bool $twos_compliment
  525. * @return string
  526. * @access public
  527. * @internal Converts a base-2**26 number to base-2**8
  528. */
  529. public function toHex($twos_compliment = false)
  530. {
  531. return Hex::encode($this->toBytes($twos_compliment));
  532. }
  533. /**
  534. * Converts a BigInteger to a bit string (eg. base-2).
  535. *
  536. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  537. * saved as two's compliment.
  538. *
  539. * Here's an example:
  540. * <code>
  541. * <?php
  542. * $a = new \phpseclib\Math\BigInteger('65');
  543. *
  544. * echo $a->toBits(); // outputs '1000001'
  545. * ?>
  546. * </code>
  547. *
  548. * @param bool $twos_compliment
  549. * @return string
  550. * @access public
  551. * @internal Converts a base-2**26 number to base-2**2
  552. */
  553. public function toBits($twos_compliment = false)
  554. {
  555. $hex = $this->toHex($twos_compliment);
  556. $bits = '';
  557. for ($i = strlen($hex) - 8, $start = strlen($hex) & 7; $i >= $start; $i-=8) {
  558. $bits = str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT) . $bits;
  559. }
  560. if ($start) { // hexdec('') == 0
  561. $bits = str_pad(decbin(hexdec(substr($hex, 0, $start))), 8, '0', STR_PAD_LEFT) . $bits;
  562. }
  563. $result = $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0');
  564. if ($twos_compliment && $this->compare(new static()) > 0 && $this->precision <= 0) {
  565. return '0' . $result;
  566. }
  567. return $result;
  568. }
  569. /**
  570. * Converts a BigInteger to a base-10 number.
  571. *
  572. * Here's an example:
  573. * <code>
  574. * <?php
  575. * $a = new \phpseclib\Math\BigInteger('50');
  576. *
  577. * echo $a->toString(); // outputs 50
  578. * ?>
  579. * </code>
  580. *
  581. * @return string
  582. * @access public
  583. * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10)
  584. */
  585. public function toString()
  586. {
  587. switch (MATH_BIGINTEGER_MODE) {
  588. case self::MODE_GMP:
  589. return gmp_strval($this->value);
  590. case self::MODE_BCMATH:
  591. if ($this->value === '0') {
  592. return '0';
  593. }
  594. return ltrim($this->value, '0');
  595. }
  596. if (!count($this->value)) {
  597. return '0';
  598. }
  599. $temp = clone $this;
  600. $temp->is_negative = false;
  601. $divisor = new static();
  602. $divisor->value = array(self::$max10);
  603. $result = '';
  604. while (count($temp->value)) {
  605. list($temp, $mod) = $temp->divide($divisor);
  606. $result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', self::$max10Len, '0', STR_PAD_LEFT) . $result;
  607. }
  608. $result = ltrim($result, '0');
  609. if (empty($result)) {
  610. $result = '0';
  611. }
  612. if ($this->is_negative) {
  613. $result = '-' . $result;
  614. }
  615. return $result;
  616. }
  617. /**
  618. * __toString() magic method
  619. *
  620. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  621. * toString().
  622. *
  623. * @access public
  624. * @internal Implemented per a suggestion by Techie-Michael - thanks!
  625. */
  626. public function __toString()
  627. {
  628. return $this->toString();
  629. }
  630. /**
  631. * __sleep() magic method
  632. *
  633. * Will be called, automatically, when serialize() is called on a BigInteger object.
  634. *
  635. * @see self::__wakeup()
  636. * @access public
  637. */
  638. public function __sleep()
  639. {
  640. $this->hex = $this->toHex(true);
  641. $vars = array('hex');
  642. if ($this->precision > 0) {
  643. $vars[] = 'precision';
  644. }
  645. return $vars;
  646. }
  647. /**
  648. * __wakeup() magic method
  649. *
  650. * Will be called, automatically, when unserialize() is called on a BigInteger object.
  651. *
  652. * @see self::__sleep()
  653. * @access public
  654. */
  655. public function __wakeup()
  656. {
  657. $temp = new static($this->hex, -16);
  658. $this->value = $temp->value;
  659. $this->is_negative = $temp->is_negative;
  660. if ($this->precision > 0) {
  661. // recalculate $this->bitmask
  662. $this->setPrecision($this->precision);
  663. }
  664. }
  665. /**
  666. * __debugInfo() magic method
  667. *
  668. * Will be called, automatically, when print_r() or var_dump() are called
  669. *
  670. * @access public
  671. */
  672. public function __debugInfo()
  673. {
  674. $opts = array();
  675. switch (MATH_BIGINTEGER_MODE) {
  676. case self::MODE_GMP:
  677. $engine = 'gmp';
  678. break;
  679. case self::MODE_BCMATH:
  680. $engine = 'bcmath';
  681. break;
  682. case self::MODE_INTERNAL:
  683. $engine = 'internal';
  684. $opts[] = PHP_INT_SIZE == 8 ? '64-bit' : '32-bit';
  685. }
  686. if (MATH_BIGINTEGER_MODE != self::MODE_GMP && defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) {
  687. $opts[] = 'OpenSSL';
  688. }
  689. if (!empty($opts)) {
  690. $engine.= ' (' . implode($opts, ', ') . ')';
  691. }
  692. return array(
  693. 'value' => '0x' . $this->toHex(true),
  694. 'engine' => $engine
  695. );
  696. }
  697. /**
  698. * Adds two BigIntegers.
  699. *
  700. * Here's an example:
  701. * <code>
  702. * <?php
  703. * $a = new \phpseclib\Math\BigInteger('10');
  704. * $b = new \phpseclib\Math\BigInteger('20');
  705. *
  706. * $c = $a->add($b);
  707. *
  708. * echo $c->toString(); // outputs 30
  709. * ?>
  710. * </code>
  711. *
  712. * @param \phpseclib\Math\BigInteger $y
  713. * @return \phpseclib\Math\BigInteger
  714. * @access public
  715. * @internal Performs base-2**52 addition
  716. */
  717. public function add($y)
  718. {
  719. switch (MATH_BIGINTEGER_MODE) {
  720. case self::MODE_GMP:
  721. $temp = new static();
  722. $temp->value = gmp_add($this->value, $y->value);
  723. return $this->_normalize($temp);
  724. case self::MODE_BCMATH:
  725. $temp = new static();
  726. $temp->value = bcadd($this->value, $y->value, 0);
  727. return $this->_normalize($temp);
  728. }
  729. $temp = self::_add($this->value, $this->is_negative, $y->value, $y->is_negative);
  730. $result = new static();
  731. $result->value = $temp[self::VALUE];
  732. $result->is_negative = $temp[self::SIGN];
  733. return $this->_normalize($result);
  734. }
  735. /**
  736. * Performs addition.
  737. *
  738. * @param array $x_value
  739. * @param bool $x_negative
  740. * @param array $y_value
  741. * @param bool $y_negative
  742. * @return array
  743. * @access private
  744. */
  745. private static function _add($x_value, $x_negative, $y_value, $y_negative)
  746. {
  747. $x_size = count($x_value);
  748. $y_size = count($y_value);
  749. if ($x_size == 0) {
  750. return array(
  751. self::VALUE => $y_value,
  752. self::SIGN => $y_negative
  753. );
  754. } elseif ($y_size == 0) {
  755. return array(
  756. self::VALUE => $x_value,
  757. self::SIGN => $x_negative
  758. );
  759. }
  760. // subtract, if appropriate
  761. if ($x_negative != $y_negative) {
  762. if ($x_value == $y_value) {
  763. return array(
  764. self::VALUE => array(),
  765. self::SIGN => false
  766. );
  767. }
  768. $temp = self::_subtract($x_value, false, $y_value, false);
  769. $temp[self::SIGN] = self::_compare($x_value, false, $y_value, false) > 0 ?
  770. $x_negative : $y_negative;
  771. return $temp;
  772. }
  773. if ($x_size < $y_size) {
  774. $size = $x_size;
  775. $value = $y_value;
  776. } else {
  777. $size = $y_size;
  778. $value = $x_value;
  779. }
  780. $value[count($value)] = 0; // just in case the carry adds an extra digit
  781. $carry = 0;
  782. for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) {
  783. $sum = $x_value[$j] * self::$baseFull + $x_value[$i] + $y_value[$j] * self::$baseFull + $y_value[$i] + $carry;
  784. $carry = $sum >= self::$maxDigit2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  785. $sum = $carry ? $sum - self::$maxDigit2 : $sum;
  786. $temp = self::$base === 26 ? intval($sum / 0x4000000) : ($sum >> 31);
  787. $value[$i] = (int) ($sum - self::$baseFull * $temp); // eg. a faster alternative to fmod($sum, 0x4000000)
  788. $value[$j] = $temp;
  789. }
  790. if ($j == $size) { // ie. if $y_size is odd
  791. $sum = $x_value[$i] + $y_value[$i] + $carry;
  792. $carry = $sum >= self::$baseFull;
  793. $value[$i] = $carry ? $sum - self::$baseFull : $sum;
  794. ++$i; // ie. let $i = $j since we've just done $value[$i]
  795. }
  796. if ($carry) {
  797. for (; $value[$i] == self::$maxDigit; ++$i) {
  798. $value[$i] = 0;
  799. }
  800. ++$value[$i];
  801. }
  802. return array(
  803. self::VALUE => self::_trim($value),
  804. self::SIGN => $x_negative
  805. );
  806. }
  807. /**
  808. * Subtracts two BigIntegers.
  809. *
  810. * Here's an example:
  811. * <code>
  812. * <?php
  813. * $a = new \phpseclib\Math\BigInteger('10');
  814. * $b = new \phpseclib\Math\BigInteger('20');
  815. *
  816. * $c = $a->subtract($b);
  817. *
  818. * echo $c->toString(); // outputs -10
  819. * ?>
  820. * </code>
  821. *
  822. * @param \phpseclib\Math\BigInteger $y
  823. * @return \phpseclib\Math\BigInteger
  824. * @access public
  825. * @internal Performs base-2**52 subtraction
  826. */
  827. public function subtract($y)
  828. {
  829. switch (MATH_BIGINTEGER_MODE) {
  830. case self::MODE_GMP:
  831. $temp = new static();
  832. $temp->value = gmp_sub($this->value, $y->value);
  833. return $this->_normalize($temp);
  834. case self::MODE_BCMATH:
  835. $temp = new static();
  836. $temp->value = bcsub($this->value, $y->value, 0);
  837. return $this->_normalize($temp);
  838. }
  839. $temp = self::_subtract($this->value, $this->is_negative, $y->value, $y->is_negative);
  840. $result = new static();
  841. $result->value = $temp[self::VALUE];
  842. $result->is_negative = $temp[self::SIGN];
  843. return $this->_normalize($result);
  844. }
  845. /**
  846. * Performs subtraction.
  847. *
  848. * @param array $x_value
  849. * @param bool $x_negative
  850. * @param array $y_value
  851. * @param bool $y_negative
  852. * @return array
  853. * @access private
  854. */
  855. private static function _subtract($x_value, $x_negative, $y_value, $y_negative)
  856. {
  857. $x_size = count($x_value);
  858. $y_size = count($y_value);
  859. if ($x_size == 0) {
  860. return array(
  861. self::VALUE => $y_value,
  862. self::SIGN => !$y_negative
  863. );
  864. } elseif ($y_size == 0) {
  865. return array(
  866. self::VALUE => $x_value,
  867. self::SIGN => $x_negative
  868. );
  869. }
  870. // add, if appropriate (ie. -$x - +$y or +$x - -$y)
  871. if ($x_negative != $y_negative) {
  872. $temp = self::_add($x_value, false, $y_value, false);
  873. $temp[self::SIGN] = $x_negative;
  874. return $temp;
  875. }
  876. $diff = self::_compare($x_value, $x_negative, $y_value, $y_negative);
  877. if (!$diff) {
  878. return array(
  879. self::VALUE => array(),
  880. self::SIGN => false
  881. );
  882. }
  883. // switch $x and $y around, if appropriate.
  884. if ((!$x_negative && $diff < 0) || ($x_negative && $diff > 0)) {
  885. $temp = $x_value;
  886. $x_value = $y_value;
  887. $y_value = $temp;
  888. $x_negative = !$x_negative;
  889. $x_size = count($x_value);
  890. $y_size = count($y_value);
  891. }
  892. // at this point, $x_value should be at least as big as - if not bigger than - $y_value
  893. $carry = 0;
  894. for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) {
  895. $sum = $x_value[$j] * self::$baseFull + $x_value[$i] - $y_value[$j] * self::$baseFull - $y_value[$i] - $carry;
  896. $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  897. $sum = $carry ? $sum + self::$maxDigit2 : $sum;
  898. $temp = self::$base === 26 ? intval($sum / 0x4000000) : ($sum >> 31);
  899. $x_value[$i] = (int) ($sum - self::$baseFull * $temp);
  900. $x_value[$j] = $temp;
  901. }
  902. if ($j == $y_size) { // ie. if $y_size is odd
  903. $sum = $x_value[$i] - $y_value[$i] - $carry;
  904. $carry = $sum < 0;
  905. $x_value[$i] = $carry ? $sum + self::$baseFull : $sum;
  906. ++$i;
  907. }
  908. if ($carry) {
  909. for (; !$x_value[$i]; ++$i) {
  910. $x_value[$i] = self::$maxDigit;
  911. }
  912. --$x_value[$i];
  913. }
  914. return array(
  915. self::VALUE => self::_trim($x_value),
  916. self::SIGN => $x_negative
  917. );
  918. }
  919. /**
  920. * Multiplies two BigIntegers
  921. *
  922. * Here's an example:
  923. * <code>
  924. * <?php
  925. * $a = new \phpseclib\Math\BigInteger('10');
  926. * $b = new \phpseclib\Math\BigInteger('20');
  927. *
  928. * $c = $a->multiply($b);
  929. *
  930. * echo $c->toString(); // outputs 200
  931. * ?>
  932. * </code>
  933. *
  934. * @param \phpseclib\Math\BigInteger $x
  935. * @return \phpseclib\Math\BigInteger
  936. * @access public
  937. */
  938. public function multiply($x)
  939. {
  940. switch (MATH_BIGINTEGER_MODE) {
  941. case self::MODE_GMP:
  942. $temp = new static();
  943. $temp->value = gmp_mul($this->value, $x->value);
  944. return $this->_normalize($temp);
  945. case self::MODE_BCMATH:
  946. $temp = new static();
  947. $temp->value = bcmul($this->value, $x->value, 0);
  948. return $this->_normalize($temp);
  949. }
  950. $temp = self::_multiply($this->value, $this->is_negative, $x->value, $x->is_negative);
  951. $product = new static();
  952. $product->value = $temp[self::VALUE];
  953. $product->is_negative = $temp[self::SIGN];
  954. return $this->_normalize($product);
  955. }
  956. /**
  957. * Performs multiplication.
  958. *
  959. * @param array $x_value
  960. * @param bool $x_negative
  961. * @param array $y_value
  962. * @param bool $y_negative
  963. * @return array
  964. * @access private
  965. */
  966. private static function _multiply($x_value, $x_negative, $y_value, $y_negative)
  967. {
  968. //if ( $x_value == $y_value ) {
  969. // return [
  970. // self::VALUE => $this->_square($x_value),
  971. // self::SIGN => $x_sign != $y_value
  972. // ];
  973. //}
  974. $x_length = count($x_value);
  975. $y_length = count($y_value);
  976. if (!$x_length || !$y_length) { // a 0 is being multiplied
  977. return array(
  978. self::VALUE => array(),
  979. self::SIGN => false
  980. );
  981. }
  982. return array(
  983. self::VALUE => min($x_length, $y_length) < 2 * self::KARATSUBA_CUTOFF ?
  984. self::_trim(self::_regularMultiply($x_value, $y_value)) :
  985. self::_trim(self::_karatsuba($x_value, $y_value)),
  986. self::SIGN => $x_negative != $y_negative
  987. );
  988. }
  989. /**
  990. * Performs long multiplication on two BigIntegers
  991. *
  992. * Modeled after 'multiply' in MutableBigInteger.java.
  993. *
  994. * @param array $x_value
  995. * @param array $y_value
  996. * @return array
  997. * @access private
  998. */
  999. private static function _regularMultiply($x_value, $y_value)
  1000. {
  1001. $x_length = count($x_value);
  1002. $y_length = count($y_value);
  1003. if (!$x_length || !$y_length) { // a 0 is being multiplied
  1004. return array();
  1005. }
  1006. if ($x_length < $y_length) {
  1007. $temp = $x_value;
  1008. $x_value = $y_value;
  1009. $y_value = $temp;
  1010. $x_length = count($x_value);
  1011. $y_length = count($y_value);
  1012. }
  1013. $product_value = self::_array_repeat(0, $x_length + $y_length);
  1014. // the following for loop could be removed if the for loop following it
  1015. // (the one with nested for loops) initially set $i to 0, but
  1016. // doing so would also make the result in one set of unnecessary adds,
  1017. // since on the outermost loops first pass, $product->value[$k] is going
  1018. // to always be 0
  1019. $carry = 0;
  1020. for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0
  1021. $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
  1022. $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1023. $product_value[$j] = (int) ($temp - self::$baseFull * $carry);
  1024. }
  1025. $product_value[$j] = $carry;
  1026. // the above for loop is what the previous comment was talking about. the
  1027. // following for loop is the "one with nested for loops"
  1028. for ($i = 1; $i < $y_length; ++$i) {
  1029. $carry = 0;
  1030. for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) {
  1031. $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
  1032. $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1033. $product_value[$k] = (int) ($temp - self::$baseFull * $carry);
  1034. }
  1035. $product_value[$k] = $carry;
  1036. }
  1037. return $product_value;
  1038. }
  1039. /**
  1040. * Performs Karatsuba multiplication on two BigIntegers
  1041. *
  1042. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1043. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}.
  1044. *
  1045. * @param array $x_value
  1046. * @param array $y_value
  1047. * @return array
  1048. * @access private
  1049. */
  1050. private static function _karatsuba($x_value, $y_value)
  1051. {
  1052. $m = min(count($x_value) >> 1, count($y_value) >> 1);
  1053. if ($m < self::KARATSUBA_CUTOFF) {
  1054. return self::_regularMultiply($x_value, $y_value);
  1055. }
  1056. $x1 = array_slice($x_value, $m);
  1057. $x0 = array_slice($x_value, 0, $m);
  1058. $y1 = array_slice($y_value, $m);
  1059. $y0 = array_slice($y_value, 0, $m);
  1060. $z2 = self::_karatsuba($x1, $y1);
  1061. $z0 = self::_karatsuba($x0, $y0);
  1062. $z1 = self::_add($x1, false, $x0, false);
  1063. $temp = self::_add($y1, false, $y0, false);
  1064. $z1 = self::_karatsuba($z1[self::VALUE], $temp[self::VALUE]);
  1065. $temp = self::_add($z2, false, $z0, false);
  1066. $z1 = self::_subtract($z1, false, $temp[self::VALUE], false);
  1067. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1068. $z1[self::VALUE] = array_merge(array_fill(0, $m, 0), $z1[self::VALUE]);
  1069. $xy = self::_add($z2, false, $z1[self::VALUE], $z1[self::SIGN]);
  1070. $xy = self::_add($xy[self::VALUE], $xy[self::SIGN], $z0, false);
  1071. return $xy[self::VALUE];
  1072. }
  1073. /**
  1074. * Performs squaring
  1075. *
  1076. * @param array $x
  1077. * @return array
  1078. * @access private
  1079. */
  1080. private static function _square($x = false)
  1081. {
  1082. return count($x) < 2 * self::KARATSUBA_CUTOFF ?
  1083. self::_trim(self::_baseSquare($x)) :
  1084. self::_trim(self::_karatsubaSquare($x));
  1085. }
  1086. /**
  1087. * Performs traditional squaring on two BigIntegers
  1088. *
  1089. * Squaring can be done faster than multiplying a number by itself can be. See
  1090. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} /
  1091. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information.
  1092. *
  1093. * @param array $value
  1094. * @return array
  1095. * @access private
  1096. */
  1097. private static function _baseSquare($value)
  1098. {
  1099. if (empty($value)) {
  1100. return array();
  1101. }
  1102. $square_value = self::_array_repeat(0, 2 * count($value));
  1103. for ($i = 0, $max_index = count($value) - 1; $i <= $max_index; ++$i) {
  1104. $i2 = $i << 1;
  1105. $temp = $square_value[$i2] + $value[$i] * $value[$i];
  1106. $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1107. $square_value[$i2] = (int) ($temp - self::$baseFull * $carry);
  1108. // note how we start from $i+1 instead of 0 as we do in multiplication.
  1109. for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) {
  1110. $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry;
  1111. $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1112. $square_value[$k] = (int) ($temp - self::$baseFull * $carry);
  1113. }
  1114. // the following line can yield values larger 2**15. at this point, PHP should switch
  1115. // over to floats.
  1116. $square_value[$i + $max_index + 1] = $carry;
  1117. }
  1118. return $square_value;
  1119. }
  1120. /**
  1121. * Performs Karatsuba "squaring" on two BigIntegers
  1122. *
  1123. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1124. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}.
  1125. *
  1126. * @param array $value
  1127. * @return array
  1128. * @access private
  1129. */
  1130. private static function _karatsubaSquare($value)
  1131. {
  1132. $m = count($value) >> 1;
  1133. if ($m < self::KARATSUBA_CUTOFF) {
  1134. return self::_baseSquare($value);
  1135. }
  1136. $x1 = array_slice($value, $m);
  1137. $x0 = array_slice($value, 0, $m);
  1138. $z2 = self::_karatsubaSquare($x1);
  1139. $z0 = self::_karatsubaSquare($x0);
  1140. $z1 = self::_add($x1, false, $x0, false);
  1141. $z1 = self::_karatsubaSquare($z1[self::VALUE]);
  1142. $temp = self::_add($z2, false, $z0, false);
  1143. $z1 = self::_subtract($z1, false, $temp[self::VALUE], false);
  1144. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1145. $z1[self::VALUE] = array_merge(array_fill(0, $m, 0), $z1[self::VALUE]);
  1146. $xx = self::_add($z2, false, $z1[self::VALUE], $z1[self::SIGN]);
  1147. $xx = self::_add($xx[self::VALUE], $xx[self::SIGN], $z0, false);
  1148. return $xx[self::VALUE];
  1149. }
  1150. /**
  1151. * Divides two BigIntegers.
  1152. *
  1153. * Returns an array whose first element contains the quotient and whose second element contains the
  1154. * "common residue". If the remainder would be positive, the "common residue" and the remainder are the
  1155. * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder
  1156. * and the divisor (basically, the "common residue" is the first positive modulo).
  1157. *
  1158. * Here's an example:
  1159. * <code>
  1160. * <?php
  1161. * $a = new \phpseclib\Math\BigInteger('10');
  1162. * $b = new \phpseclib\Math\BigInteger('20');
  1163. *
  1164. * list($quotient, $remainder) = $a->divide($b);
  1165. *
  1166. * echo $quotient->toString(); // outputs 0
  1167. * echo "\r\n";
  1168. * echo $remainder->toString(); // outputs 10
  1169. * ?>
  1170. * </code>
  1171. *
  1172. * @param \phpseclib\Math\BigInteger $y
  1173. * @return array
  1174. * @access public
  1175. * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}.
  1176. */
  1177. public function divide($y)
  1178. {
  1179. switch (MATH_BIGINTEGER_MODE) {
  1180. case self::MODE_GMP:
  1181. $quotient = new static();
  1182. $remainder = new static();
  1183. list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value);
  1184. if (gmp_sign($remainder->value) < 0) {
  1185. $remainder->value = gmp_add($remainder->value, gmp_abs($y->value));
  1186. }
  1187. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1188. case self::MODE_BCMATH:
  1189. $quotient = new static();
  1190. $remainder = new static();
  1191. $quotient->value = bcdiv($this->value, $y->value, 0);
  1192. $remainder->value = bcmod($this->value, $y->value);
  1193. if ($remainder->value[0] == '-') {
  1194. $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value, 0);
  1195. }
  1196. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1197. }
  1198. if (count($y->value) == 1) {
  1199. list($q, $r) = $this->_divide_digit($this->value, $y->value[0]);
  1200. $quotient = new static();
  1201. $remainder = new static();
  1202. $quotient->value = $q;
  1203. $remainder->value = array($r);
  1204. $quotient->is_negative = $this->is_negative != $y->is_negative;
  1205. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1206. }
  1207. static $zero;
  1208. if (!isset($zero)) {
  1209. $zero = new static();
  1210. }
  1211. $x = clone $this;
  1212. $y = clone $y;
  1213. $x_sign = $x->is_negative;
  1214. $y_sign = $y->is_negative;
  1215. $x->is_negative = $y->is_negative = false;
  1216. $diff = $x->compare($y);
  1217. if (!$diff) {
  1218. $temp = new static();
  1219. $temp->value = array(1);
  1220. $temp->is_negative = $x_sign != $y_sign;
  1221. return array($this->_normalize($temp), $this->_normalize(new static()));
  1222. }
  1223. if ($diff < 0) {
  1224. // if $x is negative, "add" $y.
  1225. if ($x_sign) {
  1226. $x = $y->subtract($x);
  1227. }
  1228. return array($this->_normalize(new static()), $this->_normalize($x));
  1229. }
  1230. // normalize $x and $y as described in HAC 14.23 / 14.24
  1231. $msb = $y->value[count($y->value) - 1];
  1232. for ($shift = 0; !($msb & self::$msb); ++$shift) {
  1233. $msb <<= 1;
  1234. }
  1235. $x->_lshift($shift);
  1236. $y->_lshift($shift);
  1237. $y_value = &$y->value;
  1238. $x_max = count($x->value) - 1;
  1239. $y_max = count($y->value) - 1;
  1240. $quotient = new static();
  1241. $quotient_value = &$quotient->value;
  1242. $quotient_value = self::_array_repeat(0, $x_max - $y_max + 1);
  1243. static $temp, $lhs, $rhs;
  1244. if (!isset($temp)) {
  1245. $temp = new static();
  1246. $lhs = new static();
  1247. $rhs = new static();
  1248. }
  1249. $temp_value = &$temp->value;
  1250. $rhs_value = &$rhs->value;
  1251. // $temp = $y << ($x_max - $y_max-1) in base 2**26
  1252. $temp_value = array_merge(self::_array_repeat(0, $x_max - $y_max), $y_value);
  1253. while ($x->compare($temp) >= 0) {
  1254. // calculate the "common residue"
  1255. ++$quotient_value[$x_max - $y_max];
  1256. $x = $x->subtract($temp);
  1257. $x_max = count($x->value) - 1;
  1258. }
  1259. for ($i = $x_max; $i >= $y_max + 1; --$i) {
  1260. $x_value = &$x->value;
  1261. $x_window = array(
  1262. isset($x_value[$i]) ? $x_value[$i] : 0,
  1263. isset($x_value[$i - 1]) ? $x_value[$i - 1] : 0,
  1264. isset($x_value[$i - 2]) ? $x_value[$i - 2] : 0
  1265. );
  1266. $y_window = array(
  1267. $y_value[$y_max],
  1268. ($y_max > 0) ? $y_value[$y_max - 1] : 0
  1269. );
  1270. $q_index = $i - $y_max - 1;
  1271. if ($x_window[0] == $y_window[0]) {
  1272. $quotient_value[$q_index] = self::$maxDigit;
  1273. } else {
  1274. $quotient_value[$q_index] = $this->_safe_divide(
  1275. $x_window[0] * self::$baseFull + $x_window[1],
  1276. $y_window[0]
  1277. );
  1278. }
  1279. $temp_value = array($y_window[1], $y_window[0]);
  1280. $lhs->value = array($quotient_value[$q_index]);
  1281. $lhs = $lhs->multiply($temp);
  1282. $rhs_value = array($x_window[2], $x_window[1], $x_window[0]);
  1283. while ($lhs->compare($rhs) > 0) {
  1284. --$quotient_value[$q_index];
  1285. $lhs->value = array($quotient_value[$q_index]);
  1286. $lhs = $lhs->multiply($temp);
  1287. }
  1288. $adjust = self::_array_repeat(0, $q_index);
  1289. $temp_value = array($quotient_value[$q_index]);
  1290. $temp = $temp->multiply($y);
  1291. $temp_value = &$temp->value;
  1292. $temp_value = array_merge($adjust, $temp_value);
  1293. $x = $x->subtract($temp);
  1294. if ($x->compare($zero) < 0) {
  1295. $temp_value = array_merge($adjust, $y_value);
  1296. $x = $x->add($temp);
  1297. --$quotient_value[$q_index];
  1298. }
  1299. $x_max = count($x_value) - 1;
  1300. }
  1301. // unnormalize the remainder
  1302. $x->_rshift($shift);
  1303. $quotient->is_negative = $x_sign != $y_sign;
  1304. // calculate the "common residue", if appropriate
  1305. if ($x_sign) {
  1306. $y->_rshift($shift);
  1307. $x = $y->subtract($x);
  1308. }
  1309. return array($this->_normalize($quotient), $this->_normalize($x));
  1310. }
  1311. /**
  1312. * Divides a BigInteger by a regular integer
  1313. *
  1314. * abc / x = a00 / x + b0 / x + c / x
  1315. *
  1316. * @param array $dividend
  1317. * @param array $divisor
  1318. * @return array
  1319. * @access private
  1320. */
  1321. private static function _divide_digit($dividend, $divisor)
  1322. {
  1323. $carry = 0;
  1324. $result = array();
  1325. for ($i = count($dividend) - 1; $i >= 0; --$i) {
  1326. $temp = self::$baseFull * $carry + $dividend[$i];
  1327. $result[$i] = self::_safe_divide($temp, $divisor);
  1328. $carry = (int) ($temp - $divisor * $result[$i]);
  1329. }
  1330. return array($result, $carry);
  1331. }
  1332. /**
  1333. * Performs modular exponentiation.
  1334. *
  1335. * Here's an example:
  1336. * <code>
  1337. * <?php
  1338. * $a = new \phpseclib\Math\BigInteger('10');
  1339. * $b = new \phpseclib\Math\BigInteger('20');
  1340. * $c = new \phpseclib\Math\BigInteger('30');
  1341. *
  1342. * $c = $a->modPow($b, $c);
  1343. *
  1344. * echo $c->toString(); // outputs 10
  1345. * ?>
  1346. * </code>
  1347. *
  1348. * @param \phpseclib\Math\BigInteger $e
  1349. * @param \phpseclib\Math\BigInteger $n
  1350. * @return \phpseclib\Math\BigInteger
  1351. * @access public
  1352. * @internal The most naive approach to modular exponentiation has very unreasonable requirements, and
  1353. * and although the approach involving repeated squaring does vastly better, it, too, is impractical
  1354. * for our purposes. The reason being that division - by far the most complicated and time-consuming
  1355. * of the basic operations (eg. +,-,*,/) - occurs multiple times within it.
  1356. *
  1357. * Modular reductions resolve this issue. Although an individual modular reduction takes more time
  1358. * then an individual division, when performed in succession (with the same modulo), they're a lot faster.
  1359. *
  1360. * The two most commonly used modular reductions are Barrett and Montgomery reduction. Montgomery reduction,
  1361. * although faster, only works when the gcd of the modulo and of the base being used is 1. In RSA, when the
  1362. * base is a power of two, the modulo - a product of two primes - is always going to have a gcd of 1 (because
  1363. * the product of two odd numbers is odd), but what about when RSA isn't used?
  1364. *
  1365. * In contrast, Barrett reduction has no such constraint. As such, some bigint implementations perform a
  1366. * Barrett reduction after every operation in the modpow function. Others perform Barrett reductions when the
  1367. * modulo is even and Montgomery reductions when the modulo is odd. BigInteger.java's modPow method, however,
  1368. * uses a trick involving the Chinese Remainder Theorem to factor the even modulo into two numbers - one odd and
  1369. * the other, a power of two - and recombine them, later. This is the method that this modPow function uses.
  1370. * {@link http://islab.oregonstate.edu/papers/j34monex.pdf Montgomery Reduction with Even Modulus} elaborates.
  1371. */
  1372. public function modPow($e, $n)
  1373. {
  1374. $n = $this->bitmask !== false && $this->bitmask->compare($n) < 0 ? $this->bitmask : $n->abs();
  1375. if ($e->compare(new static()) < 0) {
  1376. $e = $e->abs();
  1377. $temp = $this->modInverse($n);
  1378. if ($temp === false) {
  1379. return false;
  1380. }
  1381. return $this->_normalize($temp->modPow($e, $n));
  1382. }
  1383. if (MATH_BIGINTEGER_MODE == self::MODE_GMP) {
  1384. $temp = new static();
  1385. $temp->value = gmp_powm($this->value, $e->value, $n->value);
  1386. return $this->_normalize($temp);
  1387. }
  1388. if ($this->compare(new static()) < 0 || $this->compare($n) > 0) {
  1389. list(, $temp) = $this->divide($n);
  1390. return $temp->modPow($e, $n);
  1391. }
  1392. if (defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) {
  1393. $components = array(
  1394. 'modulus' => $n->toBytes(true),
  1395. 'publicExponent' => $e->toBytes(true)
  1396. );
  1397. $components = array(
  1398. 'modulus' => pack('Ca*a*', 2, ASN1::encodeLength(strlen($components['modulus'])), $components['modulus']),
  1399. 'publicExponent' => pack('Ca*a*', 2, ASN1::encodeLength(strlen($components['publicExponent'])), $components['publicExponent'])
  1400. );
  1401. $RSAPublicKey = pack(
  1402. 'Ca*a*a*',
  1403. 48,
  1404. ASN1::encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  1405. $components['modulus'],
  1406. $components['publicExponent']
  1407. );
  1408. $rsaOID = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00"; // hex version of MA0GCSqGSIb3DQEBAQUA
  1409. $RSAPublicKey = chr(0) . $RSAPublicKey;
  1410. $RSAPublicKey = chr(3) . ASN1::encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
  1411. $encapsulated = pack(
  1412. 'Ca*a*',
  1413. 48,
  1414. ASN1::encodeLength(strlen($rsaOID . $RSAPublicKey)),
  1415. $rsaOID . $RSAPublicKey
  1416. );
  1417. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  1418. chunk_split(Base64::encode($encapsulated)) .
  1419. '-----END PUBLIC KEY-----';
  1420. $plaintext = str_pad($this->toBytes(), strlen($n->toBytes(true)) - 1, "\0", STR_PAD_LEFT);
  1421. if (openssl_public_encrypt($plaintext, $result, $RSAPublicKey, OPENSSL_NO_PADDING)) {
  1422. return new static($result, 256);
  1423. }
  1424. }
  1425. if (MATH_BIGINTEGER_MODE == self::MODE_BCMATH) {
  1426. $temp = new static();
  1427. $temp->value = bcpowmod($this->value, $e->value, $n->value, 0);
  1428. return $this->_normalize($temp);
  1429. }
  1430. if (empty($e->value)) {
  1431. $temp = new static();
  1432. $temp->value = array(1);
  1433. return $this->_normalize($temp);
  1434. }
  1435. if ($e->value == array(1)) {
  1436. list(, $temp) = $this->divide($n);
  1437. return $this->_normalize($temp);
  1438. }
  1439. if ($e->value == array(2)) {
  1440. $temp = new static();
  1441. $temp->value = self::_square($this->value);
  1442. list(, $temp) = $temp->divide($n);
  1443. return $this->_normalize($temp);
  1444. }
  1445. return $this->_normalize($this->_slidingWindow($e, $n, self::BARRETT));
  1446. // the following code, although not callable, can be run independently of the above code
  1447. // although the above code performed better in my benchmarks the following could might
  1448. // perform better under different circumstances. in lieu of deleting it it's just been
  1449. // made uncallable
  1450. // is the modulo odd?
  1451. if ($n->value[0] & 1) {
  1452. return $this->_normalize($this->_slidingWindow($e, $n, self::MONTGOMERY));
  1453. }
  1454. // if it's not, it's even
  1455. // find the lowest set bit (eg. the max pow of 2 that divides $n)
  1456. for ($i = 0; $i < count($n->value); ++$i) {
  1457. if ($n->value[$i]) {
  1458. $temp = decbin($n->value[$i]);
  1459. $j = strlen($temp) - strrpos($temp, '1') - 1;
  1460. $j+= 26 * $i;
  1461. break;
  1462. }
  1463. }
  1464. // at this point, 2^$j * $n/(2^$j) == $n
  1465. $mod1 = clone $n;
  1466. $mod1->_rshift($j);
  1467. $mod2 = new static();
  1468. $mod2->value = array(1);
  1469. $mod2->_lshift($j);
  1470. $part1 = ($mod1->value != array(1)) ? $this->_slidingWindow($e, $mod1, self::MONTGOMERY) : new static();
  1471. $part2 = $this->_slidingWindow($e, $mod2, self::POWEROF2);
  1472. $y1 = $mod2->modInverse($mod1);
  1473. $y2 = $mod1->modInverse($mod2);
  1474. $result = $part1->multiply($mod2);
  1475. $result = $result->multiply($y1);
  1476. $temp = $part2->multiply($mod1);
  1477. $temp = $temp->multiply($y2);
  1478. $result = $result->add($temp);
  1479. list(, $result) = $result->divide($n);
  1480. return $this->_normalize($result);
  1481. }
  1482. /**
  1483. * Performs modular exponentiation.
  1484. *
  1485. * Alias for modPow().
  1486. *
  1487. * @param \phpseclib\Math\BigInteger $e
  1488. * @param \phpseclib\Math\BigInteger $n
  1489. * @return \phpseclib\Math\BigInteger
  1490. * @access public
  1491. */
  1492. public function powMod($e, $n)
  1493. {
  1494. return $this->modPow($e, $n);
  1495. }
  1496. /**
  1497. * Sliding Window k-ary Modular Exponentiation
  1498. *
  1499. * Based on {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=27 HAC 14.85} /
  1500. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=210 MPM 7.7}. In a departure from those algorithims,
  1501. * however, this function performs a modular reduction after every multiplication and squaring operation.
  1502. * As such, this function has the same preconditions that the reductions being used do.
  1503. *
  1504. * @param \phpseclib\Math\BigInteger $e
  1505. * @param \phpseclib\Math\BigInteger $n
  1506. * @param int $mode
  1507. * @return \phpseclib\Math\BigInteger
  1508. * @access private
  1509. */
  1510. private function _slidingWindow($e, $n, $mode)
  1511. {
  1512. static $window_ranges = array(7, 25, 81, 241, 673, 1793); // from BigInteger.java's oddModPow function
  1513. //static $window_ranges = array(0, 7, 36, 140, 450, 1303, 3529); // from MPM 7.3.1
  1514. $e_value = $e->value;
  1515. $e_length = count($e_value) - 1;
  1516. $e_bits = decbin($e_value[$e_length]);
  1517. for ($i = $e_length - 1; $i >= 0; --$i) {
  1518. $e_bits.= str_pad(decbin($e_value[$i]), self::$base, '0', STR_PAD_LEFT);
  1519. }
  1520. $e_length = strlen($e_bits);
  1521. // calculate the appropriate window size.
  1522. // $window_size == 3 if $window_ranges is between 25 and 81, for example.
  1523. for ($i = 0, $window_size = 1; $i < count($window_ranges) && $e_length > $window_ranges[$i]; ++$window_size, ++$i) {
  1524. }
  1525. $n_value = $n->value;
  1526. // precompute $this^0 through $this^$window_size
  1527. $powers = array();
  1528. $powers[1] = self::_prepareReduce($this->value, $n_value, $mode);
  1529. $powers[2] = self::_squareReduce($powers[1], $n_value, $mode);
  1530. // we do every other number since substr($e_bits, $i, $j+1) (see below) is supposed to end
  1531. // in a 1. ie. it's supposed to be odd.
  1532. $temp = 1 << ($window_size - 1);
  1533. for ($i = 1; $i < $temp; ++$i) {
  1534. $i2 = $i << 1;
  1535. $powers[$i2 + 1] = self::_multiplyReduce($powers[$i2 - 1], $powers[2], $n_value, $mode);
  1536. }
  1537. $result = array(1);
  1538. $result = self::_prepareReduce($result, $n_value, $mode);
  1539. for ($i = 0; $i < $e_length;) {
  1540. if (!$e_bits[$i]) {
  1541. $result = self::_squareReduce($result, $n_value, $mode);
  1542. ++$i;
  1543. } else {
  1544. for ($j = $window_size - 1; $j > 0; --$j) {
  1545. if (!empty($e_bits[$i + $j])) {
  1546. break;
  1547. }
  1548. }
  1549. // eg. the length of substr($e_bits, $i, $j + 1)
  1550. for ($k = 0; $k <= $j; ++$k) {
  1551. $result = self::_squareReduce($result, $n_value, $mode);
  1552. }
  1553. $result = self::_multiplyReduce($result, $powers[bindec(substr($e_bits, $i, $j + 1))], $n_value, $mode);
  1554. $i += $j + 1;
  1555. }
  1556. }
  1557. $temp = new static();
  1558. $temp->value = self::_reduce($result, $n_value, $mode);
  1559. return $temp;
  1560. }
  1561. /**
  1562. * Modular reduction
  1563. *
  1564. * For most $modes this will return the remainder.
  1565. *
  1566. * @see self::_slidingWindow()
  1567. * @access private
  1568. * @param array $x
  1569. * @param array $n
  1570. * @param int $mode
  1571. * @return array
  1572. */
  1573. private static function _reduce($x, $n, $mode)
  1574. {
  1575. switch ($mode) {
  1576. case self::MONTGOMERY:
  1577. return self::_montgomery($x, $n);
  1578. case self::BARRETT:
  1579. return self::_barrett($x, $n);
  1580. case self::POWEROF2:
  1581. $lhs = new static();
  1582. $lhs->value = $x;
  1583. $rhs = new static();
  1584. $rhs->value = $n;
  1585. return $x->_mod2($n);
  1586. case self::CLASSIC:
  1587. $lhs = new static();
  1588. $lhs->value = $x;
  1589. $rhs = new static();
  1590. $rhs->value = $n;
  1591. list(, $temp) = $lhs->divide($rhs);
  1592. return $temp->value;
  1593. case self::NONE:
  1594. return $x;
  1595. default:
  1596. // an invalid $mode was provided
  1597. }
  1598. }
  1599. /**
  1600. * Modular reduction preperation
  1601. *
  1602. * @see self::_slidingWindow()
  1603. * @access private
  1604. * @param array $x
  1605. * @param array $n
  1606. * @param int $mode
  1607. * @return array
  1608. */
  1609. private static function _prepareReduce($x, $n, $mode)
  1610. {
  1611. if ($mode == self::MONTGOMERY) {
  1612. return self::_prepMontgomery($x, $n);
  1613. }
  1614. return self::_reduce($x, $n, $mode);
  1615. }
  1616. /**
  1617. * Modular multiply
  1618. *
  1619. * @see self::_slidingWindow()
  1620. * @access private
  1621. * @param array $x
  1622. * @param array $y
  1623. * @param array $n
  1624. * @param int $mode
  1625. * @return array
  1626. */
  1627. private static function _multiplyReduce($x, $y, $n, $mode)
  1628. {
  1629. if ($mode == self::MONTGOMERY) {
  1630. return self::_montgomeryMultiply($x, $y, $n);
  1631. }
  1632. $temp = self::_multiply($x, false, $y, false);
  1633. return self::_reduce($temp[self::VALUE], $n, $mode);
  1634. }
  1635. /**
  1636. * Modular square
  1637. *
  1638. * @see self::_slidingWindow()
  1639. * @access private
  1640. * @param array $x
  1641. * @param array $n
  1642. * @param int $mode
  1643. * @return array
  1644. */
  1645. private static function _squareReduce($x, $n, $mode)
  1646. {
  1647. if ($mode == self::MONTGOMERY) {
  1648. return self::_montgomeryMultiply($x, $x, $n);
  1649. }
  1650. return self::_reduce(self::_square($x), $n, $mode);
  1651. }
  1652. /**
  1653. * Modulos for Powers of Two
  1654. *
  1655. * Calculates $x%$n, where $n = 2**$e, for some $e. Since this is basically the same as doing $x & ($n-1),
  1656. * we'll just use this function as a wrapper for doing that.
  1657. *
  1658. * @see self::_slidingWindow()
  1659. * @access private
  1660. * @param \phpseclib\Math\BigInteger
  1661. * @return \phpseclib\Math\BigInteger
  1662. */
  1663. private function _mod2($n)
  1664. {
  1665. $temp = new static();
  1666. $temp->value = array(1);
  1667. return $this->bitwise_and($n->subtract($temp));
  1668. }
  1669. /**
  1670. * Barrett Modular Reduction
  1671. *
  1672. * See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=14 HAC 14.3.3} /
  1673. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=165 MPM 6.2.5} for more information. Modified slightly,
  1674. * so as not to require negative numbers (initially, this script didn't support negative numbers).
  1675. *
  1676. * Employs "folding", as described at
  1677. * {@link http://www.cosic.esat.kuleuven.be/publications/thesis-149.pdf#page=66 thesis-149.pdf#page=66}. To quote from
  1678. * it, "the idea [behind folding] is to find a value x' such that x (mod m) = x' (mod m), with x' being smaller than x."
  1679. *
  1680. * Unfortunately, the "Barrett Reduction with Folding" algorithm described in thesis-149.pdf is not, as written, all that
  1681. * usable on account of (1) its not using reasonable radix points as discussed in
  1682. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=162 MPM 6.2.2} and (2) the fact that, even with reasonable
  1683. * radix points, it only works when there are an even number of digits in the denominator. The reason for (2) is that
  1684. * (x >> 1) + (x >> 1) != x / 2 + x / 2. If x is even, they're the same, but if x is odd, they're not. See the in-line
  1685. * comments for details.
  1686. *
  1687. * @see self::_slidingWindow()
  1688. * @access private
  1689. * @param array $n
  1690. * @param array $m
  1691. * @return array
  1692. */
  1693. private static function _barrett($n, $m)
  1694. {
  1695. static $cache = array(
  1696. self::VARIABLE => array(),
  1697. self::DATA => array()
  1698. );
  1699. $m_length = count($m);
  1700. // if (self::_compare($n, self::_square($m)) >= 0) {
  1701. if (count($n) > 2 * $m_length) {
  1702. $lhs = new static();
  1703. $rhs = new static();
  1704. $lhs->value = $n;
  1705. $rhs->value = $m;
  1706. list(, $temp) = $lhs->divide($rhs);
  1707. return $temp->value;
  1708. }
  1709. // if (m.length >> 1) + 2 <= m.length then m is too small and n can't be reduced
  1710. if ($m_length < 5) {
  1711. return self::_regularBarrett($n, $m);
  1712. }
  1713. // n = 2 * m.length
  1714. if (($key = array_search($m, $cache[self::VARIABLE])) === false) {
  1715. $key = count($cache[self::VARIABLE]);
  1716. $cache[self::VARIABLE][] = $m;
  1717. $lhs = new static();
  1718. $lhs_value = &$lhs->value;
  1719. $lhs_value = self::_array_repeat(0, $m_length + ($m_length >> 1));
  1720. $lhs_value[] = 1;
  1721. $rhs = new static();
  1722. $rhs->value = $m;
  1723. list($u, $m1) = $lhs->divide($rhs);
  1724. $u = $u->value;
  1725. $m1 = $m1->value;
  1726. $cache[self::DATA][] = array(
  1727. 'u' => $u, // m.length >> 1 (technically (m.length >> 1) + 1)
  1728. 'm1'=> $m1 // m.length
  1729. );
  1730. } else {
  1731. extract($cache[self::DATA][$key]);
  1732. }
  1733. $cutoff = $m_length + ($m_length >> 1);
  1734. $lsd = array_slice($n, 0, $cutoff); // m.length + (m.length >> 1)
  1735. $msd = array_slice($n, $cutoff); // m.length >> 1
  1736. $lsd = self::_trim($lsd);
  1737. $temp = self::_multiply($msd, false, $m1, false);
  1738. $n = self::_add($lsd, false, $temp[self::VALUE], false); // m.length + (m.length >> 1) + 1
  1739. if ($m_length & 1) {
  1740. return self::_regularBarrett($n[self::VALUE], $m);
  1741. }
  1742. // (m.length + (m.length >> 1) + 1) - (m.length - 1) == (m.length >> 1) + 2
  1743. $temp = array_slice($n[self::VALUE], $m_length - 1);
  1744. // if even: ((m.length >> 1) + 2) + (m.length >> 1) == m.length + 2
  1745. // if odd: ((m.length >> 1) + 2) + (m.length >> 1) == (m.length - 1) + 2 == m.length + 1
  1746. $temp = self::_multiply($temp, false, $u, false);
  1747. // if even: (m.length + 2) - ((m.length >> 1) + 1) = m.length - (m.length >> 1) + 1
  1748. // if odd: (m.length + 1) - ((m.length >> 1) + 1) = m.length - (m.length >> 1)
  1749. $temp = array_slice($temp[self::VALUE], ($m_length >> 1) + 1);
  1750. // if even: (m.length - (m.length >> 1) + 1) + m.length = 2 * m.length - (m.length >> 1) + 1
  1751. // if odd: (m.length - (m.length >> 1)) + m.length = 2 * m.length - (m.length >> 1)
  1752. $temp = self::_multiply($temp, false, $m, false);
  1753. // at this point, if m had an odd number of digits, we'd be subtracting a 2 * m.length - (m.length >> 1) digit
  1754. // number from a m.length + (m.length >> 1) + 1 digit number. ie. there'd be an extra digit and the while loop
  1755. // following this comment would loop a lot (hence our calling _regularBarrett() in that situation).
  1756. $result = self::_subtract($n[self::VALUE], false, $temp[self::VALUE], false);
  1757. while (self::_compare($result[self::VALUE], $result[self::SIGN], $m, false) >= 0) {
  1758. $result = self::_subtract($result[self::VALUE], $result[self::SIGN], $m, false);
  1759. }
  1760. return $result[self::VALUE];
  1761. }
  1762. /**
  1763. * (Regular) Barrett Modular Reduction
  1764. *
  1765. * For numbers with more than four digits BigInteger::_barrett() is faster. The difference between that and this
  1766. * is that this function does not fold the denominator into a smaller form.
  1767. *
  1768. * @see self::_slidingWindow()
  1769. * @access private
  1770. * @param array $x
  1771. * @param array $n
  1772. * @return array
  1773. */
  1774. private static function _regularBarrett($x, $n)
  1775. {
  1776. static $cache = array(
  1777. self::VARIABLE => array(),
  1778. self::DATA => array()
  1779. );
  1780. $n_length = count($n);
  1781. if (count($x) > 2 * $n_length) {
  1782. $lhs = new static();
  1783. $rhs = new static();
  1784. $lhs->value = $x;
  1785. $rhs->value = $n;
  1786. list(, $temp) = $lhs->divide($rhs);
  1787. return $temp->value;
  1788. }
  1789. if (($key = array_search($n, $cache[self::VARIABLE])) === false) {
  1790. $key = count($cache[self::VARIABLE]);
  1791. $cache[self::VARIABLE][] = $n;
  1792. $lhs = new static();
  1793. $lhs_value = &$lhs->value;
  1794. $lhs_value = self::_array_repeat(0, 2 * $n_length);
  1795. $lhs_value[] = 1;
  1796. $rhs = new static();
  1797. $rhs->value = $n;
  1798. list($temp, ) = $lhs->divide($rhs); // m.length
  1799. $cache[self::DATA][] = $temp->value;
  1800. }
  1801. // 2 * m.length - (m.length - 1) = m.length + 1
  1802. $temp = array_slice($x, $n_length - 1);
  1803. // (m.length + 1) + m.length = 2 * m.length + 1
  1804. $temp = self::_multiply($temp, false, $cache[self::DATA][$key], false);
  1805. // (2 * m.length + 1) - (m.length - 1) = m.length + 2
  1806. $temp = array_slice($temp[self::VALUE], $n_length + 1);
  1807. // m.length + 1
  1808. $result = array_slice($x, 0, $n_length + 1);
  1809. // m.length + 1
  1810. $temp = self::_multiplyLower($temp, false, $n, false, $n_length + 1);
  1811. // $temp == array_slice(self::_multiply($temp, false, $n, false)->value, 0, $n_length + 1)
  1812. if (self::_compare($result, false, $temp[self::VALUE], $temp[self::SIGN]) < 0) {
  1813. $corrector_value = self::_array_repeat(0, $n_length + 1);
  1814. $corrector_value[count($corrector_value)] = 1;
  1815. $result = self::_add($result, false, $corrector_value, false);
  1816. $result = $result[self::VALUE];
  1817. }
  1818. // at this point, we're subtracting a number with m.length + 1 digits from another number with m.length + 1 digits
  1819. $result = self::_subtract($result, false, $temp[self::VALUE], $temp[self::SIGN]);
  1820. while (self::_compare($result[self::VALUE], $result[self::SIGN], $n, false) > 0) {
  1821. $result = self::_subtract($result[self::VALUE], $result[self::SIGN], $n, false);
  1822. }
  1823. return $result[self::VALUE];
  1824. }
  1825. /**
  1826. * Performs long multiplication up to $stop digits
  1827. *
  1828. * If you're going to be doing array_slice($product->value, 0, $stop), some cycles can be saved.
  1829. *
  1830. * @see self::_regularBarrett()
  1831. * @param array $x_value
  1832. * @param bool $x_negative
  1833. * @param array $y_value
  1834. * @param bool $y_negative
  1835. * @param int $stop
  1836. * @return array
  1837. * @access private
  1838. */
  1839. private static function _multiplyLower($x_value, $x_negative, $y_value, $y_negative, $stop)
  1840. {
  1841. $x_length = count($x_value);
  1842. $y_length = count($y_value);
  1843. if (!$x_length || !$y_length) { // a 0 is being multiplied
  1844. return array(
  1845. self::VALUE => array(),
  1846. self::SIGN => false
  1847. );
  1848. }
  1849. if ($x_length < $y_length) {
  1850. $temp = $x_value;
  1851. $x_value = $y_value;
  1852. $y_value = $temp;
  1853. $x_length = count($x_value);
  1854. $y_length = count($y_value);
  1855. }
  1856. $product_value = self::_array_repeat(0, $x_length + $y_length);
  1857. // the following for loop could be removed if the for loop following it
  1858. // (the one with nested for loops) initially set $i to 0, but
  1859. // doing so would also make the result in one set of unnecessary adds,
  1860. // since on the outermost loops first pass, $product->value[$k] is going
  1861. // to always be 0
  1862. $carry = 0;
  1863. for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0, $k = $i
  1864. $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
  1865. $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1866. $product_value[$j] = (int) ($temp - self::$baseFull * $carry);
  1867. }
  1868. if ($j < $stop) {
  1869. $product_value[$j] = $carry;
  1870. }
  1871. // the above for loop is what the previous comment was talking about. the
  1872. // following for loop is the "one with nested for loops"
  1873. for ($i = 1; $i < $y_length; ++$i) {
  1874. $carry = 0;
  1875. for ($j = 0, $k = $i; $j < $x_length && $k < $stop; ++$j, ++$k) {
  1876. $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
  1877. $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1878. $product_value[$k] = (int) ($temp - self::$baseFull * $carry);
  1879. }
  1880. if ($k < $stop) {
  1881. $product_value[$k] = $carry;
  1882. }
  1883. }
  1884. return array(
  1885. self::VALUE => self::_trim($product_value),
  1886. self::SIGN => $x_negative != $y_negative
  1887. );
  1888. }
  1889. /**
  1890. * Montgomery Modular Reduction
  1891. *
  1892. * ($x->_prepMontgomery($n))->_montgomery($n) yields $x % $n.
  1893. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=170 MPM 6.3} provides insights on how this can be
  1894. * improved upon (basically, by using the comba method). gcd($n, 2) must be equal to one for this function
  1895. * to work correctly.
  1896. *
  1897. * @see self::_prepMontgomery()
  1898. * @see self::_slidingWindow()
  1899. * @access private
  1900. * @param array $x
  1901. * @param array $n
  1902. * @return array
  1903. */
  1904. private static function _montgomery($x, $n)
  1905. {
  1906. static $cache = array(
  1907. self::VARIABLE => array(),
  1908. self::DATA => array()
  1909. );
  1910. if (($key = array_search($n, $cache[self::VARIABLE])) === false) {
  1911. $key = count($cache[self::VARIABLE]);
  1912. $cache[self::VARIABLE][] = $x;
  1913. $cache[self::DATA][] = self::_modInverse67108864($n);
  1914. }
  1915. $k = count($n);
  1916. $result = array(self::VALUE => $x);
  1917. for ($i = 0; $i < $k; ++$i) {
  1918. $temp = $result[self::VALUE][$i] * $cache[self::DATA][$key];
  1919. $temp = $temp - self::$baseFull * (self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31));
  1920. $temp = self::_regularMultiply(array($temp), $n);
  1921. $temp = array_merge(self::_array_repeat(0, $i), $temp);
  1922. $result = self::_add($result[self::VALUE], false, $temp, false);
  1923. }
  1924. $result[self::VALUE] = array_slice($result[self::VALUE], $k);
  1925. if (self::_compare($result, false, $n, false) >= 0) {
  1926. $result = self::_subtract($result[self::VALUE], false, $n, false);
  1927. }
  1928. return $result[self::VALUE];
  1929. }
  1930. /**
  1931. * Montgomery Multiply
  1932. *
  1933. * Interleaves the montgomery reduction and long multiplication algorithms together as described in
  1934. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=13 HAC 14.36}
  1935. *
  1936. * @see self::_prepMontgomery()
  1937. * @see self::_montgomery()
  1938. * @access private
  1939. * @param array $x
  1940. * @param array $y
  1941. * @param array $m
  1942. * @return array
  1943. */
  1944. private static function _montgomeryMultiply($x, $y, $m)
  1945. {
  1946. $temp = self::_multiply($x, false, $y, false);
  1947. return self::_montgomery($temp[self::VALUE], $m);
  1948. // the following code, although not callable, can be run independently of the above code
  1949. // although the above code performed better in my benchmarks the following could might
  1950. // perform better under different circumstances. in lieu of deleting it it's just been
  1951. // made uncallable
  1952. static $cache = array(
  1953. self::VARIABLE => array(),
  1954. self::DATA => array()
  1955. );
  1956. if (($key = array_search($m, $cache[self::VARIABLE])) === false) {
  1957. $key = count($cache[self::VARIABLE]);
  1958. $cache[self::VARIABLE][] = $m;
  1959. $cache[self::DATA][] = self::_modInverse67108864($m);
  1960. }
  1961. $n = max(count($x), count($y), count($m));
  1962. $x = array_pad($x, $n, 0);
  1963. $y = array_pad($y, $n, 0);
  1964. $m = array_pad($m, $n, 0);
  1965. $a = array(self::VALUE => self::_array_repeat(0, $n + 1));
  1966. for ($i = 0; $i < $n; ++$i) {
  1967. $temp = $a[self::VALUE][0] + $x[$i] * $y[0];
  1968. $temp = $temp - self::$baseFull * (self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31));
  1969. $temp = $temp * $cache[self::DATA][$key];
  1970. $temp = $temp - self::$baseFull * (self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31));
  1971. $temp = self::_add(self::_regularMultiply(array($x[$i]), $y), false, self::_regularMultiply(array($temp), $m), false);
  1972. $a = self::_add($a[self::VALUE], false, $temp[self::VALUE], false);
  1973. $a[self::VALUE] = array_slice($a[self::VALUE], 1);
  1974. }
  1975. if (self::_compare($a[self::VALUE], false, $m, false) >= 0) {
  1976. $a = self::_subtract($a[self::VALUE], false, $m, false);
  1977. }
  1978. return $a[self::VALUE];
  1979. }
  1980. /**
  1981. * Prepare a number for use in Montgomery Modular Reductions
  1982. *
  1983. * @see self::_montgomery()
  1984. * @see self::_slidingWindow()
  1985. * @access private
  1986. * @param array $x
  1987. * @param array $n
  1988. * @return array
  1989. */
  1990. private static function _prepMontgomery($x, $n)
  1991. {
  1992. $lhs = new static();
  1993. $lhs->value = array_merge(self::_array_repeat(0, count($n)), $x);
  1994. $rhs = new static();
  1995. $rhs->value = $n;
  1996. list(, $temp) = $lhs->divide($rhs);
  1997. return $temp->value;
  1998. }
  1999. /**
  2000. * Modular Inverse of a number mod 2**26 (eg. 67108864)
  2001. *
  2002. * Based off of the bnpInvDigit function implemented and justified in the following URL:
  2003. *
  2004. * {@link http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js}
  2005. *
  2006. * The following URL provides more info:
  2007. *
  2008. * {@link http://groups.google.com/group/sci.crypt/msg/7a137205c1be7d85}
  2009. *
  2010. * As for why we do all the bitmasking... strange things can happen when converting from floats to ints. For
  2011. * instance, on some computers, var_dump((int) -4294967297) yields int(-1) and on others, it yields
  2012. * int(-2147483648). To avoid problems stemming from this, we use bitmasks to guarantee that ints aren't
  2013. * auto-converted to floats. The outermost bitmask is present because without it, there's no guarantee that
  2014. * the "residue" returned would be the so-called "common residue". We use fmod, in the last step, because the
  2015. * maximum possible $x is 26 bits and the maximum $result is 16 bits. Thus, we have to be able to handle up to
  2016. * 40 bits, which only 64-bit floating points will support.
  2017. *
  2018. * Thanks to Pedro Gimeno Fortea for input!
  2019. *
  2020. * @see self::_montgomery()
  2021. * @access private
  2022. * @param array $x
  2023. * @return int
  2024. */
  2025. private function _modInverse67108864($x) // 2**26 == 67,108,864
  2026. {
  2027. $x = -$x[0];
  2028. $result = $x & 0x3; // x**-1 mod 2**2
  2029. $result = ($result * (2 - $x * $result)) & 0xF; // x**-1 mod 2**4
  2030. $result = ($result * (2 - ($x & 0xFF) * $result)) & 0xFF; // x**-1 mod 2**8
  2031. $result = ($result * ((2 - ($x & 0xFFFF) * $result) & 0xFFFF)) & 0xFFFF; // x**-1 mod 2**16
  2032. $result = fmod($result * (2 - fmod($x * $result, self::$baseFull)), self::$baseFull); // x**-1 mod 2**26
  2033. return $result & self::$maxDigit;
  2034. }
  2035. /**
  2036. * Calculates modular inverses.
  2037. *
  2038. * Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses.
  2039. *
  2040. * Here's an example:
  2041. * <code>
  2042. * <?php
  2043. * $a = new \phpseclib\Math\BigInteger(30);
  2044. * $b = new \phpseclib\Math\BigInteger(17);
  2045. *
  2046. * $c = $a->modInverse($b);
  2047. * echo $c->toString(); // outputs 4
  2048. *
  2049. * echo "\r\n";
  2050. *
  2051. * $d = $a->multiply($c);
  2052. * list(, $d) = $d->divide($b);
  2053. * echo $d; // outputs 1 (as per the definition of modular inverse)
  2054. * ?>
  2055. * </code>
  2056. *
  2057. * @param \phpseclib\Math\BigInteger $n
  2058. * @return \phpseclib\Math\BigInteger|false
  2059. * @access public
  2060. * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=21 HAC 14.64} for more information.
  2061. */
  2062. public function modInverse($n)
  2063. {
  2064. switch (MATH_BIGINTEGER_MODE) {
  2065. case self::MODE_GMP:
  2066. $temp = new static();
  2067. $temp->value = gmp_invert($this->value, $n->value);
  2068. return ($temp->value === false) ? false : $this->_normalize($temp);
  2069. }
  2070. static $zero, $one;
  2071. if (!isset($zero)) {
  2072. $zero = new static();
  2073. $one = new static(1);
  2074. }
  2075. // $x mod -$n == $x mod $n.
  2076. $n = $n->abs();
  2077. if ($this->compare($zero) < 0) {
  2078. $temp = $this->abs();
  2079. $temp = $temp->modInverse($n);
  2080. return $this->_normalize($n->subtract($temp));
  2081. }
  2082. extract($this->extendedGCD($n));
  2083. if (!$gcd->equals($one)) {
  2084. return false;
  2085. }
  2086. $x = $x->compare($zero) < 0 ? $x->add($n) : $x;
  2087. return $this->compare($zero) < 0 ? $this->_normalize($n->subtract($x)) : $this->_normalize($x);
  2088. }
  2089. /**
  2090. * Calculates the greatest common divisor and Bezout's identity.
  2091. *
  2092. * Say you have 693 and 609. The GCD is 21. Bezout's identity states that there exist integers x and y such that
  2093. * 693*x + 609*y == 21. In point of fact, there are actually an infinite number of x and y combinations and which
  2094. * combination is returned is dependent upon which mode is in use. See
  2095. * {@link http://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity Bezout's identity - Wikipedia} for more information.
  2096. *
  2097. * Here's an example:
  2098. * <code>
  2099. * <?php
  2100. * $a = new \phpseclib\Math\BigInteger(693);
  2101. * $b = new \phpseclib\Math\BigInteger(609);
  2102. *
  2103. * extract($a->extendedGCD($b));
  2104. *
  2105. * echo $gcd->toString() . "\r\n"; // outputs 21
  2106. * echo $a->toString() * $x->toString() + $b->toString() * $y->toString(); // outputs 21
  2107. * ?>
  2108. * </code>
  2109. *
  2110. * @param \phpseclib\Math\BigInteger $n
  2111. * @return \phpseclib\Math\BigInteger
  2112. * @access public
  2113. * @internal Calculates the GCD using the binary xGCD algorithim described in
  2114. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=19 HAC 14.61}. As the text above 14.61 notes,
  2115. * the more traditional algorithim requires "relatively costly multiple-precision divisions".
  2116. */
  2117. public function extendedGCD($n)
  2118. {
  2119. switch (MATH_BIGINTEGER_MODE) {
  2120. case self::MODE_GMP:
  2121. extract(gmp_gcdext($this->value, $n->value));
  2122. return array(
  2123. 'gcd' => $this->_normalize(new static($g)),
  2124. 'x' => $this->_normalize(new static($s)),
  2125. 'y' => $this->_normalize(new static($t))
  2126. );
  2127. case self::MODE_BCMATH:
  2128. // it might be faster to use the binary xGCD algorithim here, as well, but (1) that algorithim works
  2129. // best when the base is a power of 2 and (2) i don't think it'd make much difference, anyway. as is,
  2130. // the basic extended euclidean algorithim is what we're using.
  2131. $u = $this->value;
  2132. $v = $n->value;
  2133. $a = '1';
  2134. $b = '0';
  2135. $c = '0';
  2136. $d = '1';
  2137. while (bccomp($v, '0', 0) != 0) {
  2138. $q = bcdiv($u, $v, 0);
  2139. $temp = $u;
  2140. $u = $v;
  2141. $v = bcsub($temp, bcmul($v, $q, 0), 0);
  2142. $temp = $a;
  2143. $a = $c;
  2144. $c = bcsub($temp, bcmul($a, $q, 0), 0);
  2145. $temp = $b;
  2146. $b = $d;
  2147. $d = bcsub($temp, bcmul($b, $q, 0), 0);
  2148. }
  2149. return array(
  2150. 'gcd' => $this->_normalize(new static($u)),
  2151. 'x' => $this->_normalize(new static($a)),
  2152. 'y' => $this->_normalize(new static($b))
  2153. );
  2154. }
  2155. $y = clone $n;
  2156. $x = clone $this;
  2157. $g = new static();
  2158. $g->value = array(1);
  2159. while (!(($x->value[0] & 1)|| ($y->value[0] & 1))) {
  2160. $x->_rshift(1);
  2161. $y->_rshift(1);
  2162. $g->_lshift(1);
  2163. }
  2164. $u = clone $x;
  2165. $v = clone $y;
  2166. $a = new static();
  2167. $b = new static();
  2168. $c = new static();
  2169. $d = new static();
  2170. $a->value = $d->value = $g->value = array(1);
  2171. $b->value = $c->value = array();
  2172. while (!empty($u->value)) {
  2173. while (!($u->value[0] & 1)) {
  2174. $u->_rshift(1);
  2175. if ((!empty($a->value) && ($a->value[0] & 1)) || (!empty($b->value) && ($b->value[0] & 1))) {
  2176. $a = $a->add($y);
  2177. $b = $b->subtract($x);
  2178. }
  2179. $a->_rshift(1);
  2180. $b->_rshift(1);
  2181. }
  2182. while (!($v->value[0] & 1)) {
  2183. $v->_rshift(1);
  2184. if ((!empty($d->value) && ($d->value[0] & 1)) || (!empty($c->value) && ($c->value[0] & 1))) {
  2185. $c = $c->add($y);
  2186. $d = $d->subtract($x);
  2187. }
  2188. $c->_rshift(1);
  2189. $d->_rshift(1);
  2190. }
  2191. if ($u->compare($v) >= 0) {
  2192. $u = $u->subtract($v);
  2193. $a = $a->subtract($c);
  2194. $b = $b->subtract($d);
  2195. } else {
  2196. $v = $v->subtract($u);
  2197. $c = $c->subtract($a);
  2198. $d = $d->subtract($b);
  2199. }
  2200. }
  2201. return array(
  2202. 'gcd' => $this->_normalize($g->multiply($v)),
  2203. 'x' => $this->_normalize($c),
  2204. 'y' => $this->_normalize($d)
  2205. );
  2206. }
  2207. /**
  2208. * Calculates the greatest common divisor
  2209. *
  2210. * Say you have 693 and 609. The GCD is 21.
  2211. *
  2212. * Here's an example:
  2213. * <code>
  2214. * <?php
  2215. * $a = new \phpseclib\Math\BigInteger(693);
  2216. * $b = new \phpseclib\Math\BigInteger(609);
  2217. *
  2218. * $gcd = a->extendedGCD($b);
  2219. *
  2220. * echo $gcd->toString() . "\r\n"; // outputs 21
  2221. * ?>
  2222. * </code>
  2223. *
  2224. * @param \phpseclib\Math\BigInteger $n
  2225. * @return \phpseclib\Math\BigInteger
  2226. * @access public
  2227. */
  2228. public function gcd($n)
  2229. {
  2230. extract($this->extendedGCD($n));
  2231. return $gcd;
  2232. }
  2233. /**
  2234. * Absolute value.
  2235. *
  2236. * @return \phpseclib\Math\BigInteger
  2237. * @access public
  2238. */
  2239. public function abs()
  2240. {
  2241. $temp = new static();
  2242. switch (MATH_BIGINTEGER_MODE) {
  2243. case self::MODE_GMP:
  2244. $temp->value = gmp_abs($this->value);
  2245. break;
  2246. case self::MODE_BCMATH:
  2247. $temp->value = (bccomp($this->value, '0', 0) < 0) ? substr($this->value, 1) : $this->value;
  2248. break;
  2249. default:
  2250. $temp->value = $this->value;
  2251. }
  2252. return $temp;
  2253. }
  2254. /**
  2255. * Compares two numbers.
  2256. *
  2257. * Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this is
  2258. * demonstrated thusly:
  2259. *
  2260. * $x > $y: $x->compare($y) > 0
  2261. * $x < $y: $x->compare($y) < 0
  2262. * $x == $y: $x->compare($y) == 0
  2263. *
  2264. * Note how the same comparison operator is used. If you want to test for equality, use $x->equals($y).
  2265. *
  2266. * @param \phpseclib\Math\BigInteger $y
  2267. * @return int < 0 if $this is less than $y; > 0 if $this is greater than $y, and 0 if they are equal.
  2268. * @access public
  2269. * @see self::equals()
  2270. * @internal Could return $this->subtract($x), but that's not as fast as what we do do.
  2271. */
  2272. public function compare($y)
  2273. {
  2274. switch (MATH_BIGINTEGER_MODE) {
  2275. case self::MODE_GMP:
  2276. return gmp_cmp($this->value, $y->value);
  2277. case self::MODE_BCMATH:
  2278. return bccomp($this->value, $y->value, 0);
  2279. }
  2280. return self::_compare($this->value, $this->is_negative, $y->value, $y->is_negative);
  2281. }
  2282. /**
  2283. * Compares two numbers.
  2284. *
  2285. * @param array $x_value
  2286. * @param bool $x_negative
  2287. * @param array $y_value
  2288. * @param bool $y_negative
  2289. * @return int
  2290. * @see self::compare()
  2291. * @access private
  2292. */
  2293. private static function _compare($x_value, $x_negative, $y_value, $y_negative)
  2294. {
  2295. if ($x_negative != $y_negative) {
  2296. return (!$x_negative && $y_negative) ? 1 : -1;
  2297. }
  2298. $result = $x_negative ? -1 : 1;
  2299. if (count($x_value) != count($y_value)) {
  2300. return (count($x_value) > count($y_value)) ? $result : -$result;
  2301. }
  2302. $size = max(count($x_value), count($y_value));
  2303. $x_value = array_pad($x_value, $size, 0);
  2304. $y_value = array_pad($y_value, $size, 0);
  2305. for ($i = count($x_value) - 1; $i >= 0; --$i) {
  2306. if ($x_value[$i] != $y_value[$i]) {
  2307. return ($x_value[$i] > $y_value[$i]) ? $result : -$result;
  2308. }
  2309. }
  2310. return 0;
  2311. }
  2312. /**
  2313. * Tests the equality of two numbers.
  2314. *
  2315. * If you need to see if one number is greater than or less than another number, use BigInteger::compare()
  2316. *
  2317. * @param \phpseclib\Math\BigInteger $x
  2318. * @return bool
  2319. * @access public
  2320. * @see self::compare()
  2321. */
  2322. public function equals($x)
  2323. {
  2324. switch (MATH_BIGINTEGER_MODE) {
  2325. case self::MODE_GMP:
  2326. return gmp_cmp($this->value, $x->value) == 0;
  2327. default:
  2328. return $this->value === $x->value && $this->is_negative == $x->is_negative;
  2329. }
  2330. }
  2331. /**
  2332. * Set Precision
  2333. *
  2334. * Some bitwise operations give different results depending on the precision being used. Examples include left
  2335. * shift, not, and rotates.
  2336. *
  2337. * @param int $bits
  2338. * @access public
  2339. */
  2340. public function setPrecision($bits)
  2341. {
  2342. if ($bits < 1) {
  2343. $this->precision = -1;
  2344. $this->bitmask = false;
  2345. return;
  2346. }
  2347. $this->precision = $bits;
  2348. if (MATH_BIGINTEGER_MODE != self::MODE_BCMATH) {
  2349. $this->bitmask = new static(chr((1 << ($bits & 0x7)) - 1) . str_repeat(chr(0xFF), $bits >> 3), 256);
  2350. } else {
  2351. $this->bitmask = new static(bcpow('2', $bits, 0));
  2352. }
  2353. $temp = $this->_normalize($this);
  2354. $this->value = $temp->value;
  2355. }
  2356. /**
  2357. * Get Precision
  2358. *
  2359. * @return int
  2360. * @see self::setPrecision()
  2361. * @access public
  2362. */
  2363. public function getPrecision()
  2364. {
  2365. return $this->precision;
  2366. }
  2367. /**
  2368. * Logical And
  2369. *
  2370. * @param \phpseclib\Math\BigInteger $x
  2371. * @access public
  2372. * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
  2373. * @return \phpseclib\Math\BigInteger
  2374. */
  2375. public function bitwise_and($x)
  2376. {
  2377. switch (MATH_BIGINTEGER_MODE) {
  2378. case self::MODE_GMP:
  2379. $temp = new static();
  2380. $temp->value = gmp_and($this->value, $x->value);
  2381. return $this->_normalize($temp);
  2382. case self::MODE_BCMATH:
  2383. $left = $this->toBytes();
  2384. $right = $x->toBytes();
  2385. $length = max(strlen($left), strlen($right));
  2386. $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
  2387. $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
  2388. return $this->_normalize(new static($left & $right, 256));
  2389. }
  2390. $result = clone $this;
  2391. $length = min(count($x->value), count($this->value));
  2392. $result->value = array_slice($result->value, 0, $length);
  2393. for ($i = 0; $i < $length; ++$i) {
  2394. $result->value[$i]&= $x->value[$i];
  2395. }
  2396. return $this->_normalize($result);
  2397. }
  2398. /**
  2399. * Logical Or
  2400. *
  2401. * @param \phpseclib\Math\BigInteger $x
  2402. * @access public
  2403. * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
  2404. * @return \phpseclib\Math\BigInteger
  2405. */
  2406. public function bitwise_or($x)
  2407. {
  2408. switch (MATH_BIGINTEGER_MODE) {
  2409. case self::MODE_GMP:
  2410. $temp = new static();
  2411. $temp->value = gmp_or($this->value, $x->value);
  2412. return $this->_normalize($temp);
  2413. case self::MODE_BCMATH:
  2414. $left = $this->toBytes();
  2415. $right = $x->toBytes();
  2416. $length = max(strlen($left), strlen($right));
  2417. $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
  2418. $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
  2419. return $this->_normalize(new static($left | $right, 256));
  2420. }
  2421. $length = max(count($this->value), count($x->value));
  2422. $result = clone $this;
  2423. $result->value = array_pad($result->value, $length, 0);
  2424. $x->value = array_pad($x->value, $length, 0);
  2425. for ($i = 0; $i < $length; ++$i) {
  2426. $result->value[$i]|= $x->value[$i];
  2427. }
  2428. return $this->_normalize($result);
  2429. }
  2430. /**
  2431. * Logical Exclusive-Or
  2432. *
  2433. * @param \phpseclib\Math\BigInteger $x
  2434. * @access public
  2435. * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
  2436. * @return \phpseclib\Math\BigInteger
  2437. */
  2438. public function bitwise_xor($x)
  2439. {
  2440. switch (MATH_BIGINTEGER_MODE) {
  2441. case self::MODE_GMP:
  2442. $temp = new static();
  2443. $temp->value = gmp_xor($this->value, $x->value);
  2444. return $this->_normalize($temp);
  2445. case self::MODE_BCMATH:
  2446. $left = $this->toBytes();
  2447. $right = $x->toBytes();
  2448. $length = max(strlen($left), strlen($right));
  2449. $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
  2450. $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
  2451. return $this->_normalize(new static($left ^ $right, 256));
  2452. }
  2453. $length = max(count($this->value), count($x->value));
  2454. $result = clone $this;
  2455. $result->value = array_pad($result->value, $length, 0);
  2456. $x->value = array_pad($x->value, $length, 0);
  2457. for ($i = 0; $i < $length; ++$i) {
  2458. $result->value[$i]^= $x->value[$i];
  2459. }
  2460. return $this->_normalize($result);
  2461. }
  2462. /**
  2463. * Logical Not
  2464. *
  2465. * @access public
  2466. * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
  2467. * @return \phpseclib\Math\BigInteger
  2468. */
  2469. public function bitwise_not()
  2470. {
  2471. // calculuate "not" without regard to $this->precision
  2472. // (will always result in a smaller number. ie. ~1 isn't 1111 1110 - it's 0)
  2473. $temp = $this->toBytes();
  2474. if ($temp == '') {
  2475. return '';
  2476. }
  2477. $pre_msb = decbin(ord($temp[0]));
  2478. $temp = ~$temp;
  2479. $msb = decbin(ord($temp[0]));
  2480. if (strlen($msb) == 8) {
  2481. $msb = substr($msb, strpos($msb, '0'));
  2482. }
  2483. $temp[0] = chr(bindec($msb));
  2484. // see if we need to add extra leading 1's
  2485. $current_bits = strlen($pre_msb) + 8 * strlen($temp) - 8;
  2486. $new_bits = $this->precision - $current_bits;
  2487. if ($new_bits <= 0) {
  2488. return $this->_normalize(new static($temp, 256));
  2489. }
  2490. // generate as many leading 1's as we need to.
  2491. $leading_ones = chr((1 << ($new_bits & 0x7)) - 1) . str_repeat(chr(0xFF), $new_bits >> 3);
  2492. self::_base256_lshift($leading_ones, $current_bits);
  2493. $temp = str_pad($temp, strlen($leading_ones), chr(0), STR_PAD_LEFT);
  2494. return $this->_normalize(new static($leading_ones | $temp, 256));
  2495. }
  2496. /**
  2497. * Logical Right Shift
  2498. *
  2499. * Shifts BigInteger's by $shift bits, effectively dividing by 2**$shift.
  2500. *
  2501. * @param int $shift
  2502. * @return \phpseclib\Math\BigInteger
  2503. * @access public
  2504. * @internal The only version that yields any speed increases is the internal version.
  2505. */
  2506. public function bitwise_rightShift($shift)
  2507. {
  2508. $temp = new static();
  2509. switch (MATH_BIGINTEGER_MODE) {
  2510. case self::MODE_GMP:
  2511. static $two;
  2512. if (!isset($two)) {
  2513. $two = gmp_init('2');
  2514. }
  2515. $temp->value = gmp_div_q($this->value, gmp_pow($two, $shift));
  2516. break;
  2517. case self::MODE_BCMATH:
  2518. $temp->value = bcdiv($this->value, bcpow('2', $shift, 0), 0);
  2519. break;
  2520. default: // could just replace _lshift with this, but then all _lshift() calls would need to be rewritten
  2521. // and I don't want to do that...
  2522. $temp->value = $this->value;
  2523. $temp->_rshift($shift);
  2524. }
  2525. return $this->_normalize($temp);
  2526. }
  2527. /**
  2528. * Logical Left Shift
  2529. *
  2530. * Shifts BigInteger's by $shift bits, effectively multiplying by 2**$shift.
  2531. *
  2532. * @param int $shift
  2533. * @return \phpseclib\Math\BigInteger
  2534. * @access public
  2535. * @internal The only version that yields any speed increases is the internal version.
  2536. */
  2537. public function bitwise_leftShift($shift)
  2538. {
  2539. $temp = new static();
  2540. switch (MATH_BIGINTEGER_MODE) {
  2541. case self::MODE_GMP:
  2542. static $two;
  2543. if (!isset($two)) {
  2544. $two = gmp_init('2');
  2545. }
  2546. $temp->value = gmp_mul($this->value, gmp_pow($two, $shift));
  2547. break;
  2548. case self::MODE_BCMATH:
  2549. $temp->value = bcmul($this->value, bcpow('2', $shift, 0), 0);
  2550. break;
  2551. default: // could just replace _rshift with this, but then all _lshift() calls would need to be rewritten
  2552. // and I don't want to do that...
  2553. $temp->value = $this->value;
  2554. $temp->_lshift($shift);
  2555. }
  2556. return $this->_normalize($temp);
  2557. }
  2558. /**
  2559. * Logical Left Rotate
  2560. *
  2561. * Instead of the top x bits being dropped they're appended to the shifted bit string.
  2562. *
  2563. * @param int $shift
  2564. * @return \phpseclib\Math\BigInteger
  2565. * @access public
  2566. */
  2567. public function bitwise_leftRotate($shift)
  2568. {
  2569. $bits = $this->toBytes();
  2570. if ($this->precision > 0) {
  2571. $precision = $this->precision;
  2572. if (MATH_BIGINTEGER_MODE == self::MODE_BCMATH) {
  2573. $mask = $this->bitmask->subtract(new static(1));
  2574. $mask = $mask->toBytes();
  2575. } else {
  2576. $mask = $this->bitmask->toBytes();
  2577. }
  2578. } else {
  2579. $temp = ord($bits[0]);
  2580. for ($i = 0; $temp >> $i; ++$i) {
  2581. }
  2582. $precision = 8 * strlen($bits) - 8 + $i;
  2583. $mask = chr((1 << ($precision & 0x7)) - 1) . str_repeat(chr(0xFF), $precision >> 3);
  2584. }
  2585. if ($shift < 0) {
  2586. $shift+= $precision;
  2587. }
  2588. $shift%= $precision;
  2589. if (!$shift) {
  2590. return clone $this;
  2591. }
  2592. $left = $this->bitwise_leftShift($shift);
  2593. $left = $left->bitwise_and(new static($mask, 256));
  2594. $right = $this->bitwise_rightShift($precision - $shift);
  2595. $result = MATH_BIGINTEGER_MODE != self::MODE_BCMATH ? $left->bitwise_or($right) : $left->add($right);
  2596. return $this->_normalize($result);
  2597. }
  2598. /**
  2599. * Logical Right Rotate
  2600. *
  2601. * Instead of the bottom x bits being dropped they're prepended to the shifted bit string.
  2602. *
  2603. * @param int $shift
  2604. * @return \phpseclib\Math\BigInteger
  2605. * @access public
  2606. */
  2607. public function bitwise_rightRotate($shift)
  2608. {
  2609. return $this->bitwise_leftRotate(-$shift);
  2610. }
  2611. /**
  2612. * Returns the smallest and largest n-bit number
  2613. *
  2614. * @param int $bits
  2615. * @return \phpseclib\Math\BigInteger
  2616. * @access public
  2617. */
  2618. public static function minMaxBits($bits)
  2619. {
  2620. $bytes = $bits >> 3;
  2621. $min = str_repeat(chr(0), $bytes);
  2622. $max = str_repeat(chr(0xFF), $bytes);
  2623. $msb = $bits & 7;
  2624. if ($msb) {
  2625. $min = chr(1 << ($msb - 1)) . $min;
  2626. $max = chr((1 << $msb) - 1) . $max;
  2627. } else {
  2628. $min[0] = chr(0x80);
  2629. }
  2630. return array(
  2631. 'min' => new static($min, 256),
  2632. 'max' => new static($max, 256)
  2633. );
  2634. }
  2635. /**
  2636. * Generates a random number of a certain size
  2637. *
  2638. * Bit length is equal to $size.
  2639. *
  2640. * @param int $size
  2641. * @return \phpseclib\Math\BigInteger
  2642. * @access public
  2643. */
  2644. public static function random($size)
  2645. {
  2646. extract(self::minMaxBits($size));
  2647. return self::randomRange($min, $max);
  2648. }
  2649. /**
  2650. * Generate a random number between a range
  2651. *
  2652. * Returns a random number between $min and $max where $min and $max
  2653. * can be defined using one of the two methods:
  2654. *
  2655. * BigInteger::randomRange($min, $max)
  2656. * BigInteger::randomRange($max, $min)
  2657. *
  2658. * @param \phpseclib\Math\BigInteger $arg1
  2659. * @param \phpseclib\Math\BigInteger $arg2
  2660. * @return \phpseclib\Math\BigInteger
  2661. * @access public
  2662. * @param \phpseclib\Math\BigInteger $min
  2663. * @param \phpseclib\Math\BigInteger $max
  2664. */
  2665. public static function randomRange($min, $max)
  2666. {
  2667. $compare = $max->compare($min);
  2668. if (!$compare) {
  2669. return $min;
  2670. } elseif ($compare < 0) {
  2671. // if $min is bigger then $max, swap $min and $max
  2672. $temp = $max;
  2673. $max = $min;
  2674. $min = $temp;
  2675. }
  2676. static $one;
  2677. if (!isset($one)) {
  2678. $one = new static(1);
  2679. }
  2680. $max = $max->subtract($min->subtract($one));
  2681. $size = strlen(ltrim($max->toBytes(), chr(0)));
  2682. /*
  2683. doing $random % $max doesn't work because some numbers will be more likely to occur than others.
  2684. eg. if $max is 140 and $random's max is 255 then that'd mean both $random = 5 and $random = 145
  2685. would produce 5 whereas the only value of random that could produce 139 would be 139. ie.
  2686. not all numbers would be equally likely. some would be more likely than others.
  2687. creating a whole new random number until you find one that is within the range doesn't work
  2688. because, for sufficiently small ranges, the likelihood that you'd get a number within that range
  2689. would be pretty small. eg. with $random's max being 255 and if your $max being 1 the probability
  2690. would be pretty high that $random would be greater than $max.
  2691. phpseclib works around this using the technique described here:
  2692. http://crypto.stackexchange.com/questions/5708/creating-a-small-number-from-a-cryptographically-secure-random-string
  2693. */
  2694. $random_max = new static(chr(1) . str_repeat("\0", $size), 256);
  2695. $random = new static(Random::string($size), 256);
  2696. list($max_multiple) = $random_max->divide($max);
  2697. $max_multiple = $max_multiple->multiply($max);
  2698. while ($random->compare($max_multiple) >= 0) {
  2699. $random = $random->subtract($max_multiple);
  2700. $random_max = $random_max->subtract($max_multiple);
  2701. $random = $random->bitwise_leftShift(8);
  2702. $random = $random->add(new static(Random::string(1), 256));
  2703. $random_max = $random_max->bitwise_leftShift(8);
  2704. list($max_multiple) = $random_max->divide($max);
  2705. $max_multiple = $max_multiple->multiply($max);
  2706. }
  2707. list(, $random) = $random->divide($max);
  2708. return $random->add($min);
  2709. }
  2710. /**
  2711. * Generates a random prime number of a certain size
  2712. *
  2713. * Bit length is equal to $size
  2714. *
  2715. * @param int $size
  2716. * @return \phpseclib\Math\BigInteger
  2717. * @access public
  2718. */
  2719. public static function randomPrime($size)
  2720. {
  2721. extract(self::minMaxBits($size));
  2722. return self::randomRangePrime($min, $max);
  2723. }
  2724. /**
  2725. * Generate a random prime number between a range
  2726. *
  2727. * If there's not a prime within the given range, false will be returned.
  2728. *
  2729. * @param \phpseclib\Math\BigInteger $min
  2730. * @param \phpseclib\Math\BigInteger $max
  2731. * @return Math_BigInteger|false
  2732. * @access public
  2733. * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}.
  2734. */
  2735. public static function randomRangePrime($min, $max)
  2736. {
  2737. $compare = $max->compare($min);
  2738. if (!$compare) {
  2739. return $min->isPrime() ? $min : false;
  2740. } elseif ($compare < 0) {
  2741. // if $min is bigger then $max, swap $min and $max
  2742. $temp = $max;
  2743. $max = $min;
  2744. $min = $temp;
  2745. }
  2746. static $one, $two;
  2747. if (!isset($one)) {
  2748. $one = new static(1);
  2749. $two = new static(2);
  2750. }
  2751. $x = self::randomRange($min, $max);
  2752. // gmp_nextprime() requires PHP 5 >= 5.2.0 per <http://php.net/gmp-nextprime>.
  2753. if (MATH_BIGINTEGER_MODE == self::MODE_GMP && extension_loaded('gmp')) {
  2754. $p = new static();
  2755. $p->value = gmp_nextprime($x->value);
  2756. if ($p->compare($max) <= 0) {
  2757. return $p;
  2758. }
  2759. if (!$min->equals($x)) {
  2760. $x = $x->subtract($one);
  2761. }
  2762. return self::randomRangePrime($min, $x);
  2763. }
  2764. if ($x->equals($two)) {
  2765. return $x;
  2766. }
  2767. $x->_make_odd();
  2768. if ($x->compare($max) > 0) {
  2769. // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range
  2770. if ($min->equals($max)) {
  2771. return false;
  2772. }
  2773. $x = clone $min;
  2774. $x->_make_odd();
  2775. }
  2776. $initial_x = clone $x;
  2777. while (true) {
  2778. if ($x->isPrime()) {
  2779. return $x;
  2780. }
  2781. $x = $x->add($two);
  2782. if ($x->compare($max) > 0) {
  2783. $x = clone $min;
  2784. if ($x->equals($two)) {
  2785. return $x;
  2786. }
  2787. $x->_make_odd();
  2788. }
  2789. if ($x->equals($initial_x)) {
  2790. return false;
  2791. }
  2792. }
  2793. }
  2794. /**
  2795. * Make the current number odd
  2796. *
  2797. * If the current number is odd it'll be unchanged. If it's even, one will be added to it.
  2798. *
  2799. * @see self::randomPrime()
  2800. * @access private
  2801. */
  2802. private function _make_odd()
  2803. {
  2804. switch (MATH_BIGINTEGER_MODE) {
  2805. case self::MODE_GMP:
  2806. gmp_setbit($this->value, 0);
  2807. break;
  2808. case self::MODE_BCMATH:
  2809. if ($this->value[strlen($this->value) - 1] % 2 == 0) {
  2810. $this->value = bcadd($this->value, '1');
  2811. }
  2812. break;
  2813. default:
  2814. $this->value[0] |= 1;
  2815. }
  2816. }
  2817. /**
  2818. * Checks a numer to see if it's prime
  2819. *
  2820. * Assuming the $t parameter is not set, this function has an error rate of 2**-80. The main motivation for the
  2821. * $t parameter is distributability. BigInteger::randomPrime() can be distributed across multiple pageloads
  2822. * on a website instead of just one.
  2823. *
  2824. * @param \phpseclib\Math\BigInteger $t
  2825. * @return bool
  2826. * @access public
  2827. * @internal Uses the
  2828. * {@link http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test Miller-Rabin primality test}. See
  2829. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=8 HAC 4.24}.
  2830. */
  2831. public function isPrime($t = false)
  2832. {
  2833. $length = strlen($this->toBytes());
  2834. if (!$t) {
  2835. // see HAC 4.49 "Note (controlling the error probability)"
  2836. // @codingStandardsIgnoreStart
  2837. if ($length >= 163) { $t = 2; } // floor(1300 / 8)
  2838. else if ($length >= 106) { $t = 3; } // floor( 850 / 8)
  2839. else if ($length >= 81 ) { $t = 4; } // floor( 650 / 8)
  2840. else if ($length >= 68 ) { $t = 5; } // floor( 550 / 8)
  2841. else if ($length >= 56 ) { $t = 6; } // floor( 450 / 8)
  2842. else if ($length >= 50 ) { $t = 7; } // floor( 400 / 8)
  2843. else if ($length >= 43 ) { $t = 8; } // floor( 350 / 8)
  2844. else if ($length >= 37 ) { $t = 9; } // floor( 300 / 8)
  2845. else if ($length >= 31 ) { $t = 12; } // floor( 250 / 8)
  2846. else if ($length >= 25 ) { $t = 15; } // floor( 200 / 8)
  2847. else if ($length >= 18 ) { $t = 18; } // floor( 150 / 8)
  2848. else { $t = 27; }
  2849. // @codingStandardsIgnoreEnd
  2850. }
  2851. // ie. gmp_testbit($this, 0)
  2852. // ie. isEven() or !isOdd()
  2853. switch (MATH_BIGINTEGER_MODE) {
  2854. case self::MODE_GMP:
  2855. return gmp_prob_prime($this->value, $t) != 0;
  2856. case self::MODE_BCMATH:
  2857. if ($this->value === '2') {
  2858. return true;
  2859. }
  2860. if ($this->value[strlen($this->value) - 1] % 2 == 0) {
  2861. return false;
  2862. }
  2863. break;
  2864. default:
  2865. if ($this->value == array(2)) {
  2866. return true;
  2867. }
  2868. if (~$this->value[0] & 1) {
  2869. return false;
  2870. }
  2871. }
  2872. static $primes, $zero, $one, $two;
  2873. if (!isset($primes)) {
  2874. $primes = array(
  2875. 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
  2876. 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
  2877. 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227,
  2878. 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
  2879. 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
  2880. 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509,
  2881. 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617,
  2882. 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727,
  2883. 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829,
  2884. 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947,
  2885. 953, 967, 971, 977, 983, 991, 997
  2886. );
  2887. if (MATH_BIGINTEGER_MODE != self::MODE_INTERNAL) {
  2888. for ($i = 0; $i < count($primes); ++$i) {
  2889. $primes[$i] = new static($primes[$i]);
  2890. }
  2891. }
  2892. $zero = new static();
  2893. $one = new static(1);
  2894. $two = new static(2);
  2895. }
  2896. if ($this->equals($one)) {
  2897. return false;
  2898. }
  2899. // see HAC 4.4.1 "Random search for probable primes"
  2900. if (MATH_BIGINTEGER_MODE != self::MODE_INTERNAL) {
  2901. foreach ($primes as $prime) {
  2902. list(, $r) = $this->divide($prime);
  2903. if ($r->equals($zero)) {
  2904. return $this->equals($prime);
  2905. }
  2906. }
  2907. } else {
  2908. $value = $this->value;
  2909. foreach ($primes as $prime) {
  2910. list(, $r) = self::_divide_digit($value, $prime);
  2911. if (!$r) {
  2912. return count($value) == 1 && $value[0] == $prime;
  2913. }
  2914. }
  2915. }
  2916. $n = clone $this;
  2917. $n_1 = $n->subtract($one);
  2918. $n_2 = $n->subtract($two);
  2919. $r = clone $n_1;
  2920. $r_value = $r->value;
  2921. // ie. $s = gmp_scan1($n, 0) and $r = gmp_div_q($n, gmp_pow(gmp_init('2'), $s));
  2922. if (MATH_BIGINTEGER_MODE == self::MODE_BCMATH) {
  2923. $s = 0;
  2924. // if $n was 1, $r would be 0 and this would be an infinite loop, hence our $this->equals($one) check earlier
  2925. while ($r->value[strlen($r->value) - 1] % 2 == 0) {
  2926. $r->value = bcdiv($r->value, '2', 0);
  2927. ++$s;
  2928. }
  2929. } else {
  2930. for ($i = 0, $r_length = count($r_value); $i < $r_length; ++$i) {
  2931. $temp = ~$r_value[$i] & 0xFFFFFF;
  2932. for ($j = 1; ($temp >> $j) & 1; ++$j) {
  2933. }
  2934. if ($j != 25) {
  2935. break;
  2936. }
  2937. }
  2938. $s = 26 * $i + $j - 1;
  2939. $r->_rshift($s);
  2940. }
  2941. for ($i = 0; $i < $t; ++$i) {
  2942. $a = self::randomRange($two, $n_2);
  2943. $y = $a->modPow($r, $n);
  2944. if (!$y->equals($one) && !$y->equals($n_1)) {
  2945. for ($j = 1; $j < $s && !$y->equals($n_1); ++$j) {
  2946. $y = $y->modPow($two, $n);
  2947. if ($y->equals($one)) {
  2948. return false;
  2949. }
  2950. }
  2951. if (!$y->equals($n_1)) {
  2952. return false;
  2953. }
  2954. }
  2955. }
  2956. return true;
  2957. }
  2958. /**
  2959. * Logical Left Shift
  2960. *
  2961. * Shifts BigInteger's by $shift bits.
  2962. *
  2963. * @param int $shift
  2964. * @access private
  2965. */
  2966. private function _lshift($shift)
  2967. {
  2968. if ($shift == 0) {
  2969. return;
  2970. }
  2971. $num_digits = (int) ($shift / self::$base);
  2972. $shift %= self::$base;
  2973. $shift = 1 << $shift;
  2974. $carry = 0;
  2975. for ($i = 0; $i < count($this->value); ++$i) {
  2976. $temp = $this->value[$i] * $shift + $carry;
  2977. $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  2978. $this->value[$i] = (int) ($temp - $carry * self::$baseFull);
  2979. }
  2980. if ($carry) {
  2981. $this->value[count($this->value)] = $carry;
  2982. }
  2983. while ($num_digits--) {
  2984. array_unshift($this->value, 0);
  2985. }
  2986. }
  2987. /**
  2988. * Logical Right Shift
  2989. *
  2990. * Shifts BigInteger's by $shift bits.
  2991. *
  2992. * @param int $shift
  2993. * @access private
  2994. */
  2995. private function _rshift($shift)
  2996. {
  2997. if ($shift == 0) {
  2998. return;
  2999. }
  3000. $num_digits = (int) ($shift / self::$base);
  3001. $shift %= self::$base;
  3002. $carry_shift = self::$base - $shift;
  3003. $carry_mask = (1 << $shift) - 1;
  3004. if ($num_digits) {
  3005. $this->value = array_slice($this->value, $num_digits);
  3006. }
  3007. $carry = 0;
  3008. for ($i = count($this->value) - 1; $i >= 0; --$i) {
  3009. $temp = $this->value[$i] >> $shift | $carry;
  3010. $carry = ($this->value[$i] & $carry_mask) << $carry_shift;
  3011. $this->value[$i] = $temp;
  3012. }
  3013. $this->value = $this->_trim($this->value);
  3014. }
  3015. /**
  3016. * Normalize
  3017. *
  3018. * Removes leading zeros and truncates (if necessary) to maintain the appropriate precision
  3019. *
  3020. * @param \phpseclib\Math\BigInteger
  3021. * @return \phpseclib\Math\BigInteger
  3022. * @see self::_trim()
  3023. * @access private
  3024. */
  3025. private function _normalize($result)
  3026. {
  3027. $result->precision = $this->precision;
  3028. $result->bitmask = $this->bitmask;
  3029. switch (MATH_BIGINTEGER_MODE) {
  3030. case self::MODE_GMP:
  3031. if ($this->bitmask !== false) {
  3032. $result->value = gmp_and($result->value, $result->bitmask->value);
  3033. }
  3034. return $result;
  3035. case self::MODE_BCMATH:
  3036. if (!empty($result->bitmask->value)) {
  3037. $result->value = bcmod($result->value, $result->bitmask->value);
  3038. }
  3039. return $result;
  3040. }
  3041. $value = &$result->value;
  3042. if (!count($value)) {
  3043. return $result;
  3044. }
  3045. $value = $this->_trim($value);
  3046. if (!empty($result->bitmask->value)) {
  3047. $length = min(count($value), count($this->bitmask->value));
  3048. $value = array_slice($value, 0, $length);
  3049. for ($i = 0; $i < $length; ++$i) {
  3050. $value[$i] = $value[$i] & $this->bitmask->value[$i];
  3051. }
  3052. }
  3053. return $result;
  3054. }
  3055. /**
  3056. * Trim
  3057. *
  3058. * Removes leading zeros
  3059. *
  3060. * @param array $value
  3061. * @return \phpseclib\Math\BigInteger
  3062. * @access private
  3063. */
  3064. private static function _trim($value)
  3065. {
  3066. for ($i = count($value) - 1; $i >= 0; --$i) {
  3067. if ($value[$i]) {
  3068. break;
  3069. }
  3070. unset($value[$i]);
  3071. }
  3072. return $value;
  3073. }
  3074. /**
  3075. * Array Repeat
  3076. *
  3077. * @param $input Array
  3078. * @param $multiplier mixed
  3079. * @return array
  3080. * @access private
  3081. */
  3082. private static function _array_repeat($input, $multiplier)
  3083. {
  3084. return ($multiplier) ? array_fill(0, $multiplier, $input) : array();
  3085. }
  3086. /**
  3087. * Logical Left Shift
  3088. *
  3089. * Shifts binary strings $shift bits, essentially multiplying by 2**$shift.
  3090. *
  3091. * @param $x String
  3092. * @param $shift Integer
  3093. * @return string
  3094. * @access private
  3095. */
  3096. private static function _base256_lshift(&$x, $shift)
  3097. {
  3098. if ($shift == 0) {
  3099. return;
  3100. }
  3101. $num_bytes = $shift >> 3; // eg. floor($shift/8)
  3102. $shift &= 7; // eg. $shift % 8
  3103. $carry = 0;
  3104. for ($i = strlen($x) - 1; $i >= 0; --$i) {
  3105. $temp = ord($x[$i]) << $shift | $carry;
  3106. $x[$i] = chr($temp);
  3107. $carry = $temp >> 8;
  3108. }
  3109. $carry = ($carry != 0) ? chr($carry) : '';
  3110. $x = $carry . $x . str_repeat(chr(0), $num_bytes);
  3111. }
  3112. /**
  3113. * Logical Right Shift
  3114. *
  3115. * Shifts binary strings $shift bits, essentially dividing by 2**$shift and returning the remainder.
  3116. *
  3117. * @param $x String
  3118. * @param $shift Integer
  3119. * @return string
  3120. * @access private
  3121. */
  3122. private static function _base256_rshift(&$x, $shift)
  3123. {
  3124. if ($shift == 0) {
  3125. $x = ltrim($x, chr(0));
  3126. return '';
  3127. }
  3128. $num_bytes = $shift >> 3; // eg. floor($shift/8)
  3129. $shift &= 7; // eg. $shift % 8
  3130. $remainder = '';
  3131. if ($num_bytes) {
  3132. $start = $num_bytes > strlen($x) ? -strlen($x) : -$num_bytes;
  3133. $remainder = substr($x, $start);
  3134. $x = substr($x, 0, -$num_bytes);
  3135. }
  3136. $carry = 0;
  3137. $carry_shift = 8 - $shift;
  3138. for ($i = 0; $i < strlen($x); ++$i) {
  3139. $temp = (ord($x[$i]) >> $shift) | $carry;
  3140. $carry = (ord($x[$i]) << $carry_shift) & 0xFF;
  3141. $x[$i] = chr($temp);
  3142. }
  3143. $x = ltrim($x, chr(0));
  3144. $remainder = chr($carry >> $carry_shift) . $remainder;
  3145. return ltrim($remainder, chr(0));
  3146. }
  3147. // one quirk about how the following functions are implemented is that PHP defines N to be an unsigned long
  3148. // at 32-bits, while java's longs are 64-bits.
  3149. /**
  3150. * Converts 32-bit integers to bytes.
  3151. *
  3152. * @param int $x
  3153. * @return string
  3154. * @access private
  3155. */
  3156. private static function _int2bytes($x)
  3157. {
  3158. return ltrim(pack('N', $x), chr(0));
  3159. }
  3160. /**
  3161. * Converts bytes to 32-bit integers
  3162. *
  3163. * @param string $x
  3164. * @return int
  3165. * @access private
  3166. */
  3167. private static function _bytes2int($x)
  3168. {
  3169. $temp = unpack('Nint', str_pad($x, 4, chr(0), STR_PAD_LEFT));
  3170. return $temp['int'];
  3171. }
  3172. /**
  3173. * Single digit division
  3174. *
  3175. * Even if int64 is being used the division operator will return a float64 value
  3176. * if the dividend is not evenly divisible by the divisor. Since a float64 doesn't
  3177. * have the precision of int64 this is a problem so, when int64 is being used,
  3178. * we'll guarantee that the dividend is divisible by first subtracting the remainder.
  3179. *
  3180. * @access private
  3181. * @param int $x
  3182. * @param int $y
  3183. * @return int
  3184. */
  3185. private static function _safe_divide($x, $y)
  3186. {
  3187. if (self::$base === 26) {
  3188. return (int) ($x / $y);
  3189. }
  3190. // self::$base === 31
  3191. return ($x - ($x % $y)) / $y;
  3192. }
  3193. /**
  3194. * Calculates the nth root of a biginteger.
  3195. *
  3196. * Returns the nth root of a positive biginteger, where n defaults to 2
  3197. *
  3198. * Here's an example:
  3199. * <code>
  3200. * <?php
  3201. * $a = new \phpseclib\Math\BigInteger('625');
  3202. *
  3203. * $root = $a->root();
  3204. *
  3205. * echo $root->toString(); // outputs 25
  3206. * ?>
  3207. * </code>
  3208. *
  3209. * @param \phpseclib\Math\BigInteger $n
  3210. * @access public
  3211. * @return \phpseclib\Math\BigInteger
  3212. * @internal This function is based off of {@link http://mathforum.org/library/drmath/view/52605.html this page} and {@link http://stackoverflow.com/questions/11242920/calculating-nth-root-with-bcmath-in-php this stackoverflow question}.
  3213. */
  3214. public function root($n = null)
  3215. {
  3216. static $zero, $one, $two;
  3217. if (!isset($one)) {
  3218. $zero = new static(0);
  3219. $one = new static(1);
  3220. $two = new static(2);
  3221. }
  3222. if ($n === null) {
  3223. $n = $two;
  3224. }
  3225. if ($n->compare($one) == -1) {
  3226. return $zero;
  3227. } // we want positive exponents
  3228. if ($this->compare($one) == -1) {
  3229. return new static(0);
  3230. } // we want positive numbers
  3231. if ($this->compare($two) == -1) {
  3232. return $one;
  3233. } // n-th root of 1 or 2 is 1
  3234. $root = new static();
  3235. if (MATH_BIGINTEGER_MODE == self::MODE_GMP && function_exists('gmp_root')) {
  3236. $root->value = gmp_root($this->value, gmp_intval($n->value));
  3237. return $this->_normalize($root);
  3238. }
  3239. // g is our guess number
  3240. $g = $two;
  3241. // while (g^n < num) g=g*2
  3242. while ($g->pow($n)->compare($this) == -1) {
  3243. $g = $g->multiply($two);
  3244. }
  3245. // if (g^n==num) num is a power of 2, we're lucky, end of job
  3246. // == 0 bccomp(bcpow($g,$n), $n->value)==0
  3247. if ($g->pow($n)->equals($this)) {
  3248. $root = $g;
  3249. return $this->_normalize($root);
  3250. }
  3251. // if we're here num wasn't a power of 2 :(
  3252. $og = $g; // og means original guess and here is our upper bound
  3253. $g = $g->divide($two); // g is set to be our lower bound
  3254. $g = $g[0]; // g is set to be our lower bound
  3255. $step = $og->subtract($g)->divide($two); // step is the half of upper bound - lower bound
  3256. $step = $step[0]; // step is the half of upper bound - lower bound
  3257. $g = $g->add($step); // we start at lower bound + step , basically in the middle of our interval
  3258. // while step>1
  3259. while ($step->compare($one) == 1) {
  3260. $guess = $g->pow($n);
  3261. $step = $step->divide($two);
  3262. $step = $step[0];
  3263. $comp = $guess->compare($this); // compare our guess with real number
  3264. switch ($comp) {
  3265. case -1: // if guess is lower we add the new step
  3266. $g = $g->add($step);
  3267. break;
  3268. case 1: // if guess is higher we sub the new step
  3269. $g = $g->subtract($step);
  3270. break;
  3271. case 0: // if guess is exactly the num we're done, we return the value
  3272. $root = $g;
  3273. break 2;
  3274. }
  3275. }
  3276. if ($comp == 1) {
  3277. $g = $g->subtract($step);
  3278. }
  3279. // whatever happened, g is the closest guess we can make so return it
  3280. $root = $g;
  3281. return $this->_normalize($root);
  3282. }
  3283. /**
  3284. * Performs exponentiation.
  3285. *
  3286. * @param \phpseclib\Math\BigInteger $n
  3287. * @access public
  3288. * @return \phpseclib\Math\BigInteger
  3289. */
  3290. public function pow($n)
  3291. {
  3292. $zero = new static(0);
  3293. if ($n->compare($zero) == 0) {
  3294. return new static(1);
  3295. } // n^0 = 1
  3296. $res = new static();
  3297. switch (MATH_BIGINTEGER_MODE) {
  3298. case self::MODE_GMP:
  3299. $res->value = gmp_pow($this->value, gmp_intval($n->value));
  3300. return $this->_normalize($res);
  3301. case self::MODE_BCMATH:
  3302. $res->value = bcpow($this->value, $n->value);
  3303. return $this->_normalize($res);
  3304. default:
  3305. $one = new static(1);
  3306. $res = $this;
  3307. while (!$n->equals($one)) {
  3308. $res = $res->multiply($this);
  3309. $n = $n->subtract($one);
  3310. }
  3311. return $res;
  3312. }
  3313. }
  3314. /**
  3315. * Return the minimum BigInteger between an arbitrary number of BigIntegers.
  3316. *
  3317. * @param \phpseclib\Math\BigInteger ...$param
  3318. * @access public
  3319. * @return \phpseclib\Math\BigInteger
  3320. */
  3321. public static function min()
  3322. {
  3323. $args = func_get_args();
  3324. if (count($args) == 1) {
  3325. return $args[0];
  3326. }
  3327. $min = $args[0];
  3328. for ($i = 1; $i < count($args); $i++) {
  3329. $min = $min->compare($args[$i]) > 0 ? $args[$i] : $min;
  3330. }
  3331. return $min;
  3332. }
  3333. /**
  3334. * Return the maximum BigInteger between an arbitrary number of BigIntegers.
  3335. *
  3336. * @param \phpseclib\Math\BigInteger ...$param
  3337. * @access public
  3338. * @return \phpseclib\Math\BigInteger
  3339. */
  3340. public static function max()
  3341. {
  3342. $args = func_get_args();
  3343. if (count($args) == 1) {
  3344. return $args[0];
  3345. }
  3346. $max = $args[0];
  3347. for ($i = 1; $i < count($args); $i++) {
  3348. $max = $max->compare($args[$i]) < 0 ? $args[$i] : $max;
  3349. }
  3350. return $max;
  3351. }
  3352. /**
  3353. * Return the size of a BigInteger in bits
  3354. *
  3355. * @access public
  3356. * @return int
  3357. */
  3358. public function getLength()
  3359. {
  3360. return strlen($this->toBits());
  3361. }
  3362. /**
  3363. * Return the size of a BigInteger in bytes
  3364. *
  3365. * @access public
  3366. * @return int
  3367. */
  3368. public function getLengthInBytes()
  3369. {
  3370. return strlen($this->toBytes());
  3371. }
  3372. /**
  3373. * Tests BigInteger to see if it is between two integers, inclusive
  3374. *
  3375. * @param \phpseclib\Math\BigInteger $min
  3376. * @param \phpseclib\Math\BigInteger $max
  3377. * @access public
  3378. * @return boolean
  3379. */
  3380. function between($min, $max)
  3381. {
  3382. return $this->compare($min) >= 0 && $this->compare($max) <= 0;
  3383. }
  3384. }