Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / phpseclib / Crypt / Random.php
blob0277393131c4a419bddd3c0713af32c79b59a00c
1 <?php
3 /**
4 * Random Number Generator
6 * PHP versions 4 and 5
8 * Here's a short example of how to use this library:
9 * <code>
10 * <?php
11 * include 'Crypt/Random.php';
13 * echo bin2hex(crypt_random_string(8));
14 * ?>
15 * </code>
17 * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
18 * of this software and associated documentation files (the "Software"), to deal
19 * in the Software without restriction, including without limitation the rights
20 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21 * copies of the Software, and to permit persons to whom the Software is
22 * furnished to do so, subject to the following conditions:
24 * The above copyright notice and this permission notice shall be included in
25 * all copies or substantial portions of the Software.
27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33 * THE SOFTWARE.
35 * @category Crypt
36 * @package Crypt_Random
37 * @author Jim Wigginton <terrafrost@php.net>
38 * @copyright MMVII Jim Wigginton
39 * @license http://www.opensource.org/licenses/mit-license.html MIT License
40 * @link http://phpseclib.sourceforge.net
43 // laravel is a PHP framework that utilizes phpseclib. laravel workbenches may, independently,
44 // have phpseclib as a requirement as well. if you're developing such a program you may encounter
45 // a "Cannot redeclare crypt_random_string()" error.
46 if (!function_exists('crypt_random_string')) {
47 /**
48 * "Is Windows" test
50 * @access private
52 define('CRYPT_RANDOM_IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
54 /**
55 * Generate a random string.
57 * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
58 * microoptimizations because this function has the potential of being called a huge number of times.
59 * eg. for RSA key generation.
61 * @param Integer $length
62 * @return String
63 * @access public
65 function crypt_random_string($length)
67 if (CRYPT_RANDOM_IS_WINDOWS) {
68 // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
69 // ie. class_alias is a function that was introduced in PHP 5.3
70 if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
71 return mcrypt_create_iv($length);
73 // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
74 // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
75 // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
76 // call php_win32_get_random_bytes():
78 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
79 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
81 // php_win32_get_random_bytes() is defined thusly:
83 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
85 // we're calling it, all the same, in the off chance that the mcrypt extension is not available
86 if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
87 return openssl_random_pseudo_bytes($length);
89 } else {
90 // method 1. the fastest
91 if (function_exists('openssl_random_pseudo_bytes')) {
92 return openssl_random_pseudo_bytes($length);
94 // method 2
95 static $fp = true;
96 if ($fp === true) {
97 // warning's will be output unles the error suppression operator is used. errors such as
98 // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
99 $fp = @fopen('/dev/urandom', 'rb');
101 if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
102 return fread($fp, $length);
104 // method 3. pretty much does the same thing as method 2 per the following url:
105 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
106 // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
107 // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
108 // restrictions or some such
109 if (function_exists('mcrypt_create_iv')) {
110 return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
113 // at this point we have no choice but to use a pure-PHP CSPRNG
115 // cascade entropy across multiple PHP instances by fixing the session and collecting all
116 // environmental variables, including the previous session data and the current session
117 // data.
119 // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
120 // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
121 // PHP isn't low level to be able to use those as sources and on a web server there's not likely
122 // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
123 // however. a ton of people visiting the website. obviously you don't want to base your seeding
124 // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
125 // by the user and (2) this isn't just looking at the data sent by the current user - it's based
126 // on the data sent by all users. one user requests the page and a hash of their info is saved.
127 // another user visits the page and the serialization of their data is utilized along with the
128 // server envirnment stuff and a hash of the previous http request data (which itself utilizes
129 // a hash of the session data before that). certainly an attacker should be assumed to have
130 // full control over his own http requests. he, however, is not going to have control over
131 // everyone's http requests.
132 static $crypto = false, $v;
133 if ($crypto === false) {
134 // save old session data
135 $old_session_id = session_id();
136 $old_use_cookies = ini_get('session.use_cookies');
137 $old_session_cache_limiter = session_cache_limiter();
138 $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
139 if ($old_session_id != '') {
140 session_write_close();
143 session_id(1);
144 ini_set('session.use_cookies', 0);
145 session_cache_limiter('');
146 session_start();
148 $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
149 serialize($_SERVER) .
150 serialize($_POST) .
151 serialize($_GET) .
152 serialize($_COOKIE) .
153 serialize($GLOBALS) .
154 serialize($_SESSION) .
155 serialize($_OLD_SESSION)
157 if (!isset($_SESSION['count'])) {
158 $_SESSION['count'] = 0;
160 $_SESSION['count']++;
162 session_write_close();
164 // restore old session data
165 if ($old_session_id != '') {
166 session_id($old_session_id);
167 session_start();
168 ini_set('session.use_cookies', $old_use_cookies);
169 session_cache_limiter($old_session_cache_limiter);
170 } else {
171 if ($_OLD_SESSION !== false) {
172 $_SESSION = $_OLD_SESSION;
173 unset($_OLD_SESSION);
174 } else {
175 unset($_SESSION);
179 // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
180 // 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.
181 // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
182 // original hash and the current hash. we'll be emulating that. for more info see the following URL:
184 // http://tools.ietf.org/html/rfc4253#section-7.2
186 // see the is_string($crypto) part for an example of how to expand the keys
187 $key = pack('H*', sha1($seed . 'A'));
188 $iv = pack('H*', sha1($seed . 'C'));
190 // ciphers are used as per the nist.gov link below. also, see this link:
192 // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
193 switch (true) {
194 case class_exists('Crypt_AES'):
195 $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);
196 break;
197 case class_exists('Crypt_TripleDES'):
198 $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
199 break;
200 case class_exists('Crypt_DES'):
201 $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);
202 break;
203 case class_exists('Crypt_RC4'):
204 $crypto = new Crypt_RC4();
205 break;
206 default:
207 $crypto = $seed;
208 return crypt_random_string($length);
211 $crypto->setKey($key);
212 $crypto->setIV($iv);
213 $crypto->enableContinuousBuffer();
216 if (is_string($crypto)) {
217 // the following is based off of ANSI X9.31:
219 // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
221 // OpenSSL uses that same standard for it's random numbers:
223 // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
224 // (do a search for "ANS X9.31 A.2.4")
226 // ANSI X9.31 recommends ciphers be used and phpseclib does use them if they're available (see
227 // later on in the code) but if they're not we'll use sha1
228 $result = '';
229 while (strlen($result) < $length) { // each loop adds 20 bytes
230 // microtime() isn't packed as "densely" as it could be but then neither is that the idea.
231 // the idea is simply to ensure that each "block" has a unique element to it.
232 $i = pack('H*', sha1(microtime()));
233 $r = pack('H*', sha1($i ^ $v));
234 $v = pack('H*', sha1($r ^ $i));
235 $result.= $r;
237 return substr($result, 0, $length);
240 //return $crypto->encrypt(str_repeat("\0", $length));
242 $result = '';
243 while (strlen($result) < $length) {
244 $i = $crypto->encrypt(microtime());
245 $r = $crypto->encrypt($i ^ $v);
246 $v = $crypto->encrypt($r ^ $i);
247 $result.= $r;
249 return substr($result, 0, $length);