Commits

Christian Heimes  committed 0a649b5

Use PyOS_URandom or Mersenne Twister as random seed source

  • Participants
  • Parent commits 7c36daa
  • Branches randomhash

Comments (0)

Files changed (1)

File Python/hash.c

 #include "Python.h"
+#include "pyrandom.h"
+#define SEED_SIZE 8
 
-uint32_t Py_RndHashSeed[8] = {0};
+uint32_t Py_RndHashSeed[SEED_SIZE] = {-1};
+
+void
+_Py_InitRndHashSeed(void)
+{
+	static int initialized = 0;
+	int result;
+	if (initialized) {
+		return;
+	}
+	initialized = 1;
+
+	result = PyOS_URandom((unsigned char*)Py_RndHashSeed, SEED_SIZE * 4);
+	/* fall back to Mersenne twister */
+	if (result == -1) {
+		_Py_MT_RandomState state;
+		time_t seed;
+		int i;
+
+		time(&seed);
+		_Py_MT_GenRand_Init(&state, seed);
+		for (i=0; i < SEED_SIZE; i++) {
+			Py_RndHashSeed[i] = _Py_MT_GenRand_Int32(&state);
+		}
+		if (Py_RndHashSeed[0] == -1) {
+			Py_RndHashSeed[0] = -2;
+		}
+
+	}
+}
+
+
 
 /* forward declarations */
 void MurmurHash3_x86_32  (const void * key, const Py_ssize_t len, const uint32_t seed[8], void * out);
 	return Py_RndHashSeed;
 }
 
-void
-_Py_InitRndHashSeed(void)
-{
-	static int initialized = 0;
-    _PyTime_timeval t;
-    pid_t pid;
-
-	if (initialized) {
-		return;
-	}
-	initialized = 1;
-
-	// must be replaced by something better
-    _PyTime_gettimeofday(&t);
-    pid = getpid();
-
-    Py_RndHashSeed[0] = pid;
-    Py_RndHashSeed[1] = t.tv_sec & 0xffff;
-    Py_RndHashSeed[2] = t.tv_usec;
-    Py_RndHashSeed[3] = t.tv_usec & 0xffff;
-    Py_RndHashSeed[4] = pid;
-    Py_RndHashSeed[5] = t.tv_sec & 0xffff;
-    Py_RndHashSeed[6] = t.tv_usec;
-    Py_RndHashSeed[7] = t.tv_usec & 0xffff;
-}
 
 Py_hash_t
 _Py_HashBytes(unsigned char *p, Py_ssize_t len)