PageRenderTime 66ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/phpseclib/phpseclib/phpseclib/Math/BigInteger.php

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