Ticket #17040: fix-1740-separate-function-for-py3.patch

File fix-1740-separate-function-for-py3.patch, 1.5 KB (added by adsworth, 13 years ago)
  • django/utils/crypto.py

    diff --git a/django/utils/crypto.py b/django/utils/crypto.py
    index 1587bfc..36d03a6 100644
    a b Django's standard crypto functions and utilities.  
    44
    55import hashlib
    66import hmac
     7import sys
    78from django.conf import settings
     9from django.utils.encoding import smart_str
    810from django.utils.py3 import b
    911
    1012def salted_hmac(key_salt, value, secret=None):
    def salted_hmac(key_salt, value, secret=None):  
    2830    # However, we need to ensure that we *always* do this.
    2931    return hmac.new(key, msg=value, digestmod=hashlib.sha1)
    3032
    31 def constant_time_compare(val1, val2):
     33def constant_time_compare_py2(val1, val2):
    3234    """
    3335    Returns True if the two strings are equal, False otherwise.
    3436
    def constant_time_compare(val1, val2):  
    4042    for x, y in zip(val1, val2):
    4143        result |= ord(x) ^ ord(y)
    4244    return result == 0
     45
     46def constant_time_compare_py3(val1, val2):
     47    """
     48    Returns True if the two strings are equal, False otherwise.
     49
     50    The time taken is independent of the number of characters that match.
     51    """
     52    val1 = smart_str(val1)
     53    val2 = smart_str(val2)
     54
     55    if len(val1) != len(val2):
     56        return False
     57    result = 0
     58    for x, y in zip(val1, val2):
     59        result |= x ^ y
     60    return result == 0
     61
     62if sys.version_info < (3, 0):
     63    constant_time_compare = constant_time_compare_py2
     64else:
     65    constant_time_compare = constant_time_compare_py3
Back to Top