4 * Random Number Generator
6 * The idea behind this function is that it can be easily replaced with your own crypt_random_string()
7 * function. eg. maybe you have a better source of entropy for creating the initial states or whatever.
11 * Here's a short example of how to use this library:
14 * include 'Crypt/Random.php';
16 * echo bin2hex(crypt_random_string(8));
20 * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
21 * of this software and associated documentation files (the "Software"), to deal
22 * in the Software without restriction, including without limitation the rights
23 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24 * copies of the Software, and to permit persons to whom the Software is
25 * furnished to do so, subject to the following conditions:
27 * The above copyright notice and this permission notice shall be included in
28 * all copies or substantial portions of the Software.
30 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
32 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
33 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
34 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
35 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * @package Crypt_Random
40 * @author Jim Wigginton <terrafrost@php.net>
41 * @copyright 2007 Jim Wigginton
42 * @license http://www.opensource.org/licenses/mit-license.html MIT License
43 * @link http://phpseclib.sourceforge.net
46 // laravel is a PHP framework that utilizes phpseclib. laravel workbenches may, independently,
47 // have phpseclib as a requirement as well. if you're developing such a program you may encounter
48 // a "Cannot redeclare crypt_random_string()" error.
49 if (!function_exists('crypt_random_string')) {
55 define('CRYPT_RANDOM_IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
58 * Generate a random string.
60 * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
61 * microoptimizations because this function has the potential of being called a huge number of times.
62 * eg. for RSA key generation.
64 * @param Integer $length
68 function crypt_random_string($length)
70 if (CRYPT_RANDOM_IS_WINDOWS) {
71 // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
72 // ie. class_alias is a function that was introduced in PHP 5.3
73 if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
74 return mcrypt_create_iv($length);
76 // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
77 // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
78 // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
79 // call php_win32_get_random_bytes():
81 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
82 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
84 // php_win32_get_random_bytes() is defined thusly:
86 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
88 // we're calling it, all the same, in the off chance that the mcrypt extension is not available
89 if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
90 return openssl_random_pseudo_bytes($length);
93 // method 1. the fastest
94 if (function_exists('openssl_random_pseudo_bytes')) {
95 return openssl_random_pseudo_bytes($length);
100 // warning's will be output unles the error suppression operator is used. errors such as
101 // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
102 $fp = @fopen('/dev/urandom', 'rb');
104 if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
105 return fread($fp, $length);
107 // method 3. pretty much does the same thing as method 2 per the following url:
108 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
109 // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
110 // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
111 // restrictions or some such
112 if (function_exists('mcrypt_create_iv')) {
113 return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
116 // at this point we have no choice but to use a pure-PHP CSPRNG
118 // cascade entropy across multiple PHP instances by fixing the session and collecting all
119 // environmental variables, including the previous session data and the current session
122 // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
123 // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
124 // PHP isn't low level to be able to use those as sources and on a web server there's not likely
125 // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
126 // however, a ton of people visiting the website. obviously you don't want to base your seeding
127 // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
128 // by the user and (2) this isn't just looking at the data sent by the current user - it's based
129 // on the data sent by all users. one user requests the page and a hash of their info is saved.
130 // another user visits the page and the serialization of their data is utilized along with the
131 // server envirnment stuff and a hash of the previous http request data (which itself utilizes
132 // a hash of the session data before that). certainly an attacker should be assumed to have
133 // full control over his own http requests. he, however, is not going to have control over
134 // everyone's http requests.
135 static $crypto = false, $v;
136 if ($crypto === false) {
137 // save old session data
138 $old_session_id = session_id();
139 $old_use_cookies = ini_get('session.use_cookies');
140 $old_session_cache_limiter = session_cache_limiter();
141 $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
142 if ($old_session_id != '') {
143 session_write_close();
147 ini_set('session.use_cookies', 0);
148 session_cache_limiter('');
151 $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
152 serialize($_SERVER) .
155 serialize($_COOKIE) .
156 serialize($GLOBALS) .
157 serialize($_SESSION) .
158 serialize($_OLD_SESSION)
160 if (!isset($_SESSION['count'])) {
161 $_SESSION['count'] = 0;
163 $_SESSION['count']++;
165 session_write_close();
167 // restore old session data
168 if ($old_session_id != '') {
169 session_id($old_session_id);
171 ini_set('session.use_cookies', $old_use_cookies);
172 session_cache_limiter($old_session_cache_limiter);
174 if ($_OLD_SESSION !== false) {
175 $_SESSION = $_OLD_SESSION;
176 unset($_OLD_SESSION);
182 // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
183 // 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.
184 // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
185 // original hash and the current hash. we'll be emulating that. for more info see the following URL:
187 // http://tools.ietf.org/html/rfc4253#section-7.2
189 // see the is_string($crypto) part for an example of how to expand the keys
190 $key = pack('H*', sha1($seed . 'A'));
191 $iv = pack('H*', sha1($seed . 'C'));
193 // ciphers are used as per the nist.gov link below. also, see this link:
195 // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
197 case phpseclib_resolve_include_path('Crypt/AES.php'):
198 if (!class_exists('Crypt_AES')) {
199 include_once 'AES.php';
201 $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);
203 case phpseclib_resolve_include_path('Crypt/Twofish.php'):
204 if (!class_exists('Crypt_Twofish')) {
205 include_once 'Twofish.php';
207 $crypto = new Crypt_Twofish(CRYPT_TWOFISH_MODE_CTR);
209 case phpseclib_resolve_include_path('Crypt/Blowfish.php'):
210 if (!class_exists('Crypt_Blowfish')) {
211 include_once 'Blowfish.php';
213 $crypto = new Crypt_Blowfish(CRYPT_BLOWFISH_MODE_CTR);
215 case phpseclib_resolve_include_path('Crypt/TripleDES.php'):
216 if (!class_exists('Crypt_TripleDES')) {
217 include_once 'TripleDES.php';
219 $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
221 case phpseclib_resolve_include_path('Crypt/DES.php'):
222 if (!class_exists('Crypt_DES')) {
223 include_once 'DES.php';
225 $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);
227 case phpseclib_resolve_include_path('Crypt/RC4.php'):
228 if (!class_exists('Crypt_RC4')) {
229 include_once 'RC4.php';
231 $crypto = new Crypt_RC4();
234 user_error('crypt_random_string requires at least one symmetric cipher be loaded');
238 $crypto->setKey($key);
240 $crypto->enableContinuousBuffer();
243 //return $crypto->encrypt(str_repeat("\0", $length));
245 // the following is based off of ANSI X9.31:
247 // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
249 // OpenSSL uses that same standard for it's random numbers:
251 // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
252 // (do a search for "ANS X9.31 A.2.4")
254 while (strlen($result) < $length) {
255 $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
256 $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
257 $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
260 return substr($result, 0, $length);
264 if (!function_exists('phpseclib_resolve_include_path')) {
266 * Resolve filename against the include path.
268 * Wrapper around stream_resolve_include_path() (which was introduced in
269 * PHP 5.3.2) with fallback implementation for earlier PHP versions.
271 * @param string $filename
272 * @return mixed Filename (string) on success, false otherwise.
275 function phpseclib_resolve_include_path($filename)
277 if (function_exists('stream_resolve_include_path')) {
278 return stream_resolve_include_path($filename);
281 // handle non-relative paths
282 if (file_exists($filename)) {
283 return realpath($filename);
286 $paths = PATH_SEPARATOR == ':' ?
287 preg_split('#(?<!phar):#', get_include_path()) :
288 explode(PATH_SEPARATOR, get_include_path());
289 foreach ($paths as $prefix) {
290 // path's specified in include_path don't always end in /
291 $ds = substr($prefix, -1) == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR;
292 $file = $prefix . $ds . $filename;
293 if (file_exists($file)) {
294 return realpath($file);