PageRenderTime 59ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Phpseclib/Math/BigInteger.php

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