BigInteger.php 121 KB

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