PageRenderTime 93ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

/plugins/authentication/openid/openid/Auth/OpenID/BigMath.php

https://github.com/cosmocommerce/joomla
PHP | 471 lines | 261 code | 72 blank | 138 comment | 30 complexity | a56dc458f1ef222812912f79ec393b4a MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * BigMath: A math library wrapper that abstracts out the underlying
  4. * long integer library.
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * LICENSE: See the COPYING file included in this distribution.
  9. *
  10. * @access private
  11. * @package OpenID
  12. * @author JanRain, Inc. <openid@janrain.com>
  13. * @copyright 2005-2008 Janrain, Inc.
  14. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
  15. */
  16. /**
  17. * Needed for random number generation
  18. */
  19. require_once 'Auth/OpenID/CryptUtil.php';
  20. /**
  21. * Need Auth_OpenID::bytes().
  22. */
  23. require_once 'Auth/OpenID.php';
  24. /**
  25. * The superclass of all big-integer math implementations
  26. * @access private
  27. * @package OpenID
  28. */
  29. class Auth_OpenID_MathLibrary {
  30. /**
  31. * Given a long integer, returns the number converted to a binary
  32. * string. This function accepts long integer values of arbitrary
  33. * magnitude and uses the local large-number math library when
  34. * available.
  35. *
  36. * @param integer $long The long number (can be a normal PHP
  37. * integer or a number created by one of the available long number
  38. * libraries)
  39. * @return string $binary The binary version of $long
  40. */
  41. function longToBinary($long)
  42. {
  43. $cmp = $this->cmp($long, 0);
  44. if ($cmp < 0) {
  45. $msg = __FUNCTION__ . " takes only positive integers.";
  46. trigger_error($msg, E_USER_ERROR);
  47. return null;
  48. }
  49. if ($cmp == 0) {
  50. return "\x00";
  51. }
  52. $bytes = array();
  53. while ($this->cmp($long, 0) > 0) {
  54. array_unshift($bytes, $this->mod($long, 256));
  55. $long = $this->div($long, pow(2, 8));
  56. }
  57. if ($bytes && ($bytes[0] > 127)) {
  58. array_unshift($bytes, 0);
  59. }
  60. $string = '';
  61. foreach ($bytes as $byte) {
  62. $string .= pack('C', $byte);
  63. }
  64. return $string;
  65. }
  66. /**
  67. * Given a binary string, returns the binary string converted to a
  68. * long number.
  69. *
  70. * @param string $binary The binary version of a long number,
  71. * probably as a result of calling longToBinary
  72. * @return integer $long The long number equivalent of the binary
  73. * string $str
  74. */
  75. function binaryToLong($str)
  76. {
  77. if ($str === null) {
  78. return null;
  79. }
  80. // Use array_merge to return a zero-indexed array instead of a
  81. // one-indexed array.
  82. $bytes = array_merge(unpack('C*', $str));
  83. $n = $this->init(0);
  84. if ($bytes && ($bytes[0] > 127)) {
  85. trigger_error("bytesToNum works only for positive integers.",
  86. E_USER_WARNING);
  87. return null;
  88. }
  89. foreach ($bytes as $byte) {
  90. $n = $this->mul($n, pow(2, 8));
  91. $n = $this->add($n, $byte);
  92. }
  93. return $n;
  94. }
  95. function base64ToLong($str)
  96. {
  97. $b64 = base64_decode($str);
  98. if ($b64 === false) {
  99. return false;
  100. }
  101. return $this->binaryToLong($b64);
  102. }
  103. function longToBase64($str)
  104. {
  105. return base64_encode($this->longToBinary($str));
  106. }
  107. /**
  108. * Returns a random number in the specified range. This function
  109. * accepts $start, $stop, and $step values of arbitrary magnitude
  110. * and will utilize the local large-number math library when
  111. * available.
  112. *
  113. * @param integer $start The start of the range, or the minimum
  114. * random number to return
  115. * @param integer $stop The end of the range, or the maximum
  116. * random number to return
  117. * @param integer $step The step size, such that $result - ($step
  118. * * N) = $start for some N
  119. * @return integer $result The resulting randomly-generated number
  120. */
  121. function rand($stop)
  122. {
  123. static $duplicate_cache = array();
  124. // Used as the key for the duplicate cache
  125. $rbytes = $this->longToBinary($stop);
  126. if (array_key_exists($rbytes, $duplicate_cache)) {
  127. list($duplicate, $nbytes) = $duplicate_cache[$rbytes];
  128. } else {
  129. if ($rbytes[0] == "\x00") {
  130. $nbytes = Auth_OpenID::bytes($rbytes) - 1;
  131. } else {
  132. $nbytes = Auth_OpenID::bytes($rbytes);
  133. }
  134. $mxrand = $this->pow(256, $nbytes);
  135. // If we get a number less than this, then it is in the
  136. // duplicated range.
  137. $duplicate = $this->mod($mxrand, $stop);
  138. if (count($duplicate_cache) > 10) {
  139. $duplicate_cache = array();
  140. }
  141. $duplicate_cache[$rbytes] = array($duplicate, $nbytes);
  142. }
  143. do {
  144. $bytes = "\x00" . Auth_OpenID_CryptUtil::getBytes($nbytes);
  145. $n = $this->binaryToLong($bytes);
  146. // Keep looping if this value is in the low duplicated range
  147. } while ($this->cmp($n, $duplicate) < 0);
  148. return $this->mod($n, $stop);
  149. }
  150. }
  151. /**
  152. * Exposes BCmath math library functionality.
  153. *
  154. * {@link Auth_OpenID_BcMathWrapper} wraps the functionality provided
  155. * by the BCMath extension.
  156. *
  157. * @access private
  158. * @package OpenID
  159. */
  160. class Auth_OpenID_BcMathWrapper extends Auth_OpenID_MathLibrary{
  161. var $type = 'bcmath';
  162. function add($x, $y)
  163. {
  164. return bcadd($x, $y);
  165. }
  166. function sub($x, $y)
  167. {
  168. return bcsub($x, $y);
  169. }
  170. function pow($base, $exponent)
  171. {
  172. return bcpow($base, $exponent);
  173. }
  174. function cmp($x, $y)
  175. {
  176. return bccomp($x, $y);
  177. }
  178. function init($number, $base = 10)
  179. {
  180. return $number;
  181. }
  182. function mod($base, $modulus)
  183. {
  184. return bcmod($base, $modulus);
  185. }
  186. function mul($x, $y)
  187. {
  188. return bcmul($x, $y);
  189. }
  190. function div($x, $y)
  191. {
  192. return bcdiv($x, $y);
  193. }
  194. /**
  195. * Same as bcpowmod when bcpowmod is missing
  196. *
  197. * @access private
  198. */
  199. function _powmod($base, $exponent, $modulus)
  200. {
  201. $square = $this->mod($base, $modulus);
  202. $result = 1;
  203. while($this->cmp($exponent, 0) > 0) {
  204. if ($this->mod($exponent, 2)) {
  205. $result = $this->mod($this->mul($result, $square), $modulus);
  206. }
  207. $square = $this->mod($this->mul($square, $square), $modulus);
  208. $exponent = $this->div($exponent, 2);
  209. }
  210. return $result;
  211. }
  212. function powmod($base, $exponent, $modulus)
  213. {
  214. if (function_exists('bcpowmod')) {
  215. return bcpowmod($base, $exponent, $modulus);
  216. } else {
  217. return $this->_powmod($base, $exponent, $modulus);
  218. }
  219. }
  220. function toString($num)
  221. {
  222. return $num;
  223. }
  224. }
  225. /**
  226. * Exposes GMP math library functionality.
  227. *
  228. * {@link Auth_OpenID_GmpMathWrapper} wraps the functionality provided
  229. * by the GMP extension.
  230. *
  231. * @access private
  232. * @package OpenID
  233. */
  234. class Auth_OpenID_GmpMathWrapper extends Auth_OpenID_MathLibrary{
  235. var $type = 'gmp';
  236. function add($x, $y)
  237. {
  238. return gmp_add($x, $y);
  239. }
  240. function sub($x, $y)
  241. {
  242. return gmp_sub($x, $y);
  243. }
  244. function pow($base, $exponent)
  245. {
  246. return gmp_pow($base, $exponent);
  247. }
  248. function cmp($x, $y)
  249. {
  250. return gmp_cmp($x, $y);
  251. }
  252. function init($number, $base = 10)
  253. {
  254. return gmp_init($number, $base);
  255. }
  256. function mod($base, $modulus)
  257. {
  258. return gmp_mod($base, $modulus);
  259. }
  260. function mul($x, $y)
  261. {
  262. return gmp_mul($x, $y);
  263. }
  264. function div($x, $y)
  265. {
  266. return gmp_div_q($x, $y);
  267. }
  268. function powmod($base, $exponent, $modulus)
  269. {
  270. return gmp_powm($base, $exponent, $modulus);
  271. }
  272. function toString($num)
  273. {
  274. return gmp_strval($num);
  275. }
  276. }
  277. /**
  278. * Define the supported extensions. An extension array has keys
  279. * 'modules', 'extension', and 'class'. 'modules' is an array of PHP
  280. * module names which the loading code will attempt to load. These
  281. * values will be suffixed with a library file extension (e.g. ".so").
  282. * 'extension' is the name of a PHP extension which will be tested
  283. * before 'modules' are loaded. 'class' is the string name of a
  284. * {@link Auth_OpenID_MathWrapper} subclass which should be
  285. * instantiated if a given extension is present.
  286. *
  287. * You can define new math library implementations and add them to
  288. * this array.
  289. */
  290. function Auth_OpenID_math_extensions()
  291. {
  292. $result = array();
  293. if (!defined('Auth_OpenID_BUGGY_GMP')) {
  294. $result[] =
  295. array('modules' => array('gmp', 'php_gmp'),
  296. 'extension' => 'gmp',
  297. 'class' => 'Auth_OpenID_GmpMathWrapper');
  298. }
  299. $result[] = array(
  300. 'modules' => array('bcmath', 'php_bcmath'),
  301. 'extension' => 'bcmath',
  302. 'class' => 'Auth_OpenID_BcMathWrapper');
  303. return $result;
  304. }
  305. /**
  306. * Detect which (if any) math library is available
  307. */
  308. function Auth_OpenID_detectMathLibrary($exts)
  309. {
  310. $loaded = false;
  311. foreach ($exts as $extension) {
  312. // See if the extension specified is already loaded.
  313. if ($extension['extension'] &&
  314. extension_loaded($extension['extension'])) {
  315. $loaded = true;
  316. }
  317. // Try to load dynamic modules.
  318. if (!$loaded) {
  319. foreach ($extension['modules'] as $module) {
  320. if (@dl($module . "." . PHP_SHLIB_SUFFIX)) {
  321. $loaded = true;
  322. break;
  323. }
  324. }
  325. }
  326. // If the load succeeded, supply an instance of
  327. // Auth_OpenID_MathWrapper which wraps the specified
  328. // module's functionality.
  329. if ($loaded) {
  330. return $extension;
  331. }
  332. }
  333. return false;
  334. }
  335. /**
  336. * {@link Auth_OpenID_getMathLib} checks for the presence of long
  337. * number extension modules and returns an instance of
  338. * {@link Auth_OpenID_MathWrapper} which exposes the module's
  339. * functionality.
  340. *
  341. * Checks for the existence of an extension module described by the
  342. * result of {@link Auth_OpenID_math_extensions()} and returns an
  343. * instance of a wrapper for that extension module. If no extension
  344. * module is found, an instance of {@link Auth_OpenID_MathWrapper} is
  345. * returned, which wraps the native PHP integer implementation. The
  346. * proper calling convention for this method is $lib =&
  347. * Auth_OpenID_getMathLib().
  348. *
  349. * This function checks for the existence of specific long number
  350. * implementations in the following order: GMP followed by BCmath.
  351. *
  352. * @return Auth_OpenID_MathWrapper $instance An instance of
  353. * {@link Auth_OpenID_MathWrapper} or one of its subclasses
  354. *
  355. * @package OpenID
  356. */
  357. function &Auth_OpenID_getMathLib()
  358. {
  359. // The instance of Auth_OpenID_MathWrapper that we choose to
  360. // supply will be stored here, so that subseqent calls to this
  361. // method will return a reference to the same object.
  362. static $lib = null;
  363. if (isset($lib)) {
  364. return $lib;
  365. }
  366. if (Auth_OpenID_noMathSupport()) {
  367. $null = null;
  368. return $null;
  369. }
  370. // If this method has not been called before, look at
  371. // Auth_OpenID_math_extensions and try to find an extension that
  372. // works.
  373. $ext = Auth_OpenID_detectMathLibrary(Auth_OpenID_math_extensions());
  374. if ($ext === false) {
  375. $tried = array();
  376. foreach (Auth_OpenID_math_extensions() as $extinfo) {
  377. $tried[] = $extinfo['extension'];
  378. }
  379. $triedstr = implode(", ", $tried);
  380. Auth_OpenID_setNoMathSupport();
  381. $result = null;
  382. return $result;
  383. }
  384. // Instantiate a new wrapper
  385. $class = $ext['class'];
  386. $lib = new $class();
  387. return $lib;
  388. }
  389. function Auth_OpenID_setNoMathSupport()
  390. {
  391. if (!defined('Auth_OpenID_NO_MATH_SUPPORT')) {
  392. define('Auth_OpenID_NO_MATH_SUPPORT', true);
  393. }
  394. }
  395. function Auth_OpenID_noMathSupport()
  396. {
  397. return defined('Auth_OpenID_NO_MATH_SUPPORT');
  398. }
  399. ?>