BigInteger.php 128 KB

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