2016-03-10 49 views
0

任何人都可以說出爲什麼以下評論說所花費的時間與匹配的字符數無關?關於django的測驗crypto.constant_time_compare()

在我看來,所花費的時間應該取決於字符的數量。

該代碼是從Django中複製,crypto.py

def constant_time_compare(val1, val2): 
    """ 
    Returns True if the two strings are equal, False otherwise. 

    The time taken is independent of the number of characters that match. 

    For the sake of simplicity, this function executes in constant time only 
    when the two strings have the same length. It short-circuits when they 
    have different lengths. Since Django only uses it to compare hashes of 
    known expected length, this is acceptable. 
    """ 
    if len(val1) != len(val2): 
     return False 
    result = 0 
    if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes): 
     for x, y in zip(val1, val2): 
      result |= x^y 
    else: 
     for x, y in zip(val1, val2): 
      result |= ord(x)^ord(y) 
    return result == 0 
+0

你可能想編輯你的問題,解釋你爲什麼認爲它的依賴,並刪除任何提及的測驗,[所以]是一個網站*編程問題,幫助*不創建它們 – Sayse

+0

哦,我做一個愚蠢的錯誤 – Jacky

回答

2

它是獨立的字符的數量的匹配,在總的字符不是數字。正如你注意到的那樣,字符串中的字符數量是線性的。

它旨在避免依賴於比較算法的保時捷漏洞,一旦它們達到非匹配字符,就立即進行保釋。