Build SHA-256 and HMAC from scratch
Stage 5 of 7v2 · 645e2bee

Complete digest

Chain all 64 rounds and validate the complete SHA-256 digest.

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.

Full SHA-256 Hash Digest

In this stage, you assemble all building blocks into the complete SHA-256 implementation: padding, initial state vectors H0…H7H_0 \dots H_7, schedule expansion, and 64 compression rounds per block.

Mental Model: The SHA-256 Pipeline

  1. Initial Vector: First 32 bits of the fractional parts of square roots of first 8 primes (H0…H7H_0 \dots H_7).
  2. Padding: Pad input UTF-8 bytes to multiple of 512 bits.
  3. Block Processing:
    • Expand 16 words to 64.
    • Run 64 rounds with constants K0…K63K_0 \dots K_{63}.
    • Additive update to H0…H7H_0 \dots H_7.
  4. Final Digest: 64-character lowercase hexadecimal string.

Your Goal in this Stage

Read a JSON object from stdin with op: "sha256" and text. Return the 64-character hex digest under "hex".

Input Format

json
{
  "op": "sha256",
  "text": "abc"
}

Output Format

json
{
  "hex": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
}

Step-by-Step Implementation Guide

  1. Encode to UTF-8 bytes: Convert input text.
  2. Apply padding: Align to 512-bit blocks.
  3. Execute compression rounds: Process blocks through rounds.
  4. Format hex digest: Join H0…H7H_0 \dots H_7 zero-padded to 8 hex digits each.
  5. Emit output: Print JSON object.

Acceptance Criteria

  • ✅ Matches NIST standard test vectors.
  • ✅ Produces 64-character lowercase hex digest.

From blocks to rounds

Prepare unsigned 32-bit rotation, logical shift, Choice, and Majority. Distinguish the small schedule sigmas from the capital compression sigmas. Save each block’s initial state for feed-forward after 64 rounds; all additions wrap modulo 2^32. Do not derive constants using floating point.

Use FIPS 180-4: §4.1.2 defines functions, §4.2.2 constants, §5.3.3 initialization, and §6.2.2 the update order. Trace one round before processing multiple blocks.

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.