PageRenderTime 67ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/updraftplus/includes/phpseclib/Math/BigInteger.php

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