Skip to content

Commit

Permalink
Small optimizaions to random id generation
Browse files Browse the repository at this point in the history
Use serialize instead of implode to add a bit more variance, since the
location of array entries in the shuffled array (for now, only
sys_getloadavg()) can vary.
Add more random inputs (memory usage, Hash ID)
Use SHA1 instead of MD5 - since we need a 23 character string, MD5 only
gets us 22 base64 chars so using a random value from mt_rand() was only
providing 10 bytes of randomness in the 23rd char.
  • Loading branch information
slusarz committed Feb 20, 2015
1 parent f096ea0 commit b2c3ec0
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions framework/Support/lib/Horde/Support/Randomid.php
Expand Up @@ -36,20 +36,23 @@ public function __construct()
*/
public function generate()
{
$r = mt_rand();

$elts = array(
$r,
uniqid(),
getmypid()
mt_rand(),
getmypid(),
spl_object_hash($this)
);
if (function_exists('zend_thread_id')) {
$elts[] = zend_thread_id();
}
if (function_exists('sys_getloadavg') &&
$loadavg = sys_getloadavg()) {
($loadavg = sys_getloadavg())) {
$elts = array_merge($elts, $loadavg);
}
if (function_exists('memory_get_usage')) {
$elts[] = memory_get_usage();
$elts[] = memory_get_peak_usage();
}

shuffle($elts);

Expand All @@ -58,8 +61,8 @@ public function generate()
return substr(str_replace(
array('/', '+', '='),
array('-', '_', ''),
base64_encode(pack('H*', hash('md5', implode('', $elts))))
) . $r, 0, 23);
base64_encode(hash('sha1', serialize($elts), true))
), 0, 23);
}

/**
Expand Down

0 comments on commit b2c3ec0

Please sign in to comment.