PageRenderTime 66ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/system/expressionengine/third_party/updater/libraries/phpseclib/Math/BigInteger.php

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