PageRenderTime 116ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 1ms

/phpseclib/Math/BigInteger.php

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