PageRenderTime 63ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/fuel/core/vendor/phpseclib/Math/BigInteger.php

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