61 if (function_exists(
'openssl_random_pseudo_bytes')
62 && (version_compare(PHP_VERSION,
'5.3.4') >= 0 || substr(PHP_OS, 0, 3) !==
'WIN')) {
63 $SSLstr = openssl_random_pseudo_bytes($length, $strong);
77 if (function_exists(
'mcrypt_create_iv')
78 && (version_compare(PHP_VERSION,
'5.3.7') >= 0 || substr(PHP_OS, 0, 3) !==
'WIN')) {
79 $str = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
94 $msec_per_round = 400;
98 $handle = @fopen(
'/dev/urandom',
'rb');
99 if ($handle && function_exists(
'stream_set_read_buffer')) {
100 @stream_set_read_buffer($handle, 0);
104 $bytes = ($total > $hash_len) ? $hash_len : $total;
108 $entropy = rand() . uniqid(mt_rand(),
true) . $SSLstr;
109 $entropy .= implode(
'', @fstat(@fopen(__FILE__,
'r')));
110 $entropy .= memory_get_usage() . getmypid();
111 $entropy .= serialize($_ENV) . serialize($_SERVER);
112 if (function_exists(
'posix_times')) {
113 $entropy .= serialize(posix_times());
115 if (function_exists(
'zend_thread_id')) {
116 $entropy .= zend_thread_id();
120 $entropy .= @fread($handle, $bytes);
123 for ($i = 0; $i < 3; $i++) {
124 $c1 = microtime(
true);
125 $var = sha1(mt_rand());
126 for ($j = 0; $j < 50; $j++) {
129 $c2 = microtime(
true);
130 $entropy .= $c1 . $c2;
135 $rounds = (int) ($msec_per_round * 50 / (
int) (($c2 - $c1) * 1000000));
139 $iter = $bytes * (int) (ceil(8 / $bits_per_round));
141 for ($i = 0; $i < $iter; $i++) {
143 $var = sha1(mt_rand());
144 for ($j = 0; $j < $rounds; $j++) {
148 $entropy .= $c1 . $c2;
153 $str .= sha1($entropy,
true);
155 }
while ($length > strlen($str));
161 return substr($str, 0, $length);
185 throw new InvalidArgumentException(
'Length should be >= 1');
189 $numBytes = ceil($length * 0.75);
191 $string = substr(rtrim(base64_encode($bytes),
'='), 0, $length);
194 return strtr(
$string,
'+/',
'-_');
197 if ($chars == self::CHARS_HEX) {
200 return substr(bin2hex($bytes), 0, $length);
203 $listLen = strlen($chars);
206 return str_repeat($chars, $length);
212 for ($i = 0; $i < $length; $i++) {
213 $pos = ($pos + ord($bytes[$i])) % $listLen;
const CHARS_PASSWORD
Character set for temp passwords (no risk of embedded profanity/glyphs that look similar) ...
getRandomBytes($length)
Generate a string of highly randomized bytes (over the full 8-bit range).
const CHARS_HEX
Character set for hexadecimal.
getRandomString($length, $chars=null)
Generate a random string of specified length.