_compat.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import decimal
  2. import hmac
  3. import numbers
  4. import sys
  5. PY2 = sys.version_info[0] == 2
  6. if PY2:
  7. from itertools import izip
  8. text_type = unicode # noqa: 821
  9. else:
  10. izip = zip
  11. text_type = str
  12. number_types = (numbers.Real, decimal.Decimal)
  13. def _constant_time_compare(val1, val2):
  14. """Return ``True`` if the two strings are equal, ``False``
  15. otherwise.
  16. The time taken is independent of the number of characters that
  17. match. Do not use this function for anything else than comparision
  18. with known length targets.
  19. This is should be implemented in C in order to get it completely
  20. right.
  21. This is an alias of :func:`hmac.compare_digest` on Python>=2.7,3.3.
  22. """
  23. len_eq = len(val1) == len(val2)
  24. if len_eq:
  25. result = 0
  26. left = val1
  27. else:
  28. result = 1
  29. left = val2
  30. for x, y in izip(bytearray(left), bytearray(val2)):
  31. result |= x ^ y
  32. return result == 0
  33. # Starting with 2.7/3.3 the standard library has a c-implementation for
  34. # constant time string compares.
  35. constant_time_compare = getattr(hmac, "compare_digest", _constant_time_compare)