PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/application/third_party/google-api/vendor/phpseclib/phpseclib/phpseclib/Crypt/Random.php

https://gitlab.com/Anas7232/Layout-Changes
PHP | 274 lines | 139 code | 16 blank | 119 comment | 29 complexity | 93193a666526c63ba95629cd71504aef MD5 | raw file
  1. <?php
  2. /**
  3. * Random Number Generator
  4. *
  5. * PHP version 5
  6. *
  7. * Here's a short example of how to use this library:
  8. * <code>
  9. * <?php
  10. * include 'vendor/autoload.php';
  11. *
  12. * echo bin2hex(\phpseclib\Crypt\Random::string(8));
  13. * ?>
  14. * </code>
  15. *
  16. * @category Crypt
  17. * @package Random
  18. * @author Jim Wigginton <terrafrost@php.net>
  19. * @copyright 2007 Jim Wigginton
  20. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  21. * @link http://phpseclib.sourceforge.net
  22. */
  23. namespace phpseclib\Crypt;
  24. /**
  25. * Pure-PHP Random Number Generator
  26. *
  27. * @package Random
  28. * @author Jim Wigginton <terrafrost@php.net>
  29. * @access public
  30. */
  31. class Random
  32. {
  33. /**
  34. * Generate a random string.
  35. *
  36. * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
  37. * microoptimizations because this function has the potential of being called a huge number of times.
  38. * eg. for RSA key generation.
  39. *
  40. * @param int $length
  41. * @return string
  42. */
  43. static function string($length)
  44. {
  45. if (!$length) {
  46. return '';
  47. }
  48. if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
  49. try {
  50. return \random_bytes($length);
  51. } catch (\Throwable $e) {
  52. // If a sufficient source of randomness is unavailable, random_bytes() will throw an
  53. // object that implements the Throwable interface (Exception, TypeError, Error).
  54. // We don't actually need to do anything here. The string() method should just continue
  55. // as normal. Note, however, that if we don't have a sufficient source of randomness for
  56. // random_bytes(), most of the other calls here will fail too, so we'll end up using
  57. // the PHP implementation.
  58. }
  59. }
  60. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  61. // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
  62. // ie. class_alias is a function that was introduced in PHP 5.3
  63. if (extension_loaded('mcrypt') && function_exists('class_alias')) {
  64. return @mcrypt_create_iv($length);
  65. }
  66. // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
  67. // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
  68. // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
  69. // call php_win32_get_random_bytes():
  70. //
  71. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
  72. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
  73. //
  74. // php_win32_get_random_bytes() is defined thusly:
  75. //
  76. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
  77. //
  78. // we're calling it, all the same, in the off chance that the mcrypt extension is not available
  79. if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
  80. return openssl_random_pseudo_bytes($length);
  81. }
  82. } else {
  83. // method 1. the fastest
  84. if (extension_loaded('openssl')) {
  85. return openssl_random_pseudo_bytes($length);
  86. }
  87. // method 2
  88. static $fp = true;
  89. if ($fp === true) {
  90. // warning's will be output unles the error suppression operator is used. errors such as
  91. // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
  92. $fp = @fopen('/dev/urandom', 'rb');
  93. }
  94. if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
  95. return fread($fp, $length);
  96. }
  97. // method 3. pretty much does the same thing as method 2 per the following url:
  98. // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
  99. // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
  100. // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
  101. // restrictions or some such
  102. if (extension_loaded('mcrypt')) {
  103. return @mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  104. }
  105. }
  106. // at this point we have no choice but to use a pure-PHP CSPRNG
  107. // cascade entropy across multiple PHP instances by fixing the session and collecting all
  108. // environmental variables, including the previous session data and the current session
  109. // data.
  110. //
  111. // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
  112. // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
  113. // PHP isn't low level to be able to use those as sources and on a web server there's not likely
  114. // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
  115. // however, a ton of people visiting the website. obviously you don't want to base your seeding
  116. // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
  117. // by the user and (2) this isn't just looking at the data sent by the current user - it's based
  118. // on the data sent by all users. one user requests the page and a hash of their info is saved.
  119. // another user visits the page and the serialization of their data is utilized along with the
  120. // server envirnment stuff and a hash of the previous http request data (which itself utilizes
  121. // a hash of the session data before that). certainly an attacker should be assumed to have
  122. // full control over his own http requests. he, however, is not going to have control over
  123. // everyone's http requests.
  124. static $crypto = false, $v;
  125. if ($crypto === false) {
  126. // save old session data
  127. $old_session_id = session_id();
  128. $old_use_cookies = ini_get('session.use_cookies');
  129. $old_session_cache_limiter = session_cache_limiter();
  130. $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
  131. if ($old_session_id != '') {
  132. session_write_close();
  133. }
  134. session_id(1);
  135. ini_set('session.use_cookies', 0);
  136. session_cache_limiter('');
  137. session_start();
  138. $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
  139. (isset($_SERVER) ? phpseclib_safe_serialize($_SERVER) : '') .
  140. (isset($_POST) ? phpseclib_safe_serialize($_POST) : '') .
  141. (isset($_GET) ? phpseclib_safe_serialize($_GET) : '') .
  142. (isset($_COOKIE) ? phpseclib_safe_serialize($_COOKIE) : '') .
  143. phpseclib_safe_serialize($GLOBALS) .
  144. phpseclib_safe_serialize($_SESSION) .
  145. phpseclib_safe_serialize($_OLD_SESSION)
  146. ));
  147. if (!isset($_SESSION['count'])) {
  148. $_SESSION['count'] = 0;
  149. }
  150. $_SESSION['count']++;
  151. session_write_close();
  152. // restore old session data
  153. if ($old_session_id != '') {
  154. session_id($old_session_id);
  155. session_start();
  156. ini_set('session.use_cookies', $old_use_cookies);
  157. session_cache_limiter($old_session_cache_limiter);
  158. } else {
  159. if ($_OLD_SESSION !== false) {
  160. $_SESSION = $_OLD_SESSION;
  161. unset($_OLD_SESSION);
  162. } else {
  163. unset($_SESSION);
  164. }
  165. }
  166. // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
  167. // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C.
  168. // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
  169. // original hash and the current hash. we'll be emulating that. for more info see the following URL:
  170. //
  171. // http://tools.ietf.org/html/rfc4253#section-7.2
  172. //
  173. // see the is_string($crypto) part for an example of how to expand the keys
  174. $key = pack('H*', sha1($seed . 'A'));
  175. $iv = pack('H*', sha1($seed . 'C'));
  176. // ciphers are used as per the nist.gov link below. also, see this link:
  177. //
  178. // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
  179. switch (true) {
  180. case class_exists('\phpseclib\Crypt\AES'):
  181. $crypto = new AES(Base::MODE_CTR);
  182. break;
  183. case class_exists('\phpseclib\Crypt\Twofish'):
  184. $crypto = new Twofish(Base::MODE_CTR);
  185. break;
  186. case class_exists('\phpseclib\Crypt\Blowfish'):
  187. $crypto = new Blowfish(Base::MODE_CTR);
  188. break;
  189. case class_exists('\phpseclib\Crypt\TripleDES'):
  190. $crypto = new TripleDES(Base::MODE_CTR);
  191. break;
  192. case class_exists('\phpseclib\Crypt\DES'):
  193. $crypto = new DES(Base::MODE_CTR);
  194. break;
  195. case class_exists('\phpseclib\Crypt\RC4'):
  196. $crypto = new RC4();
  197. break;
  198. default:
  199. user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
  200. return false;
  201. }
  202. $crypto->setKey($key);
  203. $crypto->setIV($iv);
  204. $crypto->enableContinuousBuffer();
  205. }
  206. //return $crypto->encrypt(str_repeat("\0", $length));
  207. // the following is based off of ANSI X9.31:
  208. //
  209. // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
  210. //
  211. // OpenSSL uses that same standard for it's random numbers:
  212. //
  213. // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
  214. // (do a search for "ANS X9.31 A.2.4")
  215. $result = '';
  216. while (strlen($result) < $length) {
  217. $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
  218. $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
  219. $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
  220. $result.= $r;
  221. }
  222. return substr($result, 0, $length);
  223. }
  224. }
  225. if (!function_exists('phpseclib_safe_serialize')) {
  226. /**
  227. * Safely serialize variables
  228. *
  229. * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier.
  230. * PHP 5.3 will emit a warning.
  231. *
  232. * @param mixed $arr
  233. * @access public
  234. */
  235. function phpseclib_safe_serialize(&$arr)
  236. {
  237. if (is_object($arr)) {
  238. return '';
  239. }
  240. if (!is_array($arr)) {
  241. return serialize($arr);
  242. }
  243. // prevent circular array recursion
  244. if (isset($arr['__phpseclib_marker'])) {
  245. return '';
  246. }
  247. $safearr = array();
  248. $arr['__phpseclib_marker'] = true;
  249. foreach (array_keys($arr) as $key) {
  250. // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage
  251. if ($key !== '__phpseclib_marker') {
  252. $safearr[$key] = phpseclib_safe_serialize($arr[$key]);
  253. }
  254. }
  255. unset($arr['__phpseclib_marker']);
  256. return serialize($safearr);
  257. }
  258. }