catacomb/__init__.py (_HashBase): Check that integers are within bounds.
[catacomb-python] / catacomb / __init__.py
index 8713ab7..24265ac 100644 (file)
@@ -206,15 +206,31 @@ _augment(Poly1305Hash, _tmp)
 class _HashBase (object):
   ## The standard hash methods.  Assume that `hash' is defined and returns
   ## the receiver.
-  def hashu8(me, n): return me.hash(_pack('B', n))
-  def hashu16l(me, n): return me.hash(_pack('<H', n))
-  def hashu16b(me, n): return me.hash(_pack('>H', n))
+  def _check_range(me, n, max):
+    if not (0 <= n <= max): raise OverflowError("out of range")
+  def hashu8(me, n):
+    me._check_range(n, 0xff)
+    return me.hash(_pack('B', n))
+  def hashu16l(me, n):
+    me._check_range(n, 0xffff)
+    return me.hash(_pack('<H', n))
+  def hashu16b(me, n):
+    me._check_range(n, 0xffff)
+    return me.hash(_pack('>H', n))
   hashu16 = hashu16b
-  def hashu32l(me, n): return me.hash(_pack('<L', n))
-  def hashu32b(me, n): return me.hash(_pack('>L', n))
+  def hashu32l(me, n):
+    me._check_range(n, 0xffffffff)
+    return me.hash(_pack('<L', n))
+  def hashu32b(me, n):
+    me._check_range(n, 0xffffffff)
+    return me.hash(_pack('>L', n))
   hashu32 = hashu32b
-  def hashu64l(me, n): return me.hash(_pack('<Q', n))
-  def hashu64b(me, n): return me.hash(_pack('>Q', n))
+  def hashu64l(me, n):
+    me._check_range(n, 0xffffffffffffffff)
+    return me.hash(_pack('<Q', n))
+  def hashu64b(me, n):
+    me._check_range(n, 0xffffffffffffffff)
+    return me.hash(_pack('>Q', n))
   hashu64 = hashu64b
   def hashbuf8(me, s): return me.hashu8(len(s)).hash(s)
   def hashbuf16l(me, s): return me.hashu16l(len(s)).hash(s)