Re: Use decent entropy for uniqid($prefix, TRUE)

From: Date: Tue, 03 Jan 2017 19:56:30 +0000
Subject: Re: Use decent entropy for uniqid($prefix, TRUE)
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-97508@lists.php.net to get a copy of this message
On 2016-12-31 01:20, Yasuo Ohgaki wrote:
+               zend_long rand;
+               php_random_int(1000000000, 9999999999, &rand, 1);
+               uniqid = strpprintf(0, "%s%08x%05x%.8F", prefix, sec,
usec, (double)rand/10000000000);
Your code is broken. It produces 0.10000000 - 0.99999999 when it should produce 0.00000000 - 9.99999999. Also, you have integer overflow on 32-bit systems. Why do you mess with oversized integers and doubles and at all? It would be cleaner and simpler to use just regular 32-bit integers like this:
+               zend_long rand;
+               php_random_int(0, 999999999, &rand, 1);
+               uniqid = strpprintf(0, "%s%08x%05x%d.%08d", prefix, sec, usec, rand % 10, rand / 10);
Also, your argument about PHPMailer has nothing to do with your main complaint about lcg_value, since collisions of lcg_value are not the problem there. Why don't you put your effort into a more useful solution such as random_string or something? random_string(PHP_STRING_HEX_LOWER, 32) would produce md5-style output. random_string(PHP_STRING_BASE64, 32) would produce a lot more entropy. random_string("my_charset", 20) would cover the general case. random_array([1,2,3], 20) could extend this to arbitrary arrays. -- Lauri Kenttä

« previous php.internals (#97508) next »