BigInteger.php 119 KB

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