Functional Weave
Code in Rust

crypto.hmac-sha256@1.0.0

impl/python.py

842 bytes · the Python implementation · view raw

import hashlib
import hmac
from typing import Any, List, 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 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())