Python 3.6+secretsfunction
secrets.compare_digest()
comparison
Compares two strings or two bytes objects in time that does not depend on where they differ, defending against timing attacks.
Syntax
secrets.compare_digest(a, b) -> bool
Plain == stops at the first mismatch, so response times let an attacker guess a token one character at a time. compare_digest always checks everything. str arguments must be ASCII-only, otherwise TypeError; compare .encode() results for arbitrary text. It is the same object as hmac.compare_digest.
Examples
import secrets
token = secrets.token_hex(8)
print(secrets.compare_digest(token, token)) # → True
print(secrets.compare_digest(b'abc', b'abd')) # → False
try:
secrets.compare_digest('пароль', 'пароль')
except TypeError as e:
print(e) # → comparing strings with non-ASCII characters is not supported
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy