MathBigInteger.php 135 KB

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