GitHub

API reference for mac.

HMAC as a service (Effect's effect/crypto/Mac)::

mac = yield from Mac()
key = yield from mac_module.key(hmac_sha256, secret)
tag = yield from mac.sign(key, data)
ok = yield from mac.verify(key, tag, data)

verify compares in constant time and is False for a tag of another length. A Key shows only its algorithm, equals only itself, and gives its bytes back through to_bytes.

Re-exports

Values

AttributeTypeDescription
hmac_sha1Algorithm
hmac_sha256Algorithm
hmac_sha384Algorithm
hmac_sha512Algorithm
layer_web_cryptoLayer[Mac, Never, SecureRandom]

HMAC on the WebCrypto reference; keys generated from SecureRandom.

Types

TypeDefinitionDescription
Hmactype Hmac = Callable[[DigestName, bytes, bytes], bytes]

hmac(hash_name, key, data): an in-process HMAC.

Classes

Functions

is_key

is_key(u) -> bool
ParameterTypeDescription
uobject

Returns bool

def is_key(u: object) -> bool:
    return isinstance(u, Key)

layer_web_crypto_with

layer_web_crypto_with(*, hmac=None) -> Layer[Mac, Never, SecureRandom]

layer_web_crypto, computing a byte-backed key's tags with hmac when given; CryptoKey-backed keys stay on subtle.

ParameterTypeDescription
hmacHmac | None = None

Returns Layer[Mac, Never, SecureRandom]

def layer_web_crypto_with(*, hmac: Hmac | None = None) -> Layer[Mac, Never, SecureRandom]:
    """``layer_web_crypto``, computing a byte-backed key's tags with
    ``hmac`` when given; ``CryptoKey``-backed keys stay on ``subtle``."""

    @gen
    def build():
        random = yield from SecureRandom()
        crypto = yield from WebCrypto()
        crypto_key_for = _key.make_cache(
            lambda subtle, data, algorithm: subtle.import_key(
                "raw", data, _import_params(algorithm), False, ["sign", "verify"]
            )
        )

        def tag_of(key: Key[Any]) -> Callable[[Binary], bytes] | None:
            stored = material(key)
            compute = hmac
            if compute is None or not isinstance(stored, bytes):
                return None
            return lambda data: bytes(compute(key.algorithm.hash.name, stored, bytes(data)))

        def generate_key(algorithm: Algorithm) -> Effect[Key[Any], CryptoError]:
            return random.random_bytes(_BLOCK_SIZES[algorithm.hash.name]).map(
                lambda data: Key(algorithm, data)
            )

        def sign(key: Key[Any], data: Binary) -> Effect[bytes, CryptoError]:
            compute = tag_of(key)
            if compute is not None:
                return sync(lambda: compute(data))

            def run(subtle: SubtleCrypto) -> bytes:
                return bytes(subtle.sign("HMAC", crypto_key_for(subtle, key), bytes(data)))

            return _web.run("Mac", "sign", key.algorithm.name, crypto, run)

        # Both paths compare tags in constant time and reject other lengths.
        def verify(key: Key[Any], tag: Binary, data: Binary) -> Effect[bool, CryptoError]:
            compute = tag_of(key)
            if compute is not None:
                return sync(lambda: timing_safe_equal(compute(data), tag))

            def run(subtle: SubtleCrypto) -> bool:
                return subtle.verify("HMAC", crypto_key_for(subtle, key), bytes(tag), bytes(data))

            return _web.run("Mac", "verify", key.algorithm.name, crypto, run)

        return MacService(generate_key=generate_key, sign=sign, verify=verify)

    return layer_effect(Mac, build)

key

key[A: Algorithm](algorithm, data) -> Effect[Key[A], CryptoError]

A key holding a copy of data, which cannot be empty.

ParameterTypeDescription
algorithmA
dataBinary

Returns Effect[Key[A], CryptoError]

def key[A: Algorithm](algorithm: A, data: Binary) -> Effect[Key[A], CryptoError]:
    """A key holding a copy of ``data``, which cannot be empty."""
    return _key.from_bytes(
        lambda copied: Key(algorithm, copied),
        "Mac",
        "key",
        data,
        lambda copied: "An HMAC key cannot be empty" if not copied else None,
    )

from_crypto_key

from_crypto_key[A: Algorithm](algorithm, crypto_key) -> Effect[Key[A], CryptoError]

A key backed by an HMAC CryptoKey for algorithm's hash, with both the sign and verify usages.

ParameterTypeDescription
algorithmA
crypto_keyCryptoKey

Returns Effect[Key[A], CryptoError]

def from_crypto_key[A: Algorithm](
    algorithm: A, crypto_key: CryptoKey
) -> Effect[Key[A], CryptoError]:
    """A key backed by an HMAC ``CryptoKey`` for ``algorithm``'s hash, with
    both the ``sign`` and ``verify`` usages."""

    def check(key_algorithm: KeyAlgorithm) -> str | None:
        hash_name = key_algorithm.hash
        if hash_name == algorithm.hash.name:
            return None
        return f"Expected an HMAC key for {algorithm.hash.name}, not {hash_name}"

    return _key.from_crypto_key(
        Key,
        "Mac",
        "fromCryptoKey",
        algorithm,
        crypto_key,
        _key.ExpectedCryptoKey(
            type="secret", name="HMAC", usages=("sign", "verify"), usage_policy="all", check=check
        ),
    )

to_bytes

to_bytes(key) -> Effect[bytes, CryptoError]

A copy of the key's bytes; NotExtractable for a non-extractable CryptoKey.

ParameterTypeDescription
keyKey[Any]

Returns Effect[bytes, CryptoError]

def to_bytes(key: Key[Any]) -> Effect[bytes, CryptoError]:
    """A copy of the key's bytes; ``NotExtractable`` for a non-extractable
    ``CryptoKey``."""
    return _key.to_bytes("Mac", key, _key.export_raw)

timing_safe_equal

timing_safe_equal(a, b) -> bool

Whether a and b are equal, compared in constant time; False for different lengths.

ParameterTypeDescription
aBinary
bBinary

Returns bool

def timing_safe_equal(a: Binary, b: Binary) -> bool:
    """Whether ``a`` and ``b`` are equal, compared in constant time;
    ``False`` for different lengths."""
    left, right = bytes(a), bytes(b)
    if len(left) != len(right):
        return False
    return std_hmac.compare_digest(left, right)