PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/phpseclib/Math/BigInteger.php

https://github.com/KenjiOhtsuka/core
PHP | 3714 lines | 1983 code | 491 blank | 1240 comment | 401 complexity | aafc7122eb095e2112211e2b1392fc2e MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. namespace PHPSecLib\Math;
  4. /**
  5. * Pure-PHP arbitrary precision integer arithmetic library.
  6. *
  7. * Supports base-2, base-10, base-16, and base-256 numbers. Uses the GMP or BCMath extensions, if available,
  8. * and an internal implementation, otherwise.
  9. *
  10. * PHP versions 4 and 5
  11. *
  12. * {@internal (all DocBlock comments regarding implementation - such as the one that follows - refer to the
  13. * {@link MATH_BIGINTEGER_MODE_INTERNAL MATH_BIGINTEGER_MODE_INTERNAL} mode)
  14. *
  15. * BigInteger uses base-2**26 to perform operations such as multiplication and division and
  16. * base-2**52 (ie. two base 2**26 digits) to perform addition and subtraction. Because the largest possible
  17. * value when multiplying two base-2**26 numbers together is a base-2**52 number, double precision floating
  18. * point numbers - numbers that should be supported on most hardware and whose significand is 53 bits - are
  19. * used. As a consequence, bitwise operators such as >> and << cannot be used, nor can the modulo operator %,
  20. * which only supports integers. Although this fact will slow this library down, the fact that such a high
  21. * base is being used should more than compensate.
  22. *
  23. * Numbers are stored in {@link http://en.wikipedia.org/wiki/Endianness little endian} format. ie.
  24. * (new \PHPSecLib\Math\BigInteger(pow(2, 26)))->value = array(0, 1)
  25. *
  26. * Useful resources are as follows:
  27. *
  28. * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)}
  29. * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)}
  30. * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip
  31. *
  32. * Here's an example of how to use this library:
  33. * <code>
  34. * <?php
  35. * $a = new \PHPSecLib\Math\BigInteger(2);
  36. * $b = new \PHPSecLib\Math\BigInteger(3);
  37. *
  38. * $c = $a->add($b);
  39. *
  40. * echo $c->toString(); // outputs 5
  41. * ?>
  42. * </code>
  43. *
  44. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  45. * of this software and associated documentation files (the "Software"), to deal
  46. * in the Software without restriction, including without limitation the rights
  47. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  48. * copies of the Software, and to permit persons to whom the Software is
  49. * furnished to do so, subject to the following conditions:
  50. *
  51. * The above copyright notice and this permission notice shall be included in
  52. * all copies or substantial portions of the Software.
  53. *
  54. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  55. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  56. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  57. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  58. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  59. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  60. * THE SOFTWARE.
  61. *
  62. * @category Math
  63. * @package Math_BigInteger
  64. * @author Jim Wigginton <terrafrost@php.net>
  65. * @copyright MMVI Jim Wigginton
  66. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  67. * @link http://pear.php.net/package/Math_BigInteger
  68. */
  69. use \phpseclib\Crypt\Random;
  70. /**#@+
  71. * Reduction constants
  72. *
  73. * @access private
  74. * @see BigInteger::_reduce()
  75. */
  76. /**
  77. * @see BigInteger::_montgomery()
  78. * @see BigInteger::_prepMontgomery()
  79. */
  80. define('MATH_BIGINTEGER_MONTGOMERY', 0);
  81. /**
  82. * @see BigInteger::_barrett()
  83. */
  84. define('MATH_BIGINTEGER_BARRETT', 1);
  85. /**
  86. * @see BigInteger::_mod2()
  87. */
  88. define('MATH_BIGINTEGER_POWEROF2', 2);
  89. /**
  90. * @see BigInteger::_remainder()
  91. */
  92. define('MATH_BIGINTEGER_CLASSIC', 3);
  93. /**
  94. * @see BigInteger::__clone()
  95. */
  96. define('MATH_BIGINTEGER_NONE', 4);
  97. /**#@-*/
  98. /**#@+
  99. * Array constants
  100. *
  101. * Rather than create a thousands and thousands of new BigInteger objects in repeated function calls to add() and
  102. * multiply() or whatever, we'll just work directly on arrays, taking them in as parameters and returning them.
  103. *
  104. * @access private
  105. */
  106. /**
  107. * $result[MATH_BIGINTEGER_VALUE] contains the value.
  108. */
  109. define('MATH_BIGINTEGER_VALUE', 0);
  110. /**
  111. * $result[MATH_BIGINTEGER_SIGN] contains the sign.
  112. */
  113. define('MATH_BIGINTEGER_SIGN', 1);
  114. /**#@-*/
  115. /**#@+
  116. * @access private
  117. * @see BigInteger::_montgomery()
  118. * @see BigInteger::_barrett()
  119. */
  120. /**
  121. * Cache constants
  122. *
  123. * $cache[MATH_BIGINTEGER_VARIABLE] tells us whether or not the cached data is still valid.
  124. */
  125. define('MATH_BIGINTEGER_VARIABLE', 0);
  126. /**
  127. * $cache[MATH_BIGINTEGER_DATA] contains the cached data.
  128. */
  129. define('MATH_BIGINTEGER_DATA', 1);
  130. /**#@-*/
  131. /**#@+
  132. * Mode constants.
  133. *
  134. * @access private
  135. * @see BigInteger::__construct()
  136. */
  137. /**
  138. * To use the pure-PHP implementation
  139. */
  140. define('MATH_BIGINTEGER_MODE_INTERNAL', 1);
  141. /**
  142. * To use the BCMath library
  143. *
  144. * (if enabled; otherwise, the internal implementation will be used)
  145. */
  146. define('MATH_BIGINTEGER_MODE_BCMATH', 2);
  147. /**
  148. * To use the GMP library
  149. *
  150. * (if present; otherwise, either the BCMath or the internal implementation will be used)
  151. */
  152. define('MATH_BIGINTEGER_MODE_GMP', 3);
  153. /**#@-*/
  154. /**
  155. * Karatsuba Cutoff
  156. *
  157. * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication?
  158. *
  159. * @access private
  160. */
  161. define('MATH_BIGINTEGER_KARATSUBA_CUTOFF', 25);
  162. /**
  163. * Pure-PHP arbitrary precision integer arithmetic library. Supports base-2, base-10, base-16, and base-256
  164. * numbers.
  165. *
  166. * @package Math_BigInteger
  167. * @author Jim Wigginton <terrafrost@php.net>
  168. * @access public
  169. */
  170. class BigInteger
  171. {
  172. /**
  173. * Holds the BigInteger's value.
  174. *
  175. * @var Array
  176. * @access private
  177. */
  178. var $value;
  179. /**
  180. * Holds the BigInteger's magnitude.
  181. *
  182. * @var Boolean
  183. * @access private
  184. */
  185. var $is_negative = false;
  186. /**
  187. * Random number generator function
  188. *
  189. * @access private
  190. */
  191. var $generator = 'mt_rand';
  192. /**
  193. * Precision
  194. *
  195. * @see setPrecision()
  196. * @access private
  197. */
  198. var $precision = -1;
  199. /**
  200. * Precision Bitmask
  201. *
  202. * @see setPrecision()
  203. * @access private
  204. */
  205. var $bitmask = false;
  206. /**
  207. * Mode independent value used for serialization.
  208. *
  209. * If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for
  210. * a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value,
  211. * however, $this->hex is only calculated when $this->__sleep() is called.
  212. *
  213. * @see __sleep()
  214. * @see __wakeup()
  215. * @var String
  216. * @access private
  217. */
  218. var $hex;
  219. /**
  220. * Converts base-2, base-10, base-16, and binary strings (base-256) to BigIntegers.
  221. *
  222. * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using
  223. * two's compliment. The sole exception to this is -10, which is treated the same as 10 is.
  224. *
  225. * Here's an example:
  226. * <code>
  227. * <?php
  228. * $a = new \PHPSecLib\Math\BigInteger('0x32', 16); // 50 in base-16
  229. *
  230. * echo $a->toString(); // outputs 50
  231. * ?>
  232. * </code>
  233. *
  234. * @param optional $x base-10 number or base-$base number if $base set.
  235. * @param optional integer $base
  236. * @return \PHPSecLib\Math\BigInteger
  237. * @access public
  238. */
  239. function __construct($x = 0, $base = 10)
  240. {
  241. if ( !defined('MATH_BIGINTEGER_MODE') ) {
  242. switch (true) {
  243. case extension_loaded('gmp'):
  244. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_GMP);
  245. break;
  246. case extension_loaded('bcmath'):
  247. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_BCMATH);
  248. break;
  249. default:
  250. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_INTERNAL);
  251. }
  252. }
  253. if (function_exists('openssl_public_encrypt') && !defined('MATH_BIGINTEGER_OPENSSL_DISABLE') && !defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) {
  254. // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
  255. ob_start();
  256. @phpinfo();
  257. $content = ob_get_contents();
  258. ob_end_clean();
  259. preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches);
  260. $versions = array();
  261. if (!empty($matches[1])) {
  262. for ($i = 0; $i < count($matches[1]); $i++) {
  263. $versions[$matches[1][$i]] = trim(str_replace('=>', '', strip_tags($matches[2][$i])));
  264. }
  265. }
  266. // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+
  267. switch (true) {
  268. case !isset($versions['Header']):
  269. case !isset($versions['Library']):
  270. case $versions['Header'] == $versions['Library']:
  271. define('MATH_BIGINTEGER_OPENSSL_ENABLED', true);
  272. break;
  273. default:
  274. define('MATH_BIGINTEGER_OPENSSL_DISABLE', true);
  275. }
  276. }
  277. if (!defined('PHP_INT_SIZE')) {
  278. define('PHP_INT_SIZE', 4);
  279. }
  280. if (!defined('MATH_BIGINTEGER_BASE') && MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_INTERNAL) {
  281. switch (PHP_INT_SIZE) {
  282. case 8: // use 64-bit integers if int size is 8 bytes
  283. define('MATH_BIGINTEGER_BASE', 31);
  284. define('MATH_BIGINTEGER_BASE_FULL', 0x80000000);
  285. define('MATH_BIGINTEGER_MAX_DIGIT', 0x7FFFFFFF);
  286. define('MATH_BIGINTEGER_MSB', 0x40000000);
  287. // 10**9 is the closest we can get to 2**31 without passing it
  288. define('MATH_BIGINTEGER_MAX10', 1000000000);
  289. define('MATH_BIGINTEGER_MAX10_LEN', 9);
  290. // the largest digit that may be used in addition / subtraction
  291. define('MATH_BIGINTEGER_MAX_DIGIT2', pow(2, 62));
  292. break;
  293. //case 4: // use 64-bit floats if int size is 4 bytes
  294. default:
  295. define('MATH_BIGINTEGER_BASE', 26);
  296. define('MATH_BIGINTEGER_BASE_FULL', 0x4000000);
  297. define('MATH_BIGINTEGER_MAX_DIGIT', 0x3FFFFFF);
  298. define('MATH_BIGINTEGER_MSB', 0x2000000);
  299. // 10**7 is the closest to 2**26 without passing it
  300. define('MATH_BIGINTEGER_MAX10', 10000000);
  301. define('MATH_BIGINTEGER_MAX10_LEN', 7);
  302. // the largest digit that may be used in addition / subtraction
  303. // we do pow(2, 52) instead of using 4503599627370496 directly because some
  304. // PHP installations will truncate 4503599627370496.
  305. define('MATH_BIGINTEGER_MAX_DIGIT2', pow(2, 52));
  306. }
  307. }
  308. switch ( MATH_BIGINTEGER_MODE ) {
  309. case MATH_BIGINTEGER_MODE_GMP:
  310. switch (true) {
  311. case is_resource($x) && get_resource_type($x) == 'GMP integer':
  312. // PHP 5.6 switched GMP from using resources to objects
  313. case is_object($x) && get_class($x) == 'GMP':
  314. $this->value = $x;
  315. return;
  316. }
  317. $this->value = gmp_init(0);
  318. break;
  319. case MATH_BIGINTEGER_MODE_BCMATH:
  320. $this->value = '0';
  321. break;
  322. default:
  323. $this->value = array();
  324. }
  325. // '0' counts as empty() but when the base is 256 '0' is equal to ord('0') or 48
  326. // '0' is the only value like this per http://php.net/empty
  327. if (empty($x) && (abs($base) != 256 || $x !== '0')) {
  328. return;
  329. }
  330. switch ($base) {
  331. case -256:
  332. if (ord($x[0]) & 0x80) {
  333. $x = ~$x;
  334. $this->is_negative = true;
  335. }
  336. case 256:
  337. switch ( MATH_BIGINTEGER_MODE ) {
  338. case MATH_BIGINTEGER_MODE_GMP:
  339. $sign = $this->is_negative ? '-' : '';
  340. $this->value = gmp_init($sign . '0x' . bin2hex($x));
  341. break;
  342. case MATH_BIGINTEGER_MODE_BCMATH:
  343. // round $len to the nearest 4 (thanks, DavidMJ!)
  344. $len = (strlen($x) + 3) & 0xFFFFFFFC;
  345. $x = str_pad($x, $len, chr(0), STR_PAD_LEFT);
  346. for ($i = 0; $i < $len; $i+= 4) {
  347. $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32
  348. $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0);
  349. }
  350. if ($this->is_negative) {
  351. $this->value = '-' . $this->value;
  352. }
  353. break;
  354. // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb)
  355. default:
  356. while (strlen($x)) {
  357. $this->value[] = $this->_bytes2int($this->_base256_rshift($x, MATH_BIGINTEGER_BASE));
  358. }
  359. }
  360. if ($this->is_negative) {
  361. if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) {
  362. $this->is_negative = false;
  363. }
  364. $temp = $this->add(new static('-1'));
  365. $this->value = $temp->value;
  366. }
  367. break;
  368. case 16:
  369. case -16:
  370. if ($base > 0 && $x[0] == '-') {
  371. $this->is_negative = true;
  372. $x = substr($x, 1);
  373. }
  374. $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x);
  375. $is_negative = false;
  376. if ($base < 0 && hexdec($x[0]) >= 8) {
  377. $this->is_negative = $is_negative = true;
  378. $x = bin2hex(~pack('H*', $x));
  379. }
  380. switch ( MATH_BIGINTEGER_MODE ) {
  381. case MATH_BIGINTEGER_MODE_GMP:
  382. $temp = $this->is_negative ? '-0x' . $x : '0x' . $x;
  383. $this->value = gmp_init($temp);
  384. $this->is_negative = false;
  385. break;
  386. case MATH_BIGINTEGER_MODE_BCMATH:
  387. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  388. $temp = new static(pack('H*', $x), 256);
  389. $this->value = $this->is_negative ? '-' . $temp->value : $temp->value;
  390. $this->is_negative = false;
  391. break;
  392. default:
  393. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  394. $temp = new static(pack('H*', $x), 256);
  395. $this->value = $temp->value;
  396. }
  397. if ($is_negative) {
  398. $temp = $this->add(new static('-1'));
  399. $this->value = $temp->value;
  400. }
  401. break;
  402. case 10:
  403. case -10:
  404. // (?<!^)(?:-).*: find any -'s that aren't at the beginning and then any characters that follow that
  405. // (?<=^|-)0*: find any 0's that are preceded by the start of the string or by a - (ie. octals)
  406. // [^-0-9].*: find any non-numeric characters and then any characters that follow that
  407. $x = preg_replace('#(?<!^)(?:-).*|(?<=^|-)0*|[^-0-9].*#', '', $x);
  408. switch ( MATH_BIGINTEGER_MODE ) {
  409. case MATH_BIGINTEGER_MODE_GMP:
  410. $this->value = gmp_init($x);
  411. break;
  412. case MATH_BIGINTEGER_MODE_BCMATH:
  413. // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different
  414. // results then doing it on '-1' does (modInverse does $x[0])
  415. $this->value = $x === '-' ? '0' : (string) $x;
  416. break;
  417. default:
  418. $temp = new static();
  419. $multiplier = new static();
  420. $multiplier->value = array(MATH_BIGINTEGER_MAX10);
  421. if ($x[0] == '-') {
  422. $this->is_negative = true;
  423. $x = substr($x, 1);
  424. }
  425. $x = str_pad($x, strlen($x) + ((MATH_BIGINTEGER_MAX10_LEN - 1) * strlen($x)) % MATH_BIGINTEGER_MAX10_LEN, 0, STR_PAD_LEFT);
  426. while (strlen($x)) {
  427. $temp = $temp->multiply($multiplier);
  428. $temp = $temp->add(new static($this->_int2bytes(substr($x, 0, MATH_BIGINTEGER_MAX10_LEN)), 256));
  429. $x = substr($x, MATH_BIGINTEGER_MAX10_LEN);
  430. }
  431. $this->value = $temp->value;
  432. }
  433. break;
  434. case 2: // base-2 support originally implemented by Lluis Pamies - thanks!
  435. case -2:
  436. if ($base > 0 && $x[0] == '-') {
  437. $this->is_negative = true;
  438. $x = substr($x, 1);
  439. }
  440. $x = preg_replace('#^([01]*).*#', '$1', $x);
  441. $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT);
  442. $str = '0x';
  443. while (strlen($x)) {
  444. $part = substr($x, 0, 4);
  445. $str.= dechex(bindec($part));
  446. $x = substr($x, 4);
  447. }
  448. if ($this->is_negative) {
  449. $str = '-' . $str;
  450. }
  451. $temp = new static($str, 8 * $base); // ie. either -16 or +16
  452. $this->value = $temp->value;
  453. $this->is_negative = $temp->is_negative;
  454. break;
  455. default:
  456. // base not supported, so we'll let $this == 0
  457. }
  458. }
  459. /**
  460. * Converts a BigInteger to a byte string (eg. base-256).
  461. *
  462. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  463. * saved as two's compliment.
  464. *
  465. * Here's an example:
  466. * <code>
  467. * <?php
  468. * $a = new \PHPSecLib\Math\BigInteger('65');
  469. *
  470. * echo $a->toBytes(); // outputs chr(65)
  471. * ?>
  472. * </code>
  473. *
  474. * @param Boolean $twos_compliment
  475. * @return String
  476. * @access public
  477. * @internal Converts a base-2**26 number to base-2**8
  478. */
  479. function toBytes($twos_compliment = false)
  480. {
  481. if ($twos_compliment) {
  482. $comparison = $this->compare(new static());
  483. if ($comparison == 0) {
  484. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  485. }
  486. $temp = $comparison < 0 ? $this->add(new static(1)) : $this->copy();
  487. $bytes = $temp->toBytes();
  488. if (empty($bytes)) { // eg. if the number we're trying to convert is -1
  489. $bytes = chr(0);
  490. }
  491. if (ord($bytes[0]) & 0x80) {
  492. $bytes = chr(0) . $bytes;
  493. }
  494. return $comparison < 0 ? ~$bytes : $bytes;
  495. }
  496. switch ( MATH_BIGINTEGER_MODE ) {
  497. case MATH_BIGINTEGER_MODE_GMP:
  498. if (gmp_cmp($this->value, gmp_init(0)) == 0) {
  499. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  500. }
  501. $temp = gmp_strval(gmp_abs($this->value), 16);
  502. $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp;
  503. $temp = pack('H*', $temp);
  504. return $this->precision > 0 ?
  505. substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  506. ltrim($temp, chr(0));
  507. case MATH_BIGINTEGER_MODE_BCMATH:
  508. if ($this->value === '0') {
  509. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  510. }
  511. $value = '';
  512. $current = $this->value;
  513. if ($current[0] == '-') {
  514. $current = substr($current, 1);
  515. }
  516. while (bccomp($current, '0', 0) > 0) {
  517. $temp = bcmod($current, '16777216');
  518. $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value;
  519. $current = bcdiv($current, '16777216', 0);
  520. }
  521. return $this->precision > 0 ?
  522. substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  523. ltrim($value, chr(0));
  524. }
  525. if (!count($this->value)) {
  526. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  527. }
  528. $result = $this->_int2bytes($this->value[count($this->value) - 1]);
  529. $temp = $this->copy();
  530. for ($i = count($temp->value) - 2; $i >= 0; --$i) {
  531. $temp->_base256_lshift($result, MATH_BIGINTEGER_BASE);
  532. $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT);
  533. }
  534. return $this->precision > 0 ?
  535. str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) :
  536. $result;
  537. }
  538. /**
  539. * Converts a BigInteger to a hex string (eg. base-16)).
  540. *
  541. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  542. * saved as two's compliment.
  543. *
  544. * Here's an example:
  545. * <code>
  546. * <?php
  547. * $a = new \PHPSecLib\Math\BigInteger('65');
  548. *
  549. * echo $a->toHex(); // outputs '41'
  550. * ?>
  551. * </code>
  552. *
  553. * @param Boolean $twos_compliment
  554. * @return String
  555. * @access public
  556. * @internal Converts a base-2**26 number to base-2**8
  557. */
  558. function toHex($twos_compliment = false)
  559. {
  560. return bin2hex($this->toBytes($twos_compliment));
  561. }
  562. /**
  563. * Converts a BigInteger to a bit string (eg. base-2).
  564. *
  565. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  566. * saved as two's compliment.
  567. *
  568. * Here's an example:
  569. * <code>
  570. * <?php
  571. * $a = new \PHPSecLib\Math\BigInteger('65');
  572. *
  573. * echo $a->toBits(); // outputs '1000001'
  574. * ?>
  575. * </code>
  576. *
  577. * @param Boolean $twos_compliment
  578. * @return String
  579. * @access public
  580. * @internal Converts a base-2**26 number to base-2**2
  581. */
  582. function toBits($twos_compliment = false)
  583. {
  584. $hex = $this->toHex($twos_compliment);
  585. $bits = '';
  586. for ($i = strlen($hex) - 8, $start = strlen($hex) & 7; $i >= $start; $i-=8) {
  587. $bits = str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT) . $bits;
  588. }
  589. if ($start) { // hexdec('') == 0
  590. $bits = str_pad(decbin(hexdec(substr($hex, 0, $start))), 8, '0', STR_PAD_LEFT) . $bits;
  591. }
  592. $result = $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0');
  593. if ($twos_compliment && $this->compare(new static()) > 0 && $this->precision <= 0) {
  594. return '0' . $result;
  595. }
  596. return $result;
  597. }
  598. /**
  599. * Converts a BigInteger to a base-10 number.
  600. *
  601. * Here's an example:
  602. * <code>
  603. * <?php
  604. * $a = new \PHPSecLib\Math\BigInteger('50');
  605. *
  606. * echo $a->toString(); // outputs 50
  607. * ?>
  608. * </code>
  609. *
  610. * @return String
  611. * @access public
  612. * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10)
  613. */
  614. function toString()
  615. {
  616. switch ( MATH_BIGINTEGER_MODE ) {
  617. case MATH_BIGINTEGER_MODE_GMP:
  618. return gmp_strval($this->value);
  619. case MATH_BIGINTEGER_MODE_BCMATH:
  620. if ($this->value === '0') {
  621. return '0';
  622. }
  623. return ltrim($this->value, '0');
  624. }
  625. if (!count($this->value)) {
  626. return '0';
  627. }
  628. $temp = $this->copy();
  629. $temp->is_negative = false;
  630. $divisor = new static();
  631. $divisor->value = array(MATH_BIGINTEGER_MAX10);
  632. $result = '';
  633. while (count($temp->value)) {
  634. list($temp, $mod) = $temp->divide($divisor);
  635. $result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', MATH_BIGINTEGER_MAX10_LEN, '0', STR_PAD_LEFT) . $result;
  636. }
  637. $result = ltrim($result, '0');
  638. if (empty($result)) {
  639. $result = '0';
  640. }
  641. if ($this->is_negative) {
  642. $result = '-' . $result;
  643. }
  644. return $result;
  645. }
  646. /**
  647. * Copy an object
  648. *
  649. * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee
  650. * that all objects are passed by value, when appropriate. More information can be found here:
  651. *
  652. * {@link http://php.net/language.oop5.basic#51624}
  653. *
  654. * @access public
  655. * @see __clone()
  656. * @return \PHPSecLib\Math\BigInteger
  657. */
  658. function copy()
  659. {
  660. $temp = new static();
  661. $temp->value = $this->value;
  662. $temp->is_negative = $this->is_negative;
  663. $temp->generator = $this->generator;
  664. $temp->precision = $this->precision;
  665. $temp->bitmask = $this->bitmask;
  666. return $temp;
  667. }
  668. /**
  669. * __toString() magic method
  670. *
  671. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  672. * toString().
  673. *
  674. * @access public
  675. * @internal Implemented per a suggestion by Techie-Michael - thanks!
  676. */
  677. function __toString()
  678. {
  679. return $this->toString();
  680. }
  681. /**
  682. * __clone() magic method
  683. *
  684. * Although you can call BigInteger::__toString() directly in PHP5, you cannot call BigInteger::__clone() directly
  685. * 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
  686. * only syntax of $y = clone $x. As such, if you're trying to write an application that works on both PHP4 and
  687. * PHP5, call BigInteger::copy(), instead.
  688. *
  689. * @access public
  690. * @see copy()
  691. * @return \PHPSecLib\Math\BigInteger
  692. */
  693. function __clone()
  694. {
  695. return $this->copy();
  696. }
  697. /**
  698. * __sleep() magic method
  699. *
  700. * Will be called, automatically, when serialize() is called on a BigInteger object.
  701. *
  702. * @see __wakeup()
  703. * @access public
  704. */
  705. function __sleep()
  706. {
  707. $this->hex = $this->toHex(true);
  708. $vars = array('hex');
  709. if ($this->generator != 'mt_rand') {
  710. $vars[] = 'generator';
  711. }
  712. if ($this->precision > 0) {
  713. $vars[] = 'precision';
  714. }
  715. return $vars;
  716. }
  717. /**
  718. * __wakeup() magic method
  719. *
  720. * Will be called, automatically, when unserialize() is called on a BigInteger object.
  721. *
  722. * @see __sleep()
  723. * @access public
  724. */
  725. function __wakeup()
  726. {
  727. $temp = new static($this->hex, -16);
  728. $this->value = $temp->value;
  729. $this->is_negative = $temp->is_negative;
  730. if ($this->precision > 0) {
  731. // recalculate $this->bitmask
  732. $this->setPrecision($this->precision);
  733. }
  734. }
  735. /**
  736. * Adds two BigIntegers.
  737. *
  738. * Here's an example:
  739. * <code>
  740. * <?php
  741. * $a = new \PHPSecLib\Math\BigInteger('10');
  742. * $b = new \PHPSecLib\Math\BigInteger('20');
  743. *
  744. * $c = $a->add($b);
  745. *
  746. * echo $c->toString(); // outputs 30
  747. * ?>
  748. * </code>
  749. *
  750. * @param \PHPSecLib\Math\BigInteger $y
  751. * @return \PHPSecLib\Math\BigInteger
  752. * @access public
  753. * @internal Performs base-2**52 addition
  754. */
  755. function add($y)
  756. {
  757. switch ( MATH_BIGINTEGER_MODE ) {
  758. case MATH_BIGINTEGER_MODE_GMP:
  759. $temp = new static();
  760. $temp->value = gmp_add($this->value, $y->value);
  761. return $this->_normalize($temp);
  762. case MATH_BIGINTEGER_MODE_BCMATH:
  763. $temp = new static();
  764. $temp->value = bcadd($this->value, $y->value, 0);
  765. return $this->_normalize($temp);
  766. }
  767. $temp = $this->_add($this->value, $this->is_negative, $y->value, $y->is_negative);
  768. $result = new static();
  769. $result->value = $temp[MATH_BIGINTEGER_VALUE];
  770. $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  771. return $this->_normalize($result);
  772. }
  773. /**
  774. * Performs addition.
  775. *
  776. * @param Array $x_value
  777. * @param Boolean $x_negative
  778. * @param Array $y_value
  779. * @param Boolean $y_negative
  780. * @return Array
  781. * @access private
  782. */
  783. function _add($x_value, $x_negative, $y_value, $y_negative)
  784. {
  785. $x_size = count($x_value);
  786. $y_size = count($y_value);
  787. if ($x_size == 0) {
  788. return array(
  789. MATH_BIGINTEGER_VALUE => $y_value,
  790. MATH_BIGINTEGER_SIGN => $y_negative
  791. );
  792. } else if ($y_size == 0) {
  793. return array(
  794. MATH_BIGINTEGER_VALUE => $x_value,
  795. MATH_BIGINTEGER_SIGN => $x_negative
  796. );
  797. }
  798. // subtract, if appropriate
  799. if ( $x_negative != $y_negative ) {
  800. if ( $x_value == $y_value ) {
  801. return array(
  802. MATH_BIGINTEGER_VALUE => array(),
  803. MATH_BIGINTEGER_SIGN => false
  804. );
  805. }
  806. $temp = $this->_subtract($x_value, false, $y_value, false);
  807. $temp[MATH_BIGINTEGER_SIGN] = $this->_compare($x_value, false, $y_value, false) > 0 ?
  808. $x_negative : $y_negative;
  809. return $temp;
  810. }
  811. if ($x_size < $y_size) {
  812. $size = $x_size;
  813. $value = $y_value;
  814. } else {
  815. $size = $y_size;
  816. $value = $x_value;
  817. }
  818. $value[count($value)] = 0; // just in case the carry adds an extra digit
  819. $carry = 0;
  820. for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) {
  821. $sum = $x_value[$j] * MATH_BIGINTEGER_BASE_FULL + $x_value[$i] + $y_value[$j] * MATH_BIGINTEGER_BASE_FULL + $y_value[$i] + $carry;
  822. $carry = $sum >= MATH_BIGINTEGER_MAX_DIGIT2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  823. $sum = $carry ? $sum - MATH_BIGINTEGER_MAX_DIGIT2 : $sum;
  824. $temp = MATH_BIGINTEGER_BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31);
  825. $value[$i] = (int) ($sum - MATH_BIGINTEGER_BASE_FULL * $temp); // eg. a faster alternative to fmod($sum, 0x4000000)
  826. $value[$j] = $temp;
  827. }
  828. if ($j == $size) { // ie. if $y_size is odd
  829. $sum = $x_value[$i] + $y_value[$i] + $carry;
  830. $carry = $sum >= MATH_BIGINTEGER_BASE_FULL;
  831. $value[$i] = $carry ? $sum - MATH_BIGINTEGER_BASE_FULL : $sum;
  832. ++$i; // ie. let $i = $j since we've just done $value[$i]
  833. }
  834. if ($carry) {
  835. for (; $value[$i] == MATH_BIGINTEGER_MAX_DIGIT; ++$i) {
  836. $value[$i] = 0;
  837. }
  838. ++$value[$i];
  839. }
  840. return array(
  841. MATH_BIGINTEGER_VALUE => $this->_trim($value),
  842. MATH_BIGINTEGER_SIGN => $x_negative
  843. );
  844. }
  845. /**
  846. * Subtracts two BigIntegers.
  847. *
  848. * Here's an example:
  849. * <code>
  850. * <?php
  851. * $a = new \PHPSecLib\Math\BigInteger('10');
  852. * $b = new \PHPSecLib\Math\BigInteger('20');
  853. *
  854. * $c = $a->subtract($b);
  855. *
  856. * echo $c->toString(); // outputs -10
  857. * ?>
  858. * </code>
  859. *
  860. * @param \PHPSecLib\Math\BigInteger $y
  861. * @return \PHPSecLib\Math\BigInteger
  862. * @access public
  863. * @internal Performs base-2**52 subtraction
  864. */
  865. function subtract($y)
  866. {
  867. switch ( MATH_BIGINTEGER_MODE ) {
  868. case MATH_BIGINTEGER_MODE_GMP:
  869. $temp = new static();
  870. $temp->value = gmp_sub($this->value, $y->value);
  871. return $this->_normalize($temp);
  872. case MATH_BIGINTEGER_MODE_BCMATH:
  873. $temp = new static();
  874. $temp->value = bcsub($this->value, $y->value, 0);
  875. return $this->_normalize($temp);
  876. }
  877. $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative);
  878. $result = new static();
  879. $result->value = $temp[MATH_BIGINTEGER_VALUE];
  880. $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  881. return $this->_normalize($result);
  882. }
  883. /**
  884. * Performs subtraction.
  885. *
  886. * @param Array $x_value
  887. * @param Boolean $x_negative
  888. * @param Array $y_value
  889. * @param Boolean $y_negative
  890. * @return Array
  891. * @access private
  892. */
  893. function _subtract($x_value, $x_negative, $y_value, $y_negative)
  894. {
  895. $x_size = count($x_value);
  896. $y_size = count($y_value);
  897. if ($x_size == 0) {
  898. return array(
  899. MATH_BIGINTEGER_VALUE => $y_value,
  900. MATH_BIGINTEGER_SIGN => !$y_negative
  901. );
  902. } else if ($y_size == 0) {
  903. return array(
  904. MATH_BIGINTEGER_VALUE => $x_value,
  905. MATH_BIGINTEGER_SIGN => $x_negative
  906. );
  907. }
  908. // add, if appropriate (ie. -$x - +$y or +$x - -$y)
  909. if ( $x_negative != $y_negative ) {
  910. $temp = $this->_add($x_value, false, $y_value, false);
  911. $temp[MATH_BIGINTEGER_SIGN] = $x_negative;
  912. return $temp;
  913. }
  914. $diff = $this->_compare($x_value, $x_negative, $y_value, $y_negative);
  915. if ( !$diff ) {
  916. return array(
  917. MATH_BIGINTEGER_VALUE => array(),
  918. MATH_BIGINTEGER_SIGN => false
  919. );
  920. }
  921. // switch $x and $y around, if appropriate.
  922. if ( (!$x_negative && $diff < 0) || ($x_negative && $diff > 0) ) {
  923. $temp = $x_value;
  924. $x_value = $y_value;
  925. $y_value = $temp;
  926. $x_negative = !$x_negative;
  927. $x_size = count($x_value);
  928. $y_size = count($y_value);
  929. }
  930. // at this point, $x_value should be at least as big as - if not bigger than - $y_value
  931. $carry = 0;
  932. for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) {
  933. $sum = $x_value[$j] * MATH_BIGINTEGER_BASE_FULL + $x_value[$i] - $y_value[$j] * MATH_BIGINTEGER_BASE_FULL - $y_value[$i] - $carry;
  934. $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  935. $sum = $carry ? $sum + MATH_BIGINTEGER_MAX_DIGIT2 : $sum;
  936. $temp = MATH_BIGINTEGER_BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31);
  937. $x_value[$i] = (int) ($sum - MATH_BIGINTEGER_BASE_FULL * $temp);
  938. $x_value[$j] = $temp;
  939. }
  940. if ($j == $y_size) { // ie. if $y_size is odd
  941. $sum = $x_value[$i] - $y_value[$i] - $carry;
  942. $carry = $sum < 0;
  943. $x_value[$i] = $carry ? $sum + MATH_BIGINTEGER_BASE_FULL : $sum;
  944. ++$i;
  945. }
  946. if ($carry) {
  947. for (; !$x_value[$i]; ++$i) {
  948. $x_value[$i] = MATH_BIGINTEGER_MAX_DIGIT;
  949. }
  950. --$x_value[$i];
  951. }
  952. return array(
  953. MATH_BIGINTEGER_VALUE => $this->_trim($x_value),
  954. MATH_BIGINTEGER_SIGN => $x_negative
  955. );
  956. }
  957. /**
  958. * Multiplies two BigIntegers
  959. *
  960. * Here's an example:
  961. * <code>
  962. * <?php
  963. * $a = new \PHPSecLib\Math\BigInteger('10');
  964. * $b = new \PHPSecLib\Math\BigInteger('20');
  965. *
  966. * $c = $a->multiply($b);
  967. *
  968. * echo $c->toString(); // outputs 200
  969. * ?>
  970. * </code>
  971. *
  972. * @param \PHPSecLib\Math\BigInteger $x
  973. * @return \PHPSecLib\Math\BigInteger
  974. * @access public
  975. */
  976. function multiply($x)
  977. {
  978. switch ( MATH_BIGINTEGER_MODE ) {
  979. case MATH_BIGINTEGER_MODE_GMP:
  980. $temp = new static();
  981. $temp->value = gmp_mul($this->value, $x->value);
  982. return $this->_normalize($temp);
  983. case MATH_BIGINTEGER_MODE_BCMATH:
  984. $temp = new static();
  985. $temp->value = bcmul($this->value, $x->value, 0);
  986. return $this->_normalize($temp);
  987. }
  988. $temp = $this->_multiply($this->value, $this->is_negative, $x->value, $x->is_negative);
  989. $product = new static();
  990. $product->value = $temp[MATH_BIGINTEGER_VALUE];
  991. $product->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  992. return $this->_normalize($product);
  993. }
  994. /**
  995. * Performs multiplication.
  996. *
  997. * @param Array $x_value
  998. * @param Boolean $x_negative
  999. * @param Array $y_value
  1000. * @param Boolean $y_negative
  1001. * @return Array
  1002. * @access private
  1003. */
  1004. function _multiply($x_value, $x_negative, $y_value, $y_negative)
  1005. {
  1006. //if ( $x_value == $y_value ) {
  1007. // return array(
  1008. // MATH_BIGINTEGER_VALUE => $this->_square($x_value),
  1009. // MATH_BIGINTEGER_SIGN => $x_sign != $y_value
  1010. // );
  1011. //}
  1012. $x_length = count($x_value);
  1013. $y_length = count($y_value);
  1014. if ( !$x_length || !$y_length ) { // a 0 is being multiplied
  1015. return array(
  1016. MATH_BIGINTEGER_VALUE => array(),
  1017. MATH_BIGINTEGER_SIGN => false
  1018. );
  1019. }
  1020. return array(
  1021. MATH_BIGINTEGER_VALUE => min($x_length, $y_length) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
  1022. $this->_trim($this->_regularMultiply($x_value, $y_value)) :
  1023. $this->_trim($this->_karatsuba($x_value, $y_value)),
  1024. MATH_BIGINTEGER_SIGN => $x_negative != $y_negative
  1025. );
  1026. }
  1027. /**
  1028. * Performs long multiplication on two BigIntegers
  1029. *
  1030. * Modeled after 'multiply' in MutableBigInteger.java.
  1031. *
  1032. * @param Array $x_value
  1033. * @param Array $y_value
  1034. * @return Array
  1035. * @access private
  1036. */
  1037. function _regularMultiply($x_value, $y_value)
  1038. {
  1039. $x_length = count($x_value);
  1040. $y_length = count($y_value);
  1041. if ( !$x_length || !$y_length ) { // a 0 is being multiplied
  1042. return array();
  1043. }
  1044. if ( $x_length < $y_length ) {
  1045. $temp = $x_value;
  1046. $x_value = $y_value;
  1047. $y_value = $temp;
  1048. $x_length = count($x_value);
  1049. $y_length = count($y_value);
  1050. }
  1051. $product_value = $this->_array_repeat(0, $x_length + $y_length);
  1052. // the following for loop could be removed if the for loop following it
  1053. // (the one with nested for loops) initially set $i to 0, but
  1054. // doing so would also make the result in one set of unnecessary adds,
  1055. // since on the outermost loops first pass, $product->value[$k] is going
  1056. // to always be 0
  1057. $carry = 0;
  1058. for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0
  1059. $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
  1060. $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1061. $product_value[$j] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
  1062. }
  1063. $product_value[$j] = $carry;
  1064. // the above for loop is what the previous comment was talking about. the
  1065. // following for loop is the "one with nested for loops"
  1066. for ($i = 1; $i < $y_length; ++$i) {
  1067. $carry = 0;
  1068. for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) {
  1069. $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
  1070. $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1071. $product_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
  1072. }
  1073. $product_value[$k] = $carry;
  1074. }
  1075. return $product_value;
  1076. }
  1077. /**
  1078. * Performs Karatsuba multiplication on two BigIntegers
  1079. *
  1080. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1081. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}.
  1082. *
  1083. * @param Array $x_value
  1084. * @param Array $y_value
  1085. * @return Array
  1086. * @access private
  1087. */
  1088. function _karatsuba($x_value, $y_value)
  1089. {
  1090. $m = min(count($x_value) >> 1, count($y_value) >> 1);
  1091. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1092. return $this->_regularMultiply($x_value, $y_value);
  1093. }
  1094. $x1 = array_slice($x_value, $m);
  1095. $x0 = array_slice($x_value, 0, $m);
  1096. $y1 = array_slice($y_value, $m);
  1097. $y0 = array_slice($y_value, 0, $m);
  1098. $z2 = $this->_karatsuba($x1, $y1);
  1099. $z0 = $this->_karatsuba($x0, $y0);
  1100. $z1 = $this->_add($x1, false, $x0, false);
  1101. $temp = $this->_add($y1, false, $y0, false);
  1102. $z1 = $this->_karatsuba($z1[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_VALUE]);
  1103. $temp = $this->_add($z2, false, $z0, false);
  1104. $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
  1105. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1106. $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
  1107. $xy = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
  1108. $xy = $this->_add($xy[MATH_BIGINTEGER_VALUE], $xy[MATH_BIGINTEGER_SIGN], $z0, false);
  1109. return $xy[MATH_BIGINTEGER_VALUE];
  1110. }
  1111. /**
  1112. * Performs squaring
  1113. *
  1114. * @param Array $x
  1115. * @return Array
  1116. * @access private
  1117. */
  1118. function _square($x = false)
  1119. {
  1120. return count($x) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
  1121. $this->_trim($this->_baseSquare($x)) :
  1122. $this->_trim($this->_karatsubaSquare($x));
  1123. }
  1124. /**
  1125. * Performs traditional squaring on two BigIntegers
  1126. *
  1127. * Squaring can be done faster than multiplying a number by itself can be. See
  1128. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} /
  1129. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information.
  1130. *
  1131. * @param Array $value
  1132. * @return Array
  1133. * @access private
  1134. */
  1135. function _baseSquare($value)
  1136. {
  1137. if ( empty($value) ) {
  1138. return array();
  1139. }
  1140. $square_value = $this->_array_repeat(0, 2 * count($value));
  1141. for ($i = 0, $max_index = count($value) - 1; $i <= $max_index; ++$i) {
  1142. $i2 = $i << 1;
  1143. $temp = $square_value[$i2] + $value[$i] * $value[$i];
  1144. $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1145. $square_value[$i2] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
  1146. // note how we start from $i+1 instead of 0 as we do in multiplication.
  1147. for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) {
  1148. $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry;
  1149. $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1150. $square_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
  1151. }
  1152. // the following line can yield values larger 2**15. at this point, PHP should switch
  1153. // over to floats.
  1154. $square_value[$i + $max_index + 1] = $carry;
  1155. }
  1156. return $square_value;
  1157. }
  1158. /**
  1159. * Performs Karatsuba "squaring" on two BigIntegers
  1160. *
  1161. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1162. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}.
  1163. *
  1164. * @param Array $value
  1165. * @return Array
  1166. * @access private
  1167. */
  1168. function _karatsubaSquare($value)
  1169. {
  1170. $m = count($value) >> 1;
  1171. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1172. return $this->_baseSquare($value);
  1173. }
  1174. $x1 = array_slice($value, $m);
  1175. $x0 = array_slice($value, 0, $m);
  1176. $z2 = $this->_karatsubaSquare($x1);
  1177. $z0 = $this->_karatsubaSquare($x0);
  1178. $z1 = $this->_add($x1, false, $x0, false);
  1179. $z1 = $this->_karatsubaSquare($z1[MATH_BIGINTEGER_VALUE]);
  1180. $temp = $this->_add($z2, false, $z0, false);
  1181. $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
  1182. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1183. $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
  1184. $xx = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
  1185. $xx = $this->_add($xx[MATH_BIGINTEGER_VALUE], $xx[MATH_BIGINTEGER_SIGN], $z0, false);
  1186. return $xx[MATH_BIGINTEGER_VALUE];
  1187. }
  1188. /**
  1189. * Divides two BigIntegers.
  1190. *
  1191. * Returns an array whose first element contains the quotient and whose second element contains the
  1192. * "common residue". If the remainder would be positive, the "common residue" and the remainder are the
  1193. * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder
  1194. * and the divisor (basically, the "common residue" is the first positive modulo).
  1195. *
  1196. * Here's an example:
  1197. * <code>
  1198. * <?php
  1199. * $a = new \PHPSecLib\Math\BigInteger('10');
  1200. * $b = new \PHPSecLib\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 \PHPSecLib\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 static();
  1220. $remainder = new static();
  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 static();
  1228. $remainder = new static();
  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 static();
  1239. $remainder = new static();
  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 static();
  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 static();
  1257. $temp->value = array(1);
  1258. $temp->is_negative = $x_sign != $y_sign;
  1259. return array($this->_normalize($temp), $this->_normalize(new static()));
  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 static()), $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 static();

Large files files are truncated, but you can click here to view the full file