Build SHA-256 and HMAC from scratch
Stage 6 of 7v3 · 9d901409

HMAC-SHA256

Combine normalized keys with HMAC inner and outer pads.

Build it in your language

The tester treats your program as a black box: any language works. These are just the most convenient ones for this project.

Message Authentication: HMAC-SHA-256

HMAC (Hash-based Message Authentication Code) pairs a secret key with SHA-256 to ensure authenticity and integrity (RFC 2104).

Mental Model: The HMAC Formulation

For 64-byte block size (B=64B = 64):

  1. Key Normalization:
    • If key exceeds 64 bytes: hash down using SHA-256.
    • If key under 64 bytes: zero-pad to 64 bytes.
  2. Inner & Outer Pads:
    • k_ipad = key ^ 0x36 (64 bytes).
    • k_opad = key ^ 0x5c (64 bytes).
  3. Two-Pass Hashing: HMAC(K,m)=SHA-256(kopadmathbinVertSHA-256(kipadmathbinVertm))\text{HMAC}(K, m) = \text{SHA-256}(k_opad mathbin{Vert} \text{SHA-256}(k_ipad mathbin{Vert} m))

Your Goal in this Stage

Read a JSON object from stdin with op: "hmac-sha256", keyHex, and text. Output the authentication tag in hex.

Input Format

json
{
  "op": "hmac-sha256",
  "keyHex": "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
  "text": "Hi There"
}

Output Format

json
{
  "hex": "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
}

Step-by-Step Implementation Guide

  1. Normalize key: Pad or hash to 64 bytes.
  2. Compute inner/outer pads: XOR with 0x36 and 0x5c.
  3. Compute hashes: Chain inner hash into outer hash.
  4. Emit output: Print JSON object.

Acceptance Criteria

  • ✅ Conforms to RFC 2104 / RFC 4231 standards.
  • ✅ Emits 64-character lowercase hex digest.

Output and errors

Multiline examples are formatted for readability. Emit compact JSON without optional spaces, with properties in the order shown by the output examples, and a final newline. Keep logs off stdout. Tests compare exact text. Invalid inputs use stderr containing error, empty stdout, and exit 1. Valid inputs exit 0. Serialize integer results as JSON integers.