python中的字符串对比#漂亮代码
2015-09-13 本文已影响342人
deeper
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
- zip 就像一个拉链一样,按照最短的尺度,把数组(或者更高维度的矩阵),展开为元祖的数组(或者矩阵)
- ord 可以取到字符的ASCII码
- ^ 按位异或通过位运算快速判断两个或多个数字是否相同,只要是相同,则二进制中的位置都变为0
- | 按位或运算判读多个数字的加和,如果二进制中有1,则最终结果有1
通过这些方式实现了快速对比两穿字符串的内容。
注:代码来自Django project