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

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

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