kryptos/hmac

Hash-based Message Authentication Code (HMAC).

HMAC provides message authentication using a cryptographic hash function combined with a secret key. Use it to verify both data integrity and authenticity.

Example

import kryptos/hmac
import kryptos/hash

let assert Ok(h) = hmac.new(hash.Sha256, <<"secret key":utf8>>)
let mac = h |> hmac.update(<<"hello":utf8>>) |> hmac.final()

Types

Represents an in-progress HMAC computation.

Use new to create an HMAC, update to add data, and final to get the MAC.

pub type Hmac

Values

pub fn final(hmac: Hmac) -> BitArray

Finalizes the HMAC computation and returns the authentication code.

After calling this function, the HMAC should not be reused.

pub fn new(
  algorithm: hash.HashAlgorithm,
  key: BitArray,
) -> Result(Hmac, Nil)

Creates a new HMAC for incremental authentication.

Use this when you need to authenticate data in chunks, such as when streaming or when the full input isn’t available at once.

pub fn supported_hash(algorithm: hash.HashAlgorithm) -> Bool

Checks if a hash algorithm is supported for HMAC operations.

pub fn update(hmac: Hmac, data: BitArray) -> Hmac

Adds data to an in-progress HMAC computation.

Can be called multiple times to incrementally authenticate data.

pub fn verify(
  algorithm: hash.HashAlgorithm,
  key key: BitArray,
  data data: BitArray,
  expected expected: BitArray,
) -> Result(Bool, Nil)

Verifies that a MAC matches the expected value using constant-time comparison.

Computes the HMAC and compares it to the expected value in constant time to prevent timing attacks.

Search Document