import hmac
from typing import Any, Sequence
def _check_bytes(value: Any, name: str) -> bytes:
if isinstance(value, (str, dict)) ornot hasattr(value, "__len__"):
raise TypeError("%s must be a list of integers from 0 to 255" % name)
for b in value:
if type(b) isnot int or b < 0or b > 255:
raise ValueError("%s must be a list of integers from 0 to 255" % name)
return bytes(value)
def constant_time_equal(a: Sequence[int], b: Sequence[int]) -> bool:
"""Are two byte strings equal, without stopping at the first difference? hmac.compare_digest is the standard library's constant-time comparison; the byte check before it fails a bad value with the same words as the other languages. """
left = _check_bytes(a, "a")
right = _check_bytes(b, "b")
return hmac.compare_digest(left, right)