Skip to content

Instantly share code, notes, and snippets.

@yohgaki
Last active October 2, 2016 21:55
Show Gist options
  • Save yohgaki/cbe5431f9d072b57af2883a2b5745195 to your computer and use it in GitHub Desktop.
Save yohgaki/cbe5431f9d072b57af2883a2b5745195 to your computer and use it in GitHub Desktop.
Use better entropy for uniqid() - https://bugs.php.net/bug.php?id=73215
diff --git a/ext/standard/uniqid.c b/ext/standard/uniqid.c
index f429e6d..975e65b 100644
--- a/ext/standard/uniqid.c
+++ b/ext/standard/uniqid.c
@@ -36,8 +36,11 @@
#endif
#include "php_lcg.h"
+#include "php_random.h"
#include "uniqid.h"
+#define PHP_UNIQID_ENTROPY_LEN 10
+
/* {{{ proto string uniqid([string prefix [, bool more_entropy]])
Generates a unique ID */
#ifdef HAVE_GETTIMEOFDAY
@@ -77,7 +80,28 @@ PHP_FUNCTION(uniqid)
* digits for usecs.
*/
if (more_entropy) {
- uniqid = strpprintf(0, "%s%08x%05x%.8F", prefix, sec, usec, php_combined_lcg() * 10);
+ int i;
+ unsigned char c, entropy[PHP_UNIQID_ENTROPY_LEN+1] = {0};
+
+ for(i = 0; i < PHP_UNIQID_ENTROPY_LEN;) {
+ if (php_random_bytes_throw(&c, sizeof(c)) == FAILURE) {
+ break;
+ }
+ /* Avoid modulo bias */
+ if (c > 249) {
+ continue;
+ }
+ entropy[i] = c % 10 + '0';
+ i++;
+ }
+ if (i == PHP_UNIQID_ENTROPY_LEN) {
+ /* Set . for compatibility */
+ entropy[1] = '.';
+ uniqid = strpprintf(0, "%s%08x%05x%s", prefix, sec, usec, entropy);
+ } else {
+ /* Should not ignore exception, but return something anyway */
+ uniqid = strpprintf(0, "%s%08x%05x%.8F", prefix, sec, usec, php_combined_lcg() * 10);
+ }
} else {
uniqid = strpprintf(0, "%s%08x%05x", prefix, sec, usec);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment