PageRenderTime 76ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/phpseclib/Math/BigInteger.php

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