PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/phpseclib/phpseclib/phpseclib/Math/BigInteger.php

https://bitbucket.org/openemr/openemr
PHP | 3754 lines | 2027 code | 494 blank | 1233 comment | 399 complexity | 9dff1fa96f84567b85082175a13679f5 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0, GPL-2.0, LGPL-3.0, BSD-3-Clause, Unlicense, MPL-2.0, GPL-3.0, LGPL-2.1

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

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

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