Math_BigInteger.php 135 KB

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