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

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

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