2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
5 * Random Number Generator
9 * Here's a short example of how to use this library:
12 * include('Crypt/Random.php');
14 * echo crypt_random();
18 * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
19 * of this software and associated documentation files (the "Software"), to deal
20 * in the Software without restriction, including without limitation the rights
21 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22 * copies of the Software, and to permit persons to whom the Software is
23 * furnished to do so, subject to the following conditions:
25 * The above copyright notice and this permission notice shall be included in
26 * all copies or substantial portions of the Software.
28 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
37 * @package Crypt_Random
38 * @author Jim Wigginton <terrafrost@php.net>
39 * @copyright MMVII Jim Wigginton
40 * @license http://www.opensource.org/licenses/mit-license.html MIT License
41 * @version $Id: Random.php,v 1.9 2010/04/24 06:40:48 terrafrost Exp $
42 * @link http://phpseclib.sourceforge.net
46 * Generate a random value.
48 * On 32-bit machines, the largest distance that can exist between $min and $max is 2**31.
49 * If $min and $max are farther apart than that then the last ($max - range) numbers.
51 * Depending on how this is being used, it may be worth while to write a replacement. For example,
52 * a PHP-based web app that stores its data in an SQL database can collect more entropy than this function
55 * @param optional Integer $min
56 * @param optional Integer $max
60 function crypt_random($min = 0, $max = 0x7FFFFFFF)
66 if (function_exists('openssl_random_pseudo_bytes')) {
67 // openssl_random_pseudo_bytes() is slow on windows per the following:
68 // http://stackoverflow.com/questions/1940168/openssl-random-pseudo-bytes-is-slow-php
69 if ((PHP_OS
& "\xDF\xDF\xDF") !== 'WIN') { // PHP_OS & "\xDF\xDF\xDF" == strtoupper(substr(PHP_OS, 0, 3)), but a lot faster
70 extract(unpack('Nrandom', openssl_random_pseudo_bytes(4)));
72 return abs($random) %
($max - $min) +
$min;
76 // see http://en.wikipedia.org/wiki//dev/random
77 static $urandom = true;
78 if ($urandom === true) {
79 // Warning's will be output unles the error suppression operator is used. Errors such as
80 // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
81 $urandom = @fopen
('/dev/urandom', 'rb');
83 if (!is_bool($urandom)) {
84 extract(unpack('Nrandom', fread($urandom, 4)));
86 // say $min = 0 and $max = 3. if we didn't do abs() then we could have stuff like this:
87 // -4 % 3 + 0 = -1, even though -1 < $min
88 return abs($random) %
($max - $min) +
$min;
91 /* Prior to PHP 4.2.0, mt_srand() had to be called before mt_rand() could be called.
92 Prior to PHP 5.2.6, mt_rand()'s automatic seeding was subpar, as elaborated here:
94 http://www.suspekt.org/2008/08/17/mt_srand-and-not-so-random-numbers/
96 The seeding routine is pretty much ripped from PHP's own internal GENERATE_SEED() macro:
98 http://svn.php.net/viewvc/php/php-src/tags/php_5_3_2/ext/standard/php_rand.h?view=markup */
99 if (version_compare(PHP_VERSION
, '5.2.5', '<=')) {
101 if (!isset($seeded)) {
103 mt_srand(fmod(time() * getmypid(), 0x7FFFFFFF) ^
fmod(1000000 * lcg_value(), 0x7FFFFFFF));
109 // The CSPRNG's Yarrow and Fortuna periodically reseed. This function can be reseeded by hitting F5
110 // in the browser and reloading the page.
112 if (!isset($crypto)) {
114 for ($i = 0; $i < 8; $i++
) {
115 $key.= pack('n', mt_rand(0, 0xFFFF));
116 $iv .= pack('n', mt_rand(0, 0xFFFF));
119 case class_exists('Crypt_AES'):
120 $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR
);
122 case class_exists('Crypt_TripleDES'):
123 $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR
);
125 case class_exists('Crypt_DES'):
126 $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR
);
128 case class_exists('Crypt_RC4'):
129 $crypto = new Crypt_RC4();
132 extract(unpack('Nrandom', pack('H*', sha1(mt_rand(0, 0x7FFFFFFF)))));
133 return abs($random) %
($max - $min) +
$min;
135 $crypto->setKey($key);
137 $crypto->enableContinuousBuffer();
140 extract(unpack('Nrandom', $crypto->encrypt("\0\0\0\0")));
141 return abs($random) %
($max - $min) +
$min;