Hmac

Mojo struct 🡭

Hmac

@memory_only
struct Hmac[H: Digest & Deinitable & Movable]

HMAC: a hash-based message authentication code.

HMAC turns any Merkle-Damgard hash into a MAC by nesting two hash calls around the message:

HMAC(K, m) = H((K0 ^ opad) || H((K0 ^ ipad) || m))

The outer call is what closes the length-extension forgery that a bare H(key || message) admits.

K0 is the key resized to exactly one hash block: hashed down first if it is longer than a block, then zero-padded on the right.

FIPS 198-1: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.198-1.pdf RFC 2104: https://datatracker.ietf.org/doc/html/rfc2104

Aliases

  • BLOCK_SIZE = H.BLOCK_SIZE
  • TAG_SIZE = H.OUTPUT_SIZE
  • IPAD_BYTE = UInt8(54): FIPS 198-1 §4 — the inner pad byte, applied across a whole block.
  • OPAD_BYTE = UInt8(92): FIPS 198-1 §4 — the outer pad byte, applied across a whole block.

Parameters

  • H (Digest & Deinitable & Movable)

Implemented traits

AnyType, Deinitable, Mac, Movable

Methods

__init__

fn def __init__[o: Origin[mut=o.mut]](out self, key: Span[UInt8, o])

Initialize HMAC from a key of any length.

Derives K0 (FIPS 198-1 §4 steps 1-3) and primes the inner hash with K0 ^ ipad (step 4-5), leaving it ready to absorb the message.

Parameters:

  • o (Origin[mut=mut])

Args:

  • key (Span[UInt8, o])
  • self (Self)

Returns:

Self

update

fn def update[o: Origin[mut=o.mut]](mut self, data: Span[UInt8, o])

Absorb more input.

Parameters:

  • o (Origin[mut=mut])

Args:

  • self (Self)
  • data (Span[UInt8, o])

Raises:

finalize

fn def finalize(var self) -> Array[UInt8, H.OUTPUT_SIZE]

Consume self and return the TAG_SIZE-byte authentication tag.

Closes the inner hash over (K0 ^ ipad) || text (FIPS 198-1 §4 step 7), then runs a fresh outer hash over (K0 ^ opad) || H((K0 ^ ipad) || text) (steps 8-9).

Args:

  • self (Self)

Returns:

Array[UInt8, H.OUTPUT_SIZE]

Raises:

reset

fn def reset(mut self)

Reset the accumulator to its initial state while keeping the key.

Restores the inner hash to the just-absorbed-K0 ^ ipad state, so another message can be authenticated under the same key without re-deriving K0.

Args:

  • self (Self)