import hashlib
import hmac
from typing import Any, List, 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 hmac_sha256(key: Sequence[int], message: Sequence[int]) -> List[int]:
"""HMAC-SHA256 (RFC 2104) from the standard library's hmac module. The byte values are checked here so a bad value fails with the same words as in TypeScript and Rust. """
k = _check_bytes(key, "key")
m = _check_bytes(message, "message")
return list(hmac.new(k, m, hashlib.sha256).digest())