diff Objects/bytesobject.c @ 75066:f4b7ecf8a5f8 3.1

Issue #13703: add a way to randomize the hash values of basic types (str, bytes, datetime) in order to make algorithmic complexity attacks on (e.g.) web apps much more complicated. The environment variable PYTHONHASHSEED and the new command line flag -R control this behavior.
author Georg Brandl <georg@python.org>
date Mon, 20 Feb 2012 19:54:16 +0100
parents bcbf8c3c4a88
children 160a56eac332 4a31f6b11e7a
line wrap: on
line diff
--- a/Objects/bytesobject.c	Sat Feb 18 14:42:57 2012 +0100
+++ b/Objects/bytesobject.c	Mon Feb 20 19:54:16 2012 +0100
@@ -899,11 +899,21 @@
     if (a->ob_shash != -1)
         return a->ob_shash;
     len = Py_SIZE(a);
+    /*
+      We make the hash of the empty string be 0, rather than using
+      (prefix ^ suffix), since this slightly obfuscates the hash secret
+    */
+    if (len == 0) {
+        a->ob_shash = 0;
+        return 0;
+    }
     p = (unsigned char *) a->ob_sval;
-    x = *p << 7;
+    x = _Py_HashSecret.prefix;
+    x ^= *p << 7;
     while (--len >= 0)
         x = (1000003*x) ^ *p++;
     x ^= Py_SIZE(a);
+    x ^= _Py_HashSecret.suffix;
     if (x == -1)
         x = -2;
     a->ob_shash = x;