PageRenderTime 77ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/phpseclib/Math/BigInteger.php

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