PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Phpseclib/Math/BigInteger.php

https://bitbucket.org/appstrakt/lib_php_phpseclib
PHP | 3063 lines | 1615 code | 440 blank | 1008 comment | 325 complexity | 636728e2836ca62832c632da45eabe91 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  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. * 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. * Useful resources are as follows:
  27. *
  28. * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)}
  29. * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)}
  30. * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip
  31. *
  32. * One idea for optimization is to use the comba method to reduce the number of operations performed.
  33. * MPM uses this quite extensively. The following URL elaborates:
  34. *
  35. * {@link http://www.everything2.com/index.pl?node_id=1736418}}}
  36. *
  37. * Here's an example of how to use this library:
  38. * <code>
  39. * <?php
  40. * include('Math/BigInteger.php');
  41. *
  42. * $a = new BigInteger(2);
  43. * $b = new BigInteger(3);
  44. *
  45. * $c = $a->add($b);
  46. *
  47. * echo $c->toString(); // outputs 5
  48. * ?>
  49. * </code>
  50. *
  51. * LICENSE: This library is free software; you can redistribute it and/or
  52. * modify it under the terms of the GNU Lesser General Public
  53. * License as published by the Free Software Foundation; either
  54. * version 2.1 of the License, or (at your option) any later version.
  55. *
  56. * This library is distributed in the hope that it will be useful,
  57. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  58. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  59. * Lesser General Public License for more details.
  60. *
  61. * You should have received a copy of the GNU Lesser General Public
  62. * License along with this library; if not, write to the Free Software
  63. * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  64. * MA 02111-1307 USA
  65. *
  66. * @category Math
  67. * @package BigInteger
  68. * @author Jim Wigginton <terrafrost@php.net>
  69. * @copyright MMVI Jim Wigginton
  70. * @license http://www.gnu.org/licenses/lgpl.txt
  71. * @version $Id: BigInteger.php 81 2010-05-19 21:56:16Z admin $
  72. * @link http://pear.php.net/package/BigInteger
  73. */
  74. namespace Phpseclib\Math;
  75. /**#@+
  76. * @access private
  77. * @see BigInteger::_slidingWindow()
  78. */
  79. /**
  80. * @see BigInteger::_montgomery()
  81. * @see BigInteger::_prepMontgomery()
  82. */
  83. define('MATH_BIGINTEGER_MONTGOMERY', 0);
  84. /**
  85. * @see BigInteger::_barrett()
  86. */
  87. define('MATH_BIGINTEGER_BARRETT', 1);
  88. /**
  89. * @see BigInteger::_mod2()
  90. */
  91. define('MATH_BIGINTEGER_POWEROF2', 2);
  92. /**
  93. * @see BigInteger::_remainder()
  94. */
  95. define('MATH_BIGINTEGER_CLASSIC', 3);
  96. /**
  97. * @see BigInteger::__clone()
  98. */
  99. define('MATH_BIGINTEGER_NONE', 4);
  100. /**#@-*/
  101. /**#@+
  102. * @access private
  103. * @see BigInteger::_montgomery()
  104. * @see BigInteger::_barrett()
  105. */
  106. /**
  107. * $cache[MATH_BIGINTEGER_VARIABLE] tells us whether or not the cached data is still valid.
  108. */
  109. define('MATH_BIGINTEGER_VARIABLE', 0);
  110. /**
  111. * $cache[MATH_BIGINTEGER_DATA] contains the cached data.
  112. */
  113. define('MATH_BIGINTEGER_DATA', 1);
  114. /**#@-*/
  115. /**#@+
  116. * @access private
  117. * @see BigInteger::BigInteger()
  118. */
  119. /**
  120. * To use the pure-PHP implementation
  121. */
  122. define('MATH_BIGINTEGER_MODE_INTERNAL', 1);
  123. /**
  124. * To use the BCMath library
  125. *
  126. * (if enabled; otherwise, the internal implementation will be used)
  127. */
  128. define('MATH_BIGINTEGER_MODE_BCMATH', 2);
  129. /**
  130. * To use the GMP library
  131. *
  132. * (if present; otherwise, either the BCMath or the internal implementation will be used)
  133. */
  134. define('MATH_BIGINTEGER_MODE_GMP', 3);
  135. /**#@-*/
  136. /**
  137. * The largest digit that may be used in addition / subtraction
  138. *
  139. * (we do pow(2, 52) instead of using 4503599627370496, directly, because some PHP installations
  140. * will truncate 4503599627370496)
  141. *
  142. * @access private
  143. */
  144. define('MATH_BIGINTEGER_MAX_DIGIT52', pow(2, 52));
  145. /**
  146. * Karatsuba Cutoff
  147. *
  148. * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication?
  149. *
  150. * @access private
  151. */
  152. define('MATH_BIGINTEGER_KARATSUBA_CUTOFF', 15);
  153. /**
  154. * Pure-PHP arbitrary precision integer arithmetic library. Supports base-2, base-10, base-16, and base-256
  155. * numbers.
  156. *
  157. * @author Jim Wigginton <terrafrost@php.net>
  158. * @version 1.0.0RC3
  159. * @access public
  160. * @package BigInteger
  161. */
  162. class BigInteger {
  163. /**
  164. * Holds the BigInteger's value.
  165. *
  166. * @var Array
  167. * @access private
  168. */
  169. var $value;
  170. /**
  171. * Holds the BigInteger's magnitude.
  172. *
  173. * @var Boolean
  174. * @access private
  175. */
  176. var $is_negative = false;
  177. /**
  178. * Random number generator function
  179. *
  180. * @see setRandomGenerator()
  181. * @access private
  182. */
  183. var $generator = 'mt_rand';
  184. /**
  185. * Precision
  186. *
  187. * @see setPrecision()
  188. * @access private
  189. */
  190. var $precision = -1;
  191. /**
  192. * Precision Bitmask
  193. *
  194. * @see setPrecision()
  195. * @access private
  196. */
  197. var $bitmask = false;
  198. /**
  199. * Converts base-2, base-10, base-16, and binary strings (eg. base-256) to BigIntegers.
  200. *
  201. * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using
  202. * two's compliment. The sole exception to this is -10, which is treated the same as 10 is.
  203. *
  204. * Here's an example:
  205. * <code>
  206. * <?php
  207. * include('Math/BigInteger.php');
  208. *
  209. * $a = new BigInteger('0x32', 16); // 50 in base-16
  210. *
  211. * echo $a->toString(); // outputs 50
  212. * ?>
  213. * </code>
  214. *
  215. * @param optional $x base-10 number or base-$base number if $base set.
  216. * @param optional integer $base
  217. * @return BigInteger
  218. * @access public
  219. */
  220. function __construct($x = 0, $base = 10)
  221. {
  222. if ( !defined('MATH_BIGINTEGER_MODE') ) {
  223. switch (true) {
  224. case extension_loaded('gmp'):
  225. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_GMP);
  226. break;
  227. case extension_loaded('bcmath'):
  228. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_BCMATH);
  229. break;
  230. default:
  231. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_INTERNAL);
  232. }
  233. }
  234. switch ( MATH_BIGINTEGER_MODE ) {
  235. case MATH_BIGINTEGER_MODE_GMP:
  236. if (is_resource($x) && get_resource_type($x) == 'GMP integer') {
  237. $this->value = $x;
  238. return;
  239. }
  240. $this->value = gmp_init(0);
  241. break;
  242. case MATH_BIGINTEGER_MODE_BCMATH:
  243. $this->value = '0';
  244. break;
  245. default:
  246. $this->value = array();
  247. }
  248. if ($x === 0) {
  249. return;
  250. }
  251. switch ($base) {
  252. case -256:
  253. if (ord($x[0]) & 0x80) {
  254. $x = ~$x;
  255. $this->is_negative = true;
  256. }
  257. case 256:
  258. switch ( MATH_BIGINTEGER_MODE ) {
  259. case MATH_BIGINTEGER_MODE_GMP:
  260. $sign = $this->is_negative ? '-' : '';
  261. $this->value = gmp_init($sign . '0x' . bin2hex($x));
  262. break;
  263. case MATH_BIGINTEGER_MODE_BCMATH:
  264. // round $len to the nearest 4 (thanks, DavidMJ!)
  265. $len = (strlen($x) + 3) & 0xFFFFFFFC;
  266. $x = str_pad($x, $len, chr(0), STR_PAD_LEFT);
  267. for ($i = 0; $i < $len; $i+= 4) {
  268. $this->value = bcmul($this->value, '4294967296'); // 4294967296 == 2**32
  269. $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])));
  270. }
  271. if ($this->is_negative) {
  272. $this->value = '-' . $this->value;
  273. }
  274. break;
  275. // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb)
  276. default:
  277. while (strlen($x)) {
  278. $this->value[] = $this->_bytes2int($this->_base256_rshift($x, 26));
  279. }
  280. }
  281. if ($this->is_negative) {
  282. if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) {
  283. $this->is_negative = false;
  284. }
  285. $temp = $this->add(new BigInteger('-1'));
  286. $this->value = $temp->value;
  287. }
  288. break;
  289. case 16:
  290. case -16:
  291. if ($base > 0 && $x[0] == '-') {
  292. $this->is_negative = true;
  293. $x = substr($x, 1);
  294. }
  295. $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x);
  296. $is_negative = false;
  297. if ($base < 0 && hexdec($x[0]) >= 8) {
  298. $this->is_negative = $is_negative = true;
  299. $x = bin2hex(~pack('H*', $x));
  300. }
  301. switch ( MATH_BIGINTEGER_MODE ) {
  302. case MATH_BIGINTEGER_MODE_GMP:
  303. $temp = $this->is_negative ? '-0x' . $x : '0x' . $x;
  304. $this->value = gmp_init($temp);
  305. $this->is_negative = false;
  306. break;
  307. case MATH_BIGINTEGER_MODE_BCMATH:
  308. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  309. $temp = new BigInteger(pack('H*', $x), 256);
  310. $this->value = $this->is_negative ? '-' . $temp->value : $temp->value;
  311. $this->is_negative = false;
  312. break;
  313. default:
  314. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  315. $temp = new BigInteger(pack('H*', $x), 256);
  316. $this->value = $temp->value;
  317. }
  318. if ($is_negative) {
  319. $temp = $this->add(new BigInteger('-1'));
  320. $this->value = $temp->value;
  321. }
  322. break;
  323. case 10:
  324. case -10:
  325. $x = preg_replace('#^(-?[0-9]*).*#', '$1', $x);
  326. switch ( MATH_BIGINTEGER_MODE ) {
  327. case MATH_BIGINTEGER_MODE_GMP:
  328. $this->value = gmp_init($x);
  329. break;
  330. case MATH_BIGINTEGER_MODE_BCMATH:
  331. // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different
  332. // results then doing it on '-1' does (modInverse does $x[0])
  333. $this->value = (string) $x;
  334. break;
  335. default:
  336. $temp = new BigInteger();
  337. // array(10000000) is 10**7 in base-2**26. 10**7 is the closest to 2**26 we can get without passing it.
  338. $multiplier = new BigInteger();
  339. $multiplier->value = array(10000000);
  340. if ($x[0] == '-') {
  341. $this->is_negative = true;
  342. $x = substr($x, 1);
  343. }
  344. $x = str_pad($x, strlen($x) + (6 * strlen($x)) % 7, 0, STR_PAD_LEFT);
  345. while (strlen($x)) {
  346. $temp = $temp->multiply($multiplier);
  347. $temp = $temp->add(new BigInteger($this->_int2bytes(substr($x, 0, 7)), 256));
  348. $x = substr($x, 7);
  349. }
  350. $this->value = $temp->value;
  351. }
  352. break;
  353. case 2: // base-2 support originally implemented by Lluis Pamies - thanks!
  354. case -2:
  355. if ($base > 0 && $x[0] == '-') {
  356. $this->is_negative = true;
  357. $x = substr($x, 1);
  358. }
  359. $x = preg_replace('#^([01]*).*#', '$1', $x);
  360. $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT);
  361. $str = '0x';
  362. while (strlen($x)) {
  363. $part = substr($x, 0, 4);
  364. $str.= dechex(bindec($part));
  365. $x = substr($x, 4);
  366. }
  367. if ($this->is_negative) {
  368. $str = '-' . $str;
  369. }
  370. $temp = new BigInteger($str, 8 * $base); // ie. either -16 or +16
  371. $this->value = $temp->value;
  372. $this->is_negative = $temp->is_negative;
  373. break;
  374. default:
  375. // base not supported, so we'll let $this == 0
  376. }
  377. }
  378. /**
  379. * Converts a BigInteger to a byte string (eg. base-256).
  380. *
  381. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  382. * saved as two's compliment.
  383. *
  384. * Here's an example:
  385. * <code>
  386. * <?php
  387. * include('Math/BigInteger.php');
  388. *
  389. * $a = new BigInteger('65');
  390. *
  391. * echo $a->toBytes(); // outputs chr(65)
  392. * ?>
  393. * </code>
  394. *
  395. * @param Boolean $twos_compliment
  396. * @return String
  397. * @access public
  398. * @internal Converts a base-2**26 number to base-2**8
  399. */
  400. function toBytes($twos_compliment = false)
  401. {
  402. if ($twos_compliment) {
  403. $comparison = $this->compare(new BigInteger());
  404. if ($comparison == 0) {
  405. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  406. }
  407. $temp = $comparison < 0 ? $this->add(new BigInteger(1)) : $this->copy();
  408. $bytes = $temp->toBytes();
  409. if (empty($bytes)) { // eg. if the number we're trying to convert is -1
  410. $bytes = chr(0);
  411. }
  412. if (ord($bytes[0]) & 0x80) {
  413. $bytes = chr(0) . $bytes;
  414. }
  415. return $comparison < 0 ? ~$bytes : $bytes;
  416. }
  417. switch ( MATH_BIGINTEGER_MODE ) {
  418. case MATH_BIGINTEGER_MODE_GMP:
  419. if (gmp_cmp($this->value, gmp_init(0)) == 0) {
  420. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  421. }
  422. $temp = gmp_strval(gmp_abs($this->value), 16);
  423. $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp;
  424. $temp = pack('H*', $temp);
  425. return $this->precision > 0 ?
  426. substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  427. ltrim($temp, chr(0));
  428. case MATH_BIGINTEGER_MODE_BCMATH:
  429. if ($this->value === '0') {
  430. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  431. }
  432. $value = '';
  433. $current = $this->value;
  434. if ($current[0] == '-') {
  435. $current = substr($current, 1);
  436. }
  437. // we don't do four bytes at a time because then numbers larger than 1<<31 would be negative
  438. // two's complimented numbers, which would break chr.
  439. while (bccomp($current, '0') > 0) {
  440. $temp = bcmod($current, 0x1000000);
  441. $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value;
  442. $current = bcdiv($current, 0x1000000);
  443. }
  444. return $this->precision > 0 ?
  445. substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  446. ltrim($value, chr(0));
  447. }
  448. if (!count($this->value)) {
  449. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  450. }
  451. $result = $this->_int2bytes($this->value[count($this->value) - 1]);
  452. $temp = $this->copy();
  453. for ($i = count($temp->value) - 2; $i >= 0; $i--) {
  454. $temp->_base256_lshift($result, 26);
  455. $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT);
  456. }
  457. return $this->precision > 0 ?
  458. substr(str_pad($result, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  459. $result;
  460. }
  461. /**
  462. * Converts a BigInteger to a hex string (eg. base-16)).
  463. *
  464. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  465. * saved as two's compliment.
  466. *
  467. * Here's an example:
  468. * <code>
  469. * <?php
  470. * include('Math/BigInteger.php');
  471. *
  472. * $a = new BigInteger('65');
  473. *
  474. * echo $a->toHex(); // outputs '41'
  475. * ?>
  476. * </code>
  477. *
  478. * @param Boolean $twos_compliment
  479. * @return String
  480. * @access public
  481. * @internal Converts a base-2**26 number to base-2**8
  482. */
  483. function toHex($twos_compliment = false)
  484. {
  485. return bin2hex($this->toBytes($twos_compliment));
  486. }
  487. /**
  488. * Converts a BigInteger to a bit string (eg. base-2).
  489. *
  490. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  491. * saved as two's compliment.
  492. *
  493. * Here's an example:
  494. * <code>
  495. * <?php
  496. * include('Math/BigInteger.php');
  497. *
  498. * $a = new BigInteger('65');
  499. *
  500. * echo $a->toBits(); // outputs '1000001'
  501. * ?>
  502. * </code>
  503. *
  504. * @param Boolean $twos_compliment
  505. * @return String
  506. * @access public
  507. * @internal Converts a base-2**26 number to base-2**2
  508. */
  509. function toBits($twos_compliment = false)
  510. {
  511. $hex = $this->toHex($twos_compliment);
  512. $bits = '';
  513. for ($i = 0; $i < strlen($hex); $i+=8) {
  514. $bits.= str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT);
  515. }
  516. return $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0');
  517. }
  518. /**
  519. * Converts a BigInteger to a base-10 number.
  520. *
  521. * Here's an example:
  522. * <code>
  523. * <?php
  524. * include('Math/BigInteger.php');
  525. *
  526. * $a = new BigInteger('50');
  527. *
  528. * echo $a->toString(); // outputs 50
  529. * ?>
  530. * </code>
  531. *
  532. * @return String
  533. * @access public
  534. * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10)
  535. */
  536. function toString()
  537. {
  538. switch ( MATH_BIGINTEGER_MODE ) {
  539. case MATH_BIGINTEGER_MODE_GMP:
  540. return gmp_strval($this->value);
  541. case MATH_BIGINTEGER_MODE_BCMATH:
  542. if ($this->value === '0') {
  543. return '0';
  544. }
  545. return ltrim($this->value, '0');
  546. }
  547. if (!count($this->value)) {
  548. return '0';
  549. }
  550. $temp = $this->copy();
  551. $temp->is_negative = false;
  552. $divisor = new BigInteger();
  553. $divisor->value = array(10000000); // eg. 10**7
  554. $result = '';
  555. while (count($temp->value)) {
  556. list($temp, $mod) = $temp->divide($divisor);
  557. $result = str_pad($mod->value[0], 7, '0', STR_PAD_LEFT) . $result;
  558. }
  559. $result = ltrim($result, '0');
  560. if ($this->is_negative) {
  561. $result = '-' . $result;
  562. }
  563. return $result;
  564. }
  565. /**
  566. * Copy an object
  567. *
  568. * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee
  569. * that all objects are passed by value, when appropriate. More information can be found here:
  570. *
  571. * {@link http://php.net/language.oop5.basic#51624}
  572. *
  573. * @access public
  574. * @see __clone()
  575. * @return BigInteger
  576. */
  577. function copy()
  578. {
  579. $temp = new BigInteger();
  580. $temp->value = $this->value;
  581. $temp->is_negative = $this->is_negative;
  582. $temp->generator = $this->generator;
  583. $temp->precision = $this->precision;
  584. $temp->bitmask = $this->bitmask;
  585. return $temp;
  586. }
  587. /**
  588. * __toString() magic method
  589. *
  590. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  591. * toString().
  592. *
  593. * @access public
  594. * @internal Implemented per a suggestion by Techie-Michael - thanks!
  595. */
  596. function __toString()
  597. {
  598. return $this->toString();
  599. }
  600. /**
  601. * __clone() magic method
  602. *
  603. * Although you can call BigInteger::__toString() directly in PHP5, you cannot call BigInteger::__clone()
  604. * 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
  605. * only syntax of $y = clone $x. As such, if you're trying to write an application that works on both PHP4 and PHP5,
  606. * call BigInteger::copy(), instead.
  607. *
  608. * @access public
  609. * @see copy()
  610. * @return BigInteger
  611. */
  612. function __clone()
  613. {
  614. return $this->copy();
  615. }
  616. /**
  617. * Adds two BigIntegers.
  618. *
  619. * Here's an example:
  620. * <code>
  621. * <?php
  622. * include('Math/BigInteger.php');
  623. *
  624. * $a = new BigInteger('10');
  625. * $b = new BigInteger('20');
  626. *
  627. * $c = $a->add($b);
  628. *
  629. * echo $c->toString(); // outputs 30
  630. * ?>
  631. * </code>
  632. *
  633. * @param BigInteger $y
  634. * @return BigInteger
  635. * @access public
  636. * @internal Performs base-2**52 addition
  637. */
  638. function add($y)
  639. {
  640. switch ( MATH_BIGINTEGER_MODE ) {
  641. case MATH_BIGINTEGER_MODE_GMP:
  642. $temp = new BigInteger();
  643. $temp->value = gmp_add($this->value, $y->value);
  644. return $this->_normalize($temp);
  645. case MATH_BIGINTEGER_MODE_BCMATH:
  646. $temp = new BigInteger();
  647. $temp->value = bcadd($this->value, $y->value);
  648. return $this->_normalize($temp);
  649. }
  650. $this_size = count($this->value);
  651. $y_size = count($y->value);
  652. if ($this_size == 0) {
  653. return $y->copy();
  654. } else if ($y_size == 0) {
  655. return $this->copy();
  656. }
  657. // subtract, if appropriate
  658. if ( $this->is_negative != $y->is_negative ) {
  659. // is $y the negative number?
  660. $y_negative = $this->compare($y) > 0;
  661. $temp = $this->copy();
  662. $y = $y->copy();
  663. $temp->is_negative = $y->is_negative = false;
  664. $diff = $temp->compare($y);
  665. if ( !$diff ) {
  666. $temp = new BigInteger();
  667. return $this->_normalize($temp);
  668. }
  669. $temp = $temp->subtract($y);
  670. $temp->is_negative = ($diff > 0) ? !$y_negative : $y_negative;
  671. return $this->_normalize($temp);
  672. }
  673. $result = new BigInteger();
  674. $carry = 0;
  675. $size = max($this_size, $y_size);
  676. $size+= $size & 1; // rounds $size to the nearest 2.
  677. $x = array_pad($this->value, $size, 0);
  678. $y = array_pad($y->value, $size, 0);
  679. for ($i = 0; $i < $size - 1; $i+=2) {
  680. $sum = $x[$i + 1] * 0x4000000 + $x[$i] + $y[$i + 1] * 0x4000000 + $y[$i] + $carry;
  681. $carry = $sum >= MATH_BIGINTEGER_MAX_DIGIT52; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  682. $sum = $carry ? $sum - MATH_BIGINTEGER_MAX_DIGIT52 : $sum;
  683. $temp = floor($sum / 0x4000000);
  684. $result->value[] = $sum - 0x4000000 * $temp; // eg. a faster alternative to fmod($sum, 0x4000000)
  685. $result->value[] = $temp;
  686. }
  687. if ($carry) {
  688. $result->value[] = (int) $carry;
  689. }
  690. $result->is_negative = $this->is_negative;
  691. return $this->_normalize($result);
  692. }
  693. /**
  694. * Subtracts two BigIntegers.
  695. *
  696. * Here's an example:
  697. * <code>
  698. * <?php
  699. * include('Math/BigInteger.php');
  700. *
  701. * $a = new BigInteger('10');
  702. * $b = new BigInteger('20');
  703. *
  704. * $c = $a->subtract($b);
  705. *
  706. * echo $c->toString(); // outputs -10
  707. * ?>
  708. * </code>
  709. *
  710. * @param BigInteger $y
  711. * @return BigInteger
  712. * @access public
  713. * @internal Performs base-2**52 subtraction
  714. */
  715. function subtract($y)
  716. {
  717. switch ( MATH_BIGINTEGER_MODE ) {
  718. case MATH_BIGINTEGER_MODE_GMP:
  719. $temp = new BigInteger();
  720. $temp->value = gmp_sub($this->value, $y->value);
  721. return $this->_normalize($temp);
  722. case MATH_BIGINTEGER_MODE_BCMATH:
  723. $temp = new BigInteger();
  724. $temp->value = bcsub($this->value, $y->value);
  725. return $this->_normalize($temp);
  726. }
  727. $this_size = count($this->value);
  728. $y_size = count($y->value);
  729. if ($this_size == 0) {
  730. $temp = $y->copy();
  731. $temp->is_negative = !$temp->is_negative;
  732. return $temp;
  733. } else if ($y_size == 0) {
  734. return $this->copy();
  735. }
  736. // add, if appropriate (ie. -$x - +$y or +$x - -$y)
  737. if ( $this->is_negative != $y->is_negative ) {
  738. $is_negative = $y->compare($this) > 0;
  739. $temp = $this->copy();
  740. $y = $y->copy();
  741. $temp->is_negative = $y->is_negative = false;
  742. $temp = $temp->add($y);
  743. $temp->is_negative = $is_negative;
  744. return $this->_normalize($temp);
  745. }
  746. $diff = $this->compare($y);
  747. if ( !$diff ) {
  748. $temp = new BigInteger();
  749. return $this->_normalize($temp);
  750. }
  751. // switch $this and $y around, if appropriate.
  752. if ( (!$this->is_negative && $diff < 0) || ($this->is_negative && $diff > 0) ) {
  753. $is_negative = $y->is_negative;
  754. $temp = $this->copy();
  755. $y = $y->copy();
  756. $temp->is_negative = $y->is_negative = false;
  757. $temp = $y->subtract($temp);
  758. $temp->is_negative = !$is_negative;
  759. return $this->_normalize($temp);
  760. }
  761. $result = new BigInteger();
  762. $carry = 0;
  763. $size = max($this_size, $y_size);
  764. $size+= $size % 2;
  765. $x = array_pad($this->value, $size, 0);
  766. $y = array_pad($y->value, $size, 0);
  767. for ($i = 0; $i < $size - 1; $i+=2) {
  768. $sum = $x[$i + 1] * 0x4000000 + $x[$i] - $y[$i + 1] * 0x4000000 - $y[$i] + $carry;
  769. $carry = $sum < 0 ? -1 : 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  770. $sum = $carry ? $sum + MATH_BIGINTEGER_MAX_DIGIT52 : $sum;
  771. $temp = floor($sum / 0x4000000);
  772. $result->value[] = $sum - 0x4000000 * $temp;
  773. $result->value[] = $temp;
  774. }
  775. // $carry shouldn't be anything other than zero, at this point, since we already made sure that $this
  776. // was bigger than $y.
  777. $result->is_negative = $this->is_negative;
  778. return $this->_normalize($result);
  779. }
  780. /**
  781. * Multiplies two BigIntegers
  782. *
  783. * Here's an example:
  784. * <code>
  785. * <?php
  786. * include('Math/BigInteger.php');
  787. *
  788. * $a = new BigInteger('10');
  789. * $b = new BigInteger('20');
  790. *
  791. * $c = $a->multiply($b);
  792. *
  793. * echo $c->toString(); // outputs 200
  794. * ?>
  795. * </code>
  796. *
  797. * @param BigInteger $x
  798. * @return BigInteger
  799. * @access public
  800. */
  801. function multiply($x)
  802. {
  803. switch ( MATH_BIGINTEGER_MODE ) {
  804. case MATH_BIGINTEGER_MODE_GMP:
  805. $temp = new BigInteger();
  806. $temp->value = gmp_mul($this->value, $x->value);
  807. return $this->_normalize($temp);
  808. case MATH_BIGINTEGER_MODE_BCMATH:
  809. $temp = new BigInteger();
  810. $temp->value = bcmul($this->value, $x->value);
  811. return $this->_normalize($temp);
  812. }
  813. static $cutoff = false;
  814. if ($cutoff === false) {
  815. $cutoff = 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF;
  816. }
  817. if ( $this->equals($x) ) {
  818. return $this->_square();
  819. }
  820. $this_length = count($this->value);
  821. $x_length = count($x->value);
  822. if ( !$this_length || !$x_length ) { // a 0 is being multiplied
  823. $temp = new BigInteger();
  824. return $this->_normalize($temp);
  825. }
  826. $product = min($this_length, $x_length) < $cutoff ? $this->_multiply($x) : $this->_karatsuba($x);
  827. $product->is_negative = $this->is_negative != $x->is_negative;
  828. return $this->_normalize($product);
  829. }
  830. /**
  831. * Performs long multiplication up to $stop digits
  832. *
  833. * If you're going to be doing array_slice($product->value, 0, $stop), some cycles can be saved.
  834. *
  835. * @see _barrett()
  836. * @param BigInteger $x
  837. * @return BigInteger
  838. * @access private
  839. */
  840. function _multiplyLower($x, $stop)
  841. {
  842. $this_length = count($this->value);
  843. $x_length = count($x->value);
  844. if ( !$this_length || !$x_length ) { // a 0 is being multiplied
  845. return new BigInteger();
  846. }
  847. if ( $this_length < $x_length ) {
  848. return $x->_multiplyLower($this, $stop);
  849. }
  850. $product = new BigInteger();
  851. $product->value = $this->_array_repeat(0, $this_length + $x_length);
  852. // the following for loop could be removed if the for loop following it
  853. // (the one with nested for loops) initially set $i to 0, but
  854. // doing so would also make the result in one set of unnecessary adds,
  855. // since on the outermost loops first pass, $product->value[$k] is going
  856. // to always be 0
  857. $carry = 0;
  858. for ($j = 0; $j < $this_length; $j++) { // ie. $i = 0, $k = $i
  859. $temp = $this->value[$j] * $x->value[0] + $carry; // $product->value[$k] == 0
  860. $carry = floor($temp / 0x4000000);
  861. $product->value[$j] = $temp - 0x4000000 * $carry;
  862. }
  863. if ($j < $stop) {
  864. $product->value[$j] = $carry;
  865. }
  866. // the above for loop is what the previous comment was talking about. the
  867. // following for loop is the "one with nested for loops"
  868. for ($i = 1; $i < $x_length; $i++) {
  869. $carry = 0;
  870. for ($j = 0, $k = $i; $j < $this_length && $k < $stop; $j++, $k++) {
  871. $temp = $product->value[$k] + $this->value[$j] * $x->value[$i] + $carry;
  872. $carry = floor($temp / 0x4000000);
  873. $product->value[$k] = $temp - 0x4000000 * $carry;
  874. }
  875. if ($k < $stop) {
  876. $product->value[$k] = $carry;
  877. }
  878. }
  879. $product->is_negative = $this->is_negative != $x->is_negative;
  880. return $product;
  881. }
  882. /**
  883. * Performs long multiplication on two BigIntegers
  884. *
  885. * Modeled after 'multiply' in MutableBigInteger.java.
  886. *
  887. * @param BigInteger $x
  888. * @return BigInteger
  889. * @access private
  890. */
  891. function _multiply($x)
  892. {
  893. $this_length = count($this->value);
  894. $x_length = count($x->value);
  895. if ( !$this_length || !$x_length ) { // a 0 is being multiplied
  896. return new BigInteger();
  897. }
  898. if ( $this_length < $x_length ) {
  899. return $x->_multiply($this);
  900. }
  901. $product = new BigInteger();
  902. $product->value = $this->_array_repeat(0, $this_length + $x_length);
  903. // the following for loop could be removed if the for loop following it
  904. // (the one with nested for loops) initially set $i to 0, but
  905. // doing so would also make the result in one set of unnecessary adds,
  906. // since on the outermost loops first pass, $product->value[$k] is going
  907. // to always be 0
  908. $carry = 0;
  909. for ($j = 0; $j < $this_length; $j++) { // ie. $i = 0
  910. $temp = $this->value[$j] * $x->value[0] + $carry; // $product->value[$k] == 0
  911. $carry = floor($temp / 0x4000000);
  912. $product->value[$j] = $temp - 0x4000000 * $carry;
  913. }
  914. $product->value[$j] = $carry;
  915. // the above for loop is what the previous comment was talking about. the
  916. // following for loop is the "one with nested for loops"
  917. for ($i = 1; $i < $x_length; $i++) {
  918. $carry = 0;
  919. for ($j = 0, $k = $i; $j < $this_length; $j++, $k++) {
  920. $temp = $product->value[$k] + $this->value[$j] * $x->value[$i] + $carry;
  921. $carry = floor($temp / 0x4000000);
  922. $product->value[$k] = $temp - 0x4000000 * $carry;
  923. }
  924. $product->value[$k] = $carry;
  925. }
  926. $product->is_negative = $this->is_negative != $x->is_negative;
  927. return $this->_normalize($product);
  928. }
  929. /**
  930. * Performs Karatsuba multiplication on two BigIntegers
  931. *
  932. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  933. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}.
  934. *
  935. * @param BigInteger $y
  936. * @return BigInteger
  937. * @access private
  938. */
  939. function _karatsuba($y)
  940. {
  941. $x = $this->copy();
  942. $m = min(count($x->value) >> 1, count($y->value) >> 1);
  943. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  944. return $x->_multiply($y);
  945. }
  946. $x1 = new BigInteger();
  947. $x0 = new BigInteger();
  948. $y1 = new BigInteger();
  949. $y0 = new BigInteger();
  950. $x1->value = array_slice($x->value, $m);
  951. $x0->value = array_slice($x->value, 0, $m);
  952. $y1->value = array_slice($y->value, $m);
  953. $y0->value = array_slice($y->value, 0, $m);
  954. $z2 = $x1->_karatsuba($y1);
  955. $z0 = $x0->_karatsuba($y0);
  956. $z1 = $x1->add($x0);
  957. $z1 = $z1->_karatsuba($y1->add($y0));
  958. $z1 = $z1->subtract($z2->add($z0));
  959. $z2->value = array_merge(array_fill(0, 2 * $m, 0), $z2->value);
  960. $z1->value = array_merge(array_fill(0, $m, 0), $z1->value);
  961. $xy = $z2->add($z1);
  962. $xy = $xy->add($z0);
  963. return $xy;
  964. }
  965. /**
  966. * Squares a BigInteger
  967. *
  968. * @return BigInteger
  969. * @access private
  970. */
  971. function _square()
  972. {
  973. static $cutoff = false;
  974. if ($cutoff === false) {
  975. $cutoff = 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF;
  976. }
  977. return count($this->value) < $cutoff ? $this->_baseSquare() : $this->_karatsubaSquare();
  978. }
  979. /**
  980. * Performs traditional squaring on two BigIntegers
  981. *
  982. * Squaring can be done faster than multiplying a number by itself can be. See
  983. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} /
  984. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information.
  985. *
  986. * @return BigInteger
  987. * @access private
  988. */
  989. function _baseSquare()
  990. {
  991. if ( empty($this->value) ) {
  992. return new BigInteger();
  993. }
  994. $square = new BigInteger();
  995. $square->value = $this->_array_repeat(0, 2 * count($this->value));
  996. for ($i = 0, $max_index = count($this->value) - 1; $i <= $max_index; $i++) {
  997. $i2 = 2 * $i;
  998. $temp = $square->value[$i2] + $this->value[$i] * $this->value[$i];
  999. $carry = floor($temp / 0x4000000);
  1000. $square->value[$i2] = $temp - 0x4000000 * $carry;
  1001. // note how we start from $i+1 instead of 0 as we do in multiplication.
  1002. for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; $j++, $k++) {
  1003. $temp = $square->value[$k] + 2 * $this->value[$j] * $this->value[$i] + $carry;
  1004. $carry = floor($temp / 0x4000000);
  1005. $square->value[$k] = $temp - 0x4000000 * $carry;
  1006. }
  1007. // the following line can yield values larger 2**15. at this point, PHP should switch
  1008. // over to floats.
  1009. $square->value[$i + $max_index + 1] = $carry;
  1010. }
  1011. return $square;
  1012. }
  1013. /**
  1014. * Performs Karatsuba "squaring" on two BigIntegers
  1015. *
  1016. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1017. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}.
  1018. *
  1019. * @param BigInteger $y
  1020. * @return BigInteger
  1021. * @access private
  1022. */
  1023. function _karatsubaSquare()
  1024. {
  1025. $m = count($this->value) >> 1;
  1026. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1027. return $this->_square();
  1028. }
  1029. $x1 = new BigInteger();
  1030. $x0 = new BigInteger();
  1031. $x1->value = array_slice($this->value, $m);
  1032. $x0->value = array_slice($this->value, 0, $m);
  1033. $z2 = $x1->_karatsubaSquare();
  1034. $z0 = $x0->_karatsubaSquare();
  1035. $z1 = $x1->add($x0);
  1036. $z1 = $z1->_karatsubaSquare();
  1037. $z1 = $z1->subtract($z2->add($z0));
  1038. $z2->value = array_merge(array_fill(0, 2 * $m, 0), $z2->value);
  1039. $z1->value = array_merge(array_fill(0, $m, 0), $z1->value);
  1040. $xx = $z2->add($z1);
  1041. $xx = $xx->add($z0);
  1042. return $xx;
  1043. }
  1044. /**
  1045. * Divides two BigIntegers.
  1046. *
  1047. * Returns an array whose first element contains the quotient and whose second element contains the
  1048. * "common residue". If the remainder would be positive, the "common residue" and the remainder are the
  1049. * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder
  1050. * and the divisor (basically, the "common residue" is the first positive modulo).
  1051. *
  1052. * Here's an example:
  1053. * <code>
  1054. * <?php
  1055. * include('Math/BigInteger.php');
  1056. *
  1057. * $a = new BigInteger('10');
  1058. * $b = new BigInteger('20');
  1059. *
  1060. * list($quotient, $remainder) = $a->divide($b);
  1061. *
  1062. * echo $quotient->toString(); // outputs 0
  1063. * echo "\r\n";
  1064. * echo $remainder->toString(); // outputs 10
  1065. * ?>
  1066. * </code>
  1067. *
  1068. * @param BigInteger $y
  1069. * @return Array
  1070. * @access public
  1071. * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}.
  1072. */
  1073. function divide($y)
  1074. {
  1075. switch ( MATH_BIGINTEGER_MODE ) {
  1076. case MATH_BIGINTEGER_MODE_GMP:
  1077. $quotient = new BigInteger();
  1078. $remainder = new BigInteger();
  1079. list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value);
  1080. if (gmp_sign($remainder->value) < 0) {
  1081. $remainder->value = gmp_add($remainder->value, gmp_abs($y->value));
  1082. }
  1083. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1084. case MATH_BIGINTEGER_MODE_BCMATH:
  1085. $quotient = new BigInteger();
  1086. $remainder = new BigInteger();
  1087. $quotient->value = bcdiv($this->value, $y->value);
  1088. $remainder->value = bcmod($this->value, $y->value);
  1089. if ($remainder->value[0] == '-') {
  1090. $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value);
  1091. }
  1092. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1093. }
  1094. if (count($y->value) == 1) {
  1095. $temp = $this->_divide_digit($y->value[0]);
  1096. $temp[0]->is_negative = $this->is_negative != $y->is_negative;
  1097. return array($this->_normalize($temp[0]), $this->_normalize($temp[1]));
  1098. }
  1099. static $zero;
  1100. if (!isset($zero)) {
  1101. $zero = new BigInteger();
  1102. }
  1103. $x = $this->copy();
  1104. $y = $y->copy();
  1105. $x_sign = $x->is_negative;
  1106. $y_sign = $y->is_negative;
  1107. $x->is_negative = $y->is_negative = false;
  1108. $diff = $x->compare($y);
  1109. if ( !$diff ) {
  1110. $temp = new BigInteger();
  1111. $temp->value = array(1);
  1112. $temp->is_negative = $x_sign != $y_sign;
  1113. return array($this->_normalize($temp), $this->_normalize(new BigInteger()));
  1114. }
  1115. if ( $diff < 0 ) {
  1116. // if $x is negative, "add" $y.
  1117. if ( $x_sign ) {
  1118. $x = $y->subtract($x);
  1119. }
  1120. return array($this->_normalize(new BigInteger()), $this->_normalize($x));
  1121. }
  1122. // normalize $x and $y as described in HAC 14.23 / 14.24
  1123. $msb = $y->value[count($y->value) - 1];
  1124. for ($shift = 0; !($msb & 0x2000000); $shift++) {
  1125. $msb <<= 1;
  1126. }
  1127. $x->_lshift($shift);
  1128. $y->_lshift($shift);
  1129. $x_max = count($x->value) - 1;
  1130. $y_max = count($y->value) - 1;
  1131. $quotient = new BigInteger();
  1132. $quotient->value = $this->_array_repeat(0, $x_max - $y_max + 1);
  1133. // $temp = $y << ($x_max - $y_max-1) in base 2**26
  1134. $temp = new BigInteger();
  1135. $temp->value = array_merge($this->_array_repeat(0, $x_max - $y_max), $y->value);
  1136. while ( $x->compare($temp) >= 0 ) {
  1137. // calculate the "common residue"
  1138. $quotient->value[$x_max - $y_max]++;
  1139. $x = $x->subtract($temp);
  1140. $x_max = count($x->value) - 1;
  1141. }
  1142. for ($i = $x_max; $i >= $y_max + 1; $i--) {
  1143. $x_value = array(
  1144. $x->value[$i],
  1145. ( $i > 0 ) ? $x->value[$i - 1] : 0,
  1146. ( $i > 1 ) ? $x->value[$i - 2] : 0
  1147. );
  1148. $y_value = array(
  1149. $y->value[$y_max],
  1150. ( $y_max > 0 ) ? $y->value[$y_max - 1] : 0
  1151. );
  1152. $q_index = $i - $y_max - 1;
  1153. if ($x_value[0] == $y_value[0]) {
  1154. $quotient->value[$q_index] = 0x3FFFFFF;
  1155. } else {
  1156. $quotient->value[$q_index] = floor(
  1157. ($x_value[0] * 0x4000000 + $x_value[1])
  1158. /
  1159. $y_value[0]
  1160. );
  1161. }
  1162. $temp = new BigInteger();
  1163. $temp->value = array($y_value[1], $y_value[0]);
  1164. $lhs = new BigInteger();
  1165. $lhs->value = array($quotient->value[$q_index]);
  1166. $lhs = $lhs->multiply($temp);
  1167. $rhs = new BigInteger();
  1168. $rhs->value = array($x_value[2], $x_value[1], $x_value[0]);
  1169. while ( $lhs->compare($rhs) > 0 ) {
  1170. $quotient->value[$q_index]--;
  1171. $lhs = new BigInteger();
  1172. $lhs->value = array($quotient->value[$q_index]);
  1173. $lhs = $lhs->multiply($temp);
  1174. }
  1175. $adjust = $this->_array_repeat(0, $q_index);
  1176. $temp = new BigInteger();
  1177. $temp->value = array($quotient->value[$q_index]);
  1178. $temp = $temp->multiply($y);
  1179. $temp->value = array_merge($adjust, $temp->value);
  1180. $x = $x->subtract($temp);
  1181. if ($x->compare($zero) < 0) {
  1182. $temp->value = array_merge($adjust, $y->value);
  1183. $x = $x->add($temp);
  1184. $quotient->value[$q_index]--;
  1185. }
  1186. $x_max = count($x->value) - 1;
  1187. }
  1188. // unnormalize the remainder
  1189. $x->_rshift($shift);
  1190. $quotient->is_negative = $x_sign != $y_sign;
  1191. // calculate the "common residue", if appropriate
  1192. if ( $x_sign ) {
  1193. $y->_rshift($shift);
  1194. $x = $y->subtract($x);
  1195. }
  1196. return array($this->_normalize($quotient), $this->_normalize($x));
  1197. }
  1198. /**
  1199. * Divides a BigInteger by a regular integer
  1200. *
  1201. * abc / x = a00 / x + b0 / x + c / x
  1202. *
  1203. * @param BigInteger $divisor
  1204. * @return Array
  1205. * @access public
  1206. */
  1207. function _divide_digit($divisor)
  1208. {
  1209. $carry = 0;
  1210. $result = new BigInteger();
  1211. for ($i = count($this->value) - 1; $i >= 0; $i--) {
  1212. $temp = 0x4000000 * $carry + $this->value[$i];
  1213. $result->value[$i] = floor($temp / $divisor);
  1214. $carry = fmod($temp, $divisor);
  1215. }
  1216. $remainder = new BigInteger();
  1217. $remainder->value = array($carry);
  1218. return array($result, $remainder);
  1219. }
  1220. /**
  1221. * Performs modular exponentiation.
  1222. *
  1223. * Here's an example:
  1224. * <code>
  1225. * <?php
  1226. * include('Math/BigInteger.php');
  1227. *
  1228. * $a = new BigInteger('10');
  1229. * $b = new BigInteger('20');
  1230. * $c = new BigInteger('30');
  1231. *
  1232. * $c = $a->modPow($b, $c);
  1233. *
  1234. * echo $c->toString(); // outputs 10
  1235. * ?>
  1236. * </code>
  1237. *
  1238. * @param BigInteger $e
  1239. * @param BigInteger $n
  1240. * @return BigInteger
  1241. * @access public
  1242. * @internal The most naive approach to modular exponentiation has very unreasonable requirements, and
  1243. * and although the approach involving repeated squaring does vastly better, it, too, is impractical
  1244. * for our purposes. The reason being that division - by far the most complicated and time-consuming
  1245. * of the basic operations (eg. +,-,*,/) - occurs multiple times within it.
  1246. *
  1247. * Modular reductions resolve this issue. Although an individual modular reduction takes more time
  1248. * then an individual division, when performed in succession (with the same modulo), they're a lot faster.
  1249. *
  1250. * The two most commonly used modular reductions are Barrett and Montgomery reduction. Montgomery reduction,
  1251. * although faster, only works when the gcd of the modulo and of the base being used is 1. In RSA, when the
  1252. * base is a power of two, the modulo - a product of two primes - is always going to have a gcd of 1 (because
  1253. * the product of two odd numbers is odd), but what about when RSA isn't used?
  1254. *
  1255. * In contrast, Barrett reduction has no such constraint. As such, some bigint implementations perform a
  1256. * Barrett reduction after every operation in the modpow function. Others perform Barrett reductions when the
  1257. * modulo is even and Montgomery reductions when the modulo is odd. BigInteger.java's modPow method, however,
  1258. * uses a trick involving the Chinese Remainder Theorem to factor the even modulo into two numbers - one odd and
  1259. * the other, a power of two - and recombine them, later. This is the method that this modPow function uses.
  1260. * {@link http://islab.oregonstate.edu/papers/j34monex.pdf Montgomery Reduction with Even Modulus} elaborates.
  1261. */
  1262. function modPow($e, $n)
  1263. {
  1264. $n = $this->bitmask !== false && $this->bitmask->compare($n) < 0 ? $this->bitmask : $n->abs();
  1265. if ($e->compare(new BigInteger()) < 0) {
  1266. $e = $e->abs();
  1267. $temp = $this->modInverse($n);
  1268. if ($temp === false) {
  1269. return false;
  1270. }
  1271. return $this->_normalize($temp->modPow($e, $n));
  1272. }
  1273. switch ( MATH_BIGINTEGER_MODE ) {
  1274. case MATH_BIGINTEGER_MODE_GMP:
  1275. $temp = new BigInteger();
  1276. $temp->value = gmp_powm($this->value, $e->value, $n->value);
  1277. return $this->_normalize($temp);
  1278. case MATH_BIGINTEGER_MODE_BCMATH:
  1279. $temp = new BigInteger();
  1280. $temp->value = bcpowmod($this->value, $e->value, $n->value);
  1281. return $this->_normalize($temp);
  1282. }
  1283. if ( empty($e->value) ) {
  1284. $temp = new BigInteger();
  1285. $temp->value = array(1);
  1286. return $this->_normalize($temp);
  1287. }
  1288. if ( $e->value == array(1) ) {
  1289. list(, $temp) = $this->divide($n);
  1290. return $this->_normalize($temp);
  1291. }
  1292. if ( $e->value == array(2) ) {
  1293. $temp = $this->_square();
  1294. list(, $temp) = $temp->divide($n);
  1295. return $this->_normalize($temp);
  1296. }
  1297. return $this->_normalize($this->_slidingWindow($e, $n, MATH_BIGINTEGER_BARRETT));
  1298. // is the modulo odd?
  1299. if ( $n->value[0] & 1 ) {
  1300. return $this->_normalize($this->_slidingWindow($e, $n, MATH_BIGINTEGER_MONTGOMERY));
  1301. }
  1302. // if it's not, it's even
  1303. // find the lowest set bit (eg. the max pow of 2 that divides $n)

Large files files are truncated, but you can click here to view the full file