/** * Commit new records. * * @return void */ public function commit() { $request = (object) array('pid' => getmypid(), 'threadid' => ZEND_THREAD_SAFE ? zend_thread_id() : null, 'uid' => getmyuid(), 'url' => $this->url->out_as_local_url(false), 'hostname' => gethostname(), 'memory' => memory_get_usage(), 'peakmemory' => memory_get_peak_usage()); // Not supported on Windows until PHP 7 if (function_exists('getrusage')) { $resourceusage = getrusage(); $request->numswaps = $resourceusage['ru_nswap']; $request->numpagefaults = $resourceusage['ru_majflt']; $request->usertime = $resourceusage['ru_utime.tv_usec']; } $request->id = $this->db->insert_record('telemetry_request', $request); foreach ($this->additionalstate as $collector) { $table = $collector->get_table(); $records = $collector->get_records(); foreach ($records as $record) { $record->requestid = $request->id; } $this->db->insert_records($table, $records); } }
/** * Generate a random ID. */ public function generate() { $pid = function_exists('zend_thread_id') ? zend_thread_id() : getmypid(); /* Base64 can have /, +, and = characters. Restrict to URL-safe * characters. */ return str_replace(array('/', '+', '='), array('-', '_', ''), base64_encode(pack('II', mt_rand(), crc32(php_uname('n'))) . pack('H*', uniqid() . sprintf('%04s', dechex($pid))))); }
function randomBytes($length = 16, $secure = true, $raw = true, $startEntropy = "", &$rounds = 0, &$drop = 0) { static $lastRandom = ""; $output = ""; $length = abs((int) $length); $secureValue = ""; $rounds = 0; $drop = 0; while (!isset($output[$length - 1])) { //some entropy, but works ^^ $weakEntropy = array(is_array($startEntropy) ? implode($startEntropy) : $startEntropy, serialize(stat(__FILE__)), __DIR__, PHP_OS, microtime(), (string) lcg_value(), (string) PHP_MAXPATHLEN, PHP_SAPI, (string) PHP_INT_MAX . "." . PHP_INT_SIZE, serialize($_SERVER), serialize(get_defined_constants()), get_current_user(), serialize(ini_get_all()), (string) memory_get_usage() . "." . memory_get_peak_usage(), php_uname(), phpversion(), extension_loaded("gmp") ? gmp_strval(gmp_random(4)) : microtime(), zend_version(), (string) getmypid(), (string) getmyuid(), (string) mt_rand(), (string) getmyinode(), (string) getmygid(), (string) rand(), function_exists("zend_thread_id") ? (string) zend_thread_id() : microtime(), var_export(@get_browser(), true), function_exists("getrusage") ? @implode(getrusage()) : microtime(), function_exists("sys_getloadavg") ? @implode(sys_getloadavg()) : microtime(), serialize(get_loaded_extensions()), sys_get_temp_dir(), (string) disk_free_space("."), (string) disk_total_space("."), uniqid(microtime(), true), file_exists("/proc/cpuinfo") ? file_get_contents("/proc/cpuinfo") : microtime()); shuffle($weakEntropy); $value = hash("sha512", implode($weakEntropy), true); $lastRandom .= $value; foreach ($weakEntropy as $k => $c) { //mixing entropy values with XOR and hash randomness extractor $value ^= hash("sha256", $c . microtime() . $k, true) . hash("sha256", mt_rand() . microtime() . $k . $c, true); $value ^= hash("sha512", (string) lcg_value() . $c . microtime() . $k, true); } unset($weakEntropy); if ($secure === true) { $strongEntropyValues = array(is_array($startEntropy) ? hash("sha512", $startEntropy[($rounds + $drop) % count($startEntropy)], true) : hash("sha512", $startEntropy, true), file_exists("/dev/urandom") ? fread(fopen("/dev/urandom", "rb"), 64) : str_repeat("", 64), (function_exists("openssl_random_pseudo_bytes") and version_compare(PHP_VERSION, "5.3.4", ">=")) ? openssl_random_pseudo_bytes(64) : str_repeat("", 64), function_exists("mcrypt_create_iv") ? mcrypt_create_iv(64, MCRYPT_DEV_URANDOM) : str_repeat("", 64), $value); $strongEntropy = array_pop($strongEntropyValues); foreach ($strongEntropyValues as $value) { $strongEntropy = $strongEntropy ^ $value; } $value = ""; //Von Neumann randomness extractor, increases entropy $bitcnt = 0; for ($j = 0; $j < 64; ++$j) { $a = ord($strongEntropy[$j]); for ($i = 0; $i < 8; $i += 2) { $b = ($a & 1 << $i) > 0 ? 1 : 0; if ($b != (($a & 1 << $i + 1) > 0 ? 1 : 0)) { $secureValue |= $b << $bitcnt; if ($bitcnt == 7) { $value .= chr($secureValue); $secureValue = 0; $bitcnt = 0; } else { ++$bitcnt; } ++$drop; } else { $drop += 2; } } } } $output .= substr($value, 0, min($length - strlen($output), $length)); unset($value); ++$rounds; } $lastRandom = hash("sha512", $lastRandom, true); return $raw === false ? bin2hex($output) : $output; }
/** * Generate a random UUID * * @see http://www.ietf.org/rfc/rfc4122.txt * @return RFC 4122 UUID */ public static function uuid() { $node = env('SERVER_ADDR'); if (strpos($node, ':') !== false) { if (substr_count($node, '::')) { $node = str_replace('::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node); } $node = explode(':', $node); $ipv6 = ''; foreach ($node as $id) { $ipv6 .= str_pad(base_convert($id, 16, 2), 16, 0, STR_PAD_LEFT); } $node = base_convert($ipv6, 2, 10); if (strlen($node) < 38) { $node = null; } else { $node = crc32($node); } } elseif (empty($node)) { $host = env('HOSTNAME'); if (empty($host)) { $host = env('HOST'); } if (!empty($host)) { $ip = gethostbyname($host); if ($ip === $host) { $node = crc32($host); } else { $node = ip2long($ip); } } } elseif ($node !== '127.0.0.1') { $node = ip2long($node); } else { $node = null; } if (empty($node)) { $node = crc32(Configure::read('Security.salt')); } if (function_exists('hphp_get_thread_id')) { $pid = hphp_get_thread_id(); } else { if (function_exists('zend_thread_id')) { $pid = zend_thread_id(); } else { $pid = getmypid(); } } if (!$pid || $pid > 65535) { $pid = mt_rand(0, 0xfff) | 0x4000; } list($timeMid, $timeLow) = explode(' ', microtime()); $uuid = sprintf("%08x-%04x-%04x-%02x%02x-%04x%08x", (int) $timeLow, (int) substr($timeMid, 2) & 0xffff, mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node); return $uuid; }
/** * Generate a 36-character RFC 4122 UUID, without the urn:uuid: prefix. * * @see http://www.ietf.org/rfc/rfc4122.txt * @see http://labs.omniti.com/alexandria/trunk/OmniTI/Util/UUID.php * * @return string */ public function generate() { list($time_mid, $time_low) = explode(' ', microtime()); $time_low = (int) $time_low; $time_mid = (int) substr($time_mid, 2) & 0xffff; $time_high = mt_rand(0, 0xfff) | 0x4000; $clock = mt_rand(0, 0x3fff) | 0x8000; $node_low = function_exists('zend_thread_id') ? zend_thread_id() : getmypid(); $node_high = isset($_SERVER['SERVER_ADDR']) ? ip2long($_SERVER['SERVER_ADDR']) : crc32(php_uname()); $node = bin2hex(pack('nN', $node_low, $node_high)); $this->_uuid = sprintf('%08x-%04x-%04x-%04x-%s', $time_low, $time_mid, $time_high, $clock, $node); }
/** * Generate a random ID. */ public function generate() { $r = mt_rand(); $elts = array($r, uniqid(), getmypid()); if (function_exists('zend_thread_id')) { $elts[] = zend_thread_id(); } if (function_exists('sys_getloadavg') && ($loadavg = sys_getloadavg())) { $elts = array_merge($elts, $loadavg); } shuffle($elts); /* Base64 can have /, +, and = characters. Restrict to URL-safe * characters. */ return substr(str_replace(array('/', '+', '='), array('-', '_', ''), base64_encode(pack('H*', hash('md5', implode('', $elts))))) . $r, 0, 23); }
/** * Generate a random ID. */ public function generate() { $elts = array(uniqid(), 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())) { $elts = array_merge($elts, $loadavg); } if (function_exists('memory_get_usage')) { $elts[] = memory_get_usage(); $elts[] = memory_get_peak_usage(); } shuffle($elts); /* Base64 can have /, +, and = characters. Restrict to URL-safe * characters. */ return substr(str_replace(array('/', '+', '='), array('-', '_', ''), base64_encode(hash('sha1', serialize($elts), true))), 0, 23); }
public function __construct() { $state = self::$state; if (function_exists('posix_times')) { $state .= serialize(posix_times()); } if (function_exists('zend_thread_id')) { $state .= zend_thread_id(); } $state .= getmypid() . memory_get_usage(); $state .= serialize($_ENV); $state .= serialize($_SERVER); $state .= count(debug_backtrace(false)); self::$state = hash('sha512', $state, true); if (is_null(self::$counter)) { list(, self::$counter) = unpack("i", substr(self::$state, 0, 4)); $seed = $this->generate(strlen(dechex(PHP_INT_MAX))); list(, self::$counter) = unpack("i", $seed); } }
/** * Generates a random UUID. * * @param mixed $context Used to determine the values for `'SERVER_ADDR'`, `'HOST'` * and `'HOSTNAME'`. Either a closure which is passed the requested context values, an * object with properties for each value or an array keyed by requested context value. * @return string An RFC 4122-compliant UUID. * @link http://www.ietf.org/rfc/rfc4122.txt */ public static function uuid($context) { $val = function ($value) use($context) { switch (true) { case is_object($context) && is_callable($context): $result = $context($value); break; case is_object($context): $result = isset($context->{$value}) ? $context->{$value} : null; break; case is_array($context): $result = isset($context[$value]) ? $context[$value] : null; break; } return $result; }; $node = static::_hostname($val); $pid = function_exists('zend_thread_id') ? zend_thread_id() : getmypid(); $pid = !$pid || $pid > 65535 ? mt_rand(0, 0xfff) | 0x4000 : $pid; list($timeMid, $timeLow) = explode(' ', microtime()); return sprintf("%08x-%04x-%04x-%02x%02x-%04x%08x", (int) $timeLow, (int) substr($timeMid, 2) & 0xffff, mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node); }
/** * Generate a random UUID * * @see http://www.ietf.org/rfc/rfc4122.txt * @return RFC 4122 UUID * @static */ function uuid() { $node = env('SERVER_ADDR'); if (empty($node)) { $host = env('HOSTNAME'); if (empty($host)) { $host = env('HOST'); } if (empty($host)) { $node = ip2long('127.0.0.1'); } else { $ip = gethostbyname($host); if ($ip === $host) { $node = crc32($host); } else { $node = ip2long($ip); } } } else { $node = ip2long($node); } if (function_exists('zend_thread_id')) { $pid = zend_thread_id(); } else { $pid = getmypid(); } list($timeMid, $timeLow) = explode(' ', microtime()); $uuid = sprintf("%08x-%04x-%04x-%02x%02x-%04x%08x", (int) $timeLow, (int) substr($timeMid, 2) & 0xffff, mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node); return $uuid; }
/** * This function tries to get all the entropy available in PHP, and distills it to get a good RNG. * * * @param int $length default 16, Number of bytes to generate * @param bool $secure default true, Generate secure distilled bytes, slower * @param bool $raw default true, returns a binary string if true, or an hexadecimal one * @param string $startEntropy default null, adds more initial entropy * @param int &$rounds Will be set to the number of rounds taken * @param int &$drop Will be set to the amount of dropped bytes * * @return string */ public static function getRandomBytes($length = 16, $secure = \true, $raw = \true, $startEntropy = "", &$rounds = 0, &$drop = 0) { static $lastRandom = ""; $output = ""; $length = \abs((int) $length); $secureValue = ""; $rounds = 0; $drop = 0; while (!isset($output[$length - 1])) { //some entropy, but works ^^ $weakEntropy = [\is_array($startEntropy) ? \implode($startEntropy) : $startEntropy, __DIR__, PHP_OS, \microtime(), (string) \lcg_value(), (string) PHP_MAXPATHLEN, PHP_SAPI, (string) \PHP_INT_MAX . "." . \PHP_INT_SIZE, \serialize($_SERVER), \get_current_user(), (string) \memory_get_usage() . "." . \memory_get_peak_usage(), \php_uname(), \phpversion(), \zend_version(), (string) \getmypid(), (string) \getmyuid(), (string) \mt_rand(), (string) \getmyinode(), (string) \getmygid(), (string) \rand(), \function_exists("zend_thread_id") ? (string) zend_thread_id() : \microtime(), \function_exists("getrusage") ? \implode(\getrusage()) : \microtime(), \function_exists("sys_getloadavg") ? \implode(\sys_getloadavg()) : \microtime(), \serialize(\get_loaded_extensions()), \sys_get_temp_dir(), (string) \disk_free_space("."), (string) \disk_total_space("."), \uniqid(\microtime(), \true), \file_exists("/proc/cpuinfo") ? \file_get_contents("/proc/cpuinfo") : \microtime()]; \shuffle($weakEntropy); $value = \hash("sha512", \implode($weakEntropy), \true); $lastRandom .= $value; foreach ($weakEntropy as $k => $c) { //mixing entropy values with XOR and hash randomness extractor $value ^= \hash("sha256", $c . \microtime() . $k, \true) . \hash("sha256", \mt_rand() . \microtime() . $k . $c, \true); $value ^= \hash("sha512", (string) \lcg_value() . $c . \microtime() . $k, \true); } unset($weakEntropy); if ($secure === \true) { if (\file_exists("/dev/urandom")) { $fp = \fopen("/dev/urandom", "rb"); $systemRandom = \fread($fp, 64); \fclose($fp); } else { $systemRandom = \str_repeat("", 64); } $strongEntropyValues = [\is_array($startEntropy) ? \hash("sha512", $startEntropy[($rounds + $drop) % \count($startEntropy)], \true) : \hash("sha512", $startEntropy, \true), $systemRandom, \function_exists("openssl_random_pseudo_bytes") ? openssl_random_pseudo_bytes(64) : \str_repeat("", 64), \function_exists("mcrypt_create_iv") ? mcrypt_create_iv(64, MCRYPT_DEV_URANDOM) : \str_repeat("", 64), $value]; $strongEntropy = \array_pop($strongEntropyValues); foreach ($strongEntropyValues as $value) { $strongEntropy = $strongEntropy ^ $value; } $value = ""; //Von Neumann randomness extractor, increases entropy $bitcnt = 0; for ($j = 0; $j < 64; ++$j) { $a = \ord($strongEntropy[$j]); for ($i = 0; $i < 8; $i += 2) { $b = ($a & 1 << $i) > 0 ? 1 : 0; if ($b != (($a & 1 << $i + 1) > 0 ? 1 : 0)) { $secureValue |= $b << $bitcnt; if ($bitcnt == 7) { $value .= \chr($secureValue); $secureValue = 0; $bitcnt = 0; } else { ++$bitcnt; } ++$drop; } else { $drop += 2; } } } } $output .= \substr($value, 0, \min($length - \strlen($output), $length)); unset($value); ++$rounds; } $lastRandom = \hash("sha512", $lastRandom, \true); return $raw === \false ? \bin2hex($output) : $output; }
<?php $_PCONN['cnt'] = 0; echo "start " . (function_exists('zend_thread_id') ? zend_thread_id() . " - " : '') . "\n";
<?php $_PCONN['cnt']++; if (function_exists('zend_thread_id')) { echo "thread ", zend_thread_id(), "\n"; } else { echo "main\n"; } exit(PCONN_SUCCESS);
/** * returns a process identifier. * In multi-process servers, this should be the system process ID. * In multi-threaded servers, this should be some unique ID to * prevent two threads from generating precisely the same UUID * at the same time. */ protected function getLockId() { if (function_exists('zend_thread_id')) { return zend_thread_id(); } return getmypid(); }
protected static function random_pseudo_bytes($length) { if (self::openssl_random_pseudo_bytes_exists()) { return openssl_random_pseudo_bytes($length); } if (self::mcrypt_dev_urandom_exists()) { $rnd = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); if ($rnd !== false) { return $rnd; } } // Rename the parameter on order it to fit with the code below. $len = $length; /* * The following code fragment has been taken from Secure-random-bytes-in-PHP * project, released under the New BSD License. * @see https://github.com/ivantcholakov/Secure-random-bytes-in-PHP * * * * Author: * George Argyros <*****@*****.**> * * Copyright (c) 2012, George Argyros * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL GEORGE ARGYROS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * The function is providing, at least at the systems tested :), * $len bytes of entropy under any PHP installation or operating system. * The execution time should be at most 10-20 ms in any system. */ $SSLstr = '4'; // http://xkcd.com/221/ /* * No build-in crypto randomness function found. We collect any entropy * available in the PHP core PRNGs along with some filesystem info and memory * stats. To make this data cryptographically strong we add data either from * /dev/urandom or if its unavailable, we gather entropy by measuring the * time needed to compute a number of SHA-1 hashes. */ $str = ''; $bits_per_round = 2; // bits of entropy collected in each clock drift round $msec_per_round = 400; // expected running time of each round in microseconds $hash_len = 20; // SHA-1 Hash length $total = $len; // total bytes of entropy to collect $handle = @fopen('/dev/urandom', 'rb'); if ($handle && function_exists('stream_set_read_buffer')) { @stream_set_read_buffer($handle, 0); } do { $bytes = $total > $hash_len ? $hash_len : $total; $total -= $bytes; //collect any entropy available from the PHP system and filesystem $entropy = rand() . uniqid(mt_rand(), true) . $SSLstr; $entropy .= implode('', @fstat(@fopen(__FILE__, 'r'))); $entropy .= memory_get_usage() . getmypid(); $entropy .= serialize($_ENV) . serialize($_SERVER); if (function_exists('posix_times')) { $entropy .= serialize(posix_times()); } if (function_exists('zend_thread_id')) { $entropy .= zend_thread_id(); } if ($handle) { $entropy .= @fread($handle, $bytes); } else { // Measure the time that the operations will take on average for ($i = 0; $i < 3; $i++) { $c1 = microtime(true); $var = sha1(mt_rand()); for ($j = 0; $j < 50; $j++) { $var = sha1($var); } $c2 = microtime(true); $entropy .= $c1 . $c2; } // Based on the above measurement determine the total rounds // in order to bound the total running time. $rounds = (int) ($msec_per_round * 50 / (int) (($c2 - $c1) * 1000000)); // Take the additional measurements. On average we can expect // at least $bits_per_round bits of entropy from each measurement. $iter = $bytes * (int) ceil(8 / $bits_per_round); for ($i = 0; $i < $iter; $i++) { $c1 = microtime(); $var = sha1(mt_rand()); for ($j = 0; $j < $rounds; $j++) { $var = sha1($var); } $c2 = microtime(); $entropy .= $c1 . $c2; } } // We assume sha1 is a deterministic extractor for the $entropy variable. $str .= sha1($entropy, true); // Modified by Deepak Patil <*****@*****.**>, 16-MAR-2015. //} while ($len > strlen($str)); } while ($len > self::strlen($str)); // if ($handle) { @fclose($handle); } // Modified by Deepak Patil <*****@*****.**>, 16-MAR-2015. //return substr($str, 0, $len); return self::substr($str, 0, $len); // /* * End of code fragment from Secure-random-bytes-in-PHP project. */ }
<?php echo "shutdown " . (function_exists('zend_thread_id') ? zend_thread_id() . " - " : '') . $_PCONN['cnt'] . "\n"; var_dump($_PCONN);
function secure_random_bytes($len = 10) { /* * Our primary choice for a cryptographic strong randomness function is * openssl_random_pseudo_bytes. */ $SSLstr = '4'; // http://xkcd.com/221/ if (function_exists('openssl_random_pseudo_bytes') && (version_compare(PHP_VERSION, '5.3.4') >= 0 || substr(PHP_OS, 0, 3) !== 'WIN')) { $SSLstr = openssl_random_pseudo_bytes($len, $strong); if ($strong) { return $SSLstr; } } /* * If mcrypt extension is available then we use it to gather entropy from * the operating system's PRNG. This is better than reading /dev/urandom * directly since it avoids reading larger blocks of data than needed. * Older versions of mcrypt_create_iv may be broken or take too much time * to finish so we only use this function with PHP 5.3.7 and above. * @see https://bugs.php.net/bug.php?id=55169 */ if (function_exists('mcrypt_create_iv') && (version_compare(PHP_VERSION, '5.3.7') >= 0 || substr(PHP_OS, 0, 3) !== 'WIN')) { $str = mcrypt_create_iv($len, MCRYPT_DEV_URANDOM); if ($str !== false) { return $str; } } /* * No build-in crypto randomness function found. We collect any entropy * available in the PHP core PRNGs along with some filesystem info and memory * stats. To make this data cryptographically strong we add data either from * /dev/urandom or if its unavailable, we gather entropy by measuring the * time needed to compute a number of SHA-1 hashes. */ $str = ''; $bits_per_round = 2; // bits of entropy collected in each clock drift round $msec_per_round = 400; // expected running time of each round in microseconds $hash_len = 20; // SHA-1 Hash length $total = $len; // total bytes of entropy to collect $handle = @fopen('/dev/urandom', 'rb'); if ($handle && function_exists('stream_set_read_buffer')) { @stream_set_read_buffer($handle, 0); } do { $bytes = $total > $hash_len ? $hash_len : $total; $total -= $bytes; //collect any entropy available from the PHP system and filesystem $entropy = rand() . uniqid(mt_rand(), true) . $SSLstr; $entropy .= implode('', @fstat(@fopen(__FILE__, 'r'))); $entropy .= memory_get_usage() . getmypid(); $entropy .= serialize($_ENV) . serialize($_SERVER); if (function_exists('posix_times')) { $entropy .= serialize(posix_times()); } if (function_exists('zend_thread_id')) { $entropy .= zend_thread_id(); } if ($handle) { $entropy .= @fread($handle, $bytes); } else { // Measure the time that the operations will take on average for ($i = 0; $i < 3; $i++) { $c1 = microtime(true); $var = sha1(mt_rand()); for ($j = 0; $j < 50; $j++) { $var = sha1($var); } $c2 = microtime(true); $entropy .= $c1 . $c2; } // Based on the above measurement determine the total rounds // in order to bound the total running time. $rounds = (int) ($msec_per_round * 50 / (int) (($c2 - $c1) * 1000000)); // Take the additional measurements. On average we can expect // at least $bits_per_round bits of entropy from each measurement. $iter = $bytes * (int) ceil(8 / $bits_per_round); for ($i = 0; $i < $iter; $i++) { $c1 = microtime(); $var = sha1(mt_rand()); for ($j = 0; $j < $rounds; $j++) { $var = sha1($var); } $c2 = microtime(); $entropy .= $c1 . $c2; } } // We assume sha1 is a deterministic extractor for the $entropy variable. $str .= sha1($entropy, true); } while ($len > strlen($str)); if ($handle) { @fclose($handle); } return substr($str, 0, $len); }
/** * Generate a random UUID * * @see http://www.ietf.org/rfc/rfc4122.txt * @return RFC 4122 UUID * @static * function create_guid() { $charid = strtoupper(md5(uniqid(mt_rand(), true))); $hyphen = chr(45);// "-" $uuid = chr(123)// "{" .substr($charid, 0, 8).$hyphen .substr($charid, 8, 4).$hyphen .substr($charid,12, 4).$hyphen .substr($charid,16, 4).$hyphen .substr($charid,20,12) .chr(125);// "}" return $uuid; } */ function pasguid() { if (function_exists('com_create_guid') === true) { return strtolower(trim(com_create_guid(), '{}')); } //return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 65535), //mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), //mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)); $node = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : 0; $pid = null; if (strpos($node, ':') !== false) { if (substr_count($node, '::')) { $node = str_replace('::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node); } $node = explode(':', $node); $ipv6 = ''; foreach ($node as $id) { $ipv6 .= str_pad(base_convert($id, 16, 2), 16, 0, STR_PAD_LEFT); } $node = base_convert($ipv6, 2, 10); if (strlen($node) < 38) { $node = null; } else { $node = crc32($node); } } elseif (empty($node)) { $host = isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME'] : ''; if (empty($host)) { $host = isset($_SERVER['HOST']) ? $_SERVER['HOST'] : ''; } if (!empty($host)) { $ip = gethostbyname($host); if ($ip === $host) { $node = crc32($host); } else { $node = ip2long($ip); } } } elseif ($node !== '127.0.0.1') { $node = ip2long($node); } else { $node = null; } if (empty($node)) { $node = crc32("DYhG93bdsa0qyJfIxdfs2guVoUubWwvniR2G0FgaC9mi"); } if (function_exists('zend_thread_id')) { $pid = zend_thread_id(); } else { $pid = getmypid(); } if (!$pid || $pid > 65535) { $pid = mt_rand(0, 0xfff) | 0x4000; } list($timeMid, $timeLow) = explode(' ', microtime()); $uuid = sprintf("%08x-%04x-%04x-%02x%02x-%04x%08x", (int) $timeLow, (int) substr($timeMid, 2) & 0xffff, mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node); return $uuid; }
/** * Generate a 36-character RFC 4122 UUID, without the urn:uuid: prefix. * * @see http://www.ietf.org/rfc/rfc4122.txt * @see http://labs.omniti.com/alexandria/trunk/OmniTI/Util/UUID.php */ public function generate() { $this->_uuid = null; if (extension_loaded('uuid')) { if (function_exists('uuid_export')) { // UUID extension from http://www.ossp.org/pkg/lib/uuid/ if (uuid_create($ctx) == UUID_RC_OK && uuid_make($ctx, UUID_MAKE_V4) == UUID_RC_OK && uuid_export($ctx, UUID_FMT_STR, $str) == UUID_RC_OK) { $this->_uuid = $str; uuid_destroy($ctx); } } else { // UUID extension from http://pecl.php.net/package/uuid $this->_uuid = uuid_create(); } } if (!$this->_uuid) { list($time_mid, $time_low) = explode(' ', microtime()); $time_low = (int) $time_low; $time_mid = (int) substr($time_mid, 2) & 0xffff; $time_high = mt_rand(0, 0xfff) | 0x4000; $clock = mt_rand(0, 0x3fff) | 0x8000; $node_low = function_exists('zend_thread_id') ? zend_thread_id() : getmypid(); $node_high = isset($_SERVER['SERVER_ADDR']) ? ip2long($_SERVER['SERVER_ADDR']) : crc32(php_uname()); $node = bin2hex(pack('nN', $node_low, $node_high)); $this->_uuid = sprintf('%08x-%04x-%04x-%04x-%s', $time_low, $time_mid, $time_high, $clock, $node); } }