PageRenderTime 75ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/vendors/phpseclib/Math/BigInteger.php

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