| 1 |
<?php |
<?php |
| 2 |
// $Id: common.inc,v 1.760 2008/03/17 17:01:05 dries Exp $ |
// $Id: common.inc,v 1.761 2008/03/31 18:17:21 dries Exp $ |
| 3 |
|
|
| 4 |
/** |
/** |
| 5 |
* @file |
* @file |
| 2308 |
} |
} |
| 2309 |
|
|
| 2310 |
/** |
/** |
| 2311 |
|
* Returns a string of highly randomized bytes (over the full 8-bit range). |
| 2312 |
|
* |
| 2313 |
|
* This function is better than simply calling mt_rand() or any other built-in |
| 2314 |
|
* PHP function because it can return a long string of bytes (compared to < 4 |
| 2315 |
|
* bytes normally from mt_rand()) and uses the best available pseudo-random source. |
| 2316 |
|
* |
| 2317 |
|
* @param $count |
| 2318 |
|
* The number of characters (bytes) to return in the string. |
| 2319 |
|
*/ |
| 2320 |
|
function drupal_random_bytes($count) { |
| 2321 |
|
static $random_state; |
| 2322 |
|
// We initialize with the somewhat random PHP process ID on the first call. |
| 2323 |
|
if (empty($random_state)) { |
| 2324 |
|
$random_state = getmypid(); |
| 2325 |
|
} |
| 2326 |
|
$output = ''; |
| 2327 |
|
// /dev/urandom is available on many *nix systems and is considered the best |
| 2328 |
|
// commonly available pseudo-random source. |
| 2329 |
|
if ($fh = @fopen('/dev/urandom', 'rb')) { |
| 2330 |
|
$output = fread($fh, $count); |
| 2331 |
|
fclose($fh); |
| 2332 |
|
} |
| 2333 |
|
// If /dev/urandom is not available or returns no bytes, this loop will |
| 2334 |
|
// generate a good set of pseudo-random bytes on any system. |
| 2335 |
|
// Note that it may be important that our $random_state is passed |
| 2336 |
|
// through md5() prior to being rolled into $output, that the two md5() |
| 2337 |
|
// invocations are different, and that the extra input into the first one - |
| 2338 |
|
// the microtime() - is prepended rather than appended. This is to avoid |
| 2339 |
|
// directly leaking $random_state via the $output stream, which could |
| 2340 |
|
// allow for trivial prediction of further "random" numbers. |
| 2341 |
|
while (strlen($output) < $count) { |
| 2342 |
|
$random_state = md5(microtime() . mt_rand() . $random_state); |
| 2343 |
|
$output .= md5(mt_rand() . $random_state, TRUE); |
| 2344 |
|
} |
| 2345 |
|
return substr($output, 0, $count); |
| 2346 |
|
} |
| 2347 |
|
|
| 2348 |
|
/** |
| 2349 |
* Ensure the private key variable used to generate tokens is set. |
* Ensure the private key variable used to generate tokens is set. |
| 2350 |
* |
* |
| 2351 |
* @return |
* @return |
| 2353 |
*/ |
*/ |
| 2354 |
function drupal_get_private_key() { |
function drupal_get_private_key() { |
| 2355 |
if (!($key = variable_get('drupal_private_key', 0))) { |
if (!($key = variable_get('drupal_private_key', 0))) { |
| 2356 |
$key = md5(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true)); |
$key = md5(drupal_random_bytes(64)); |
| 2357 |
variable_set('drupal_private_key', $key); |
variable_set('drupal_private_key', $key); |
| 2358 |
} |
} |
| 2359 |
return $key; |
return $key; |