Functional Weave
Code in TypeScript

crypto.constant-time-equal@1.0.0

impl/python.py

862 bytes · the Python implementation · view raw

import hmac
from typing import Any, Sequence


def _check_bytes(value: Any, name: str) -> bytes:
    if isinstance(value, (str, dict)) or not hasattr(value, "__len__"):
        raise TypeError("%s must be a list of integers from 0 to 255" % name)
    for b in value:
        if type(b) is not int or b < 0 or 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)