Keyboard shortcuts

Press ← or → to navigate between chapters

Press ? to show this help

Press Esc to hide this help

What does SHA-256 compute at the end of a file?

If you want to hash a large file as you download it, rereading the file from the beginning for each chunk would be costly. SHA-256, a member of the SHA-2 family, keeps the result so far in eight 32-bit words and updates them with each new 64-byte block. The final eight words form the 32-byte digest. FIPS 180-4 §§5–6

SHA-256: padding abc and carrying state forward
  1. Pad the messageabc (3 bytes, 24 bits) + 0x80 (the 1 bit and seven following zero bits) + 52 zero bytes + 00 00 00 00 00 00 00 18 (length in bits) = one 64-byte block.
  2. Prepare the blockRead 16 big-endian 32-bit words; expand them to 64 words.
  3. CompressRun 64 rounds on eight working words, starting from the initial eight-word state.
  4. Carry forwardAdd working words to the starting state word by word. That eight-word result becomes the starting state for the next 64-byte block.
  5. OutputAfter the final block, serialize the eight state words as the 32-byte SHA-256 digest of abc.

Why even three bytes take up a block

The ASCII input abc is 24 bits long. Append a single 1 bit after the three bytes, pad with zeros, and store the original bit length, 24, in the final eight bytes. The result is exactly 64 bytes. With abcd, both the contents and the length change. If the current block has too little room for the length field, the padding extends into another block. In Rust, feed input to Sha256 with try_update and call try_finalize_into to apply the final padding and write the digest. QuantAegis hash API

How one block changes the eight-word state

Split each block into 16 words and expand them to 64 words using bit rotations, shifts, and additions. Copy the fixed initial state, or the previous state for later blocks, into eight working words. Mix them over 64 rounds, using one expanded word per round. The rounds combine a function that uses the bits of one word to choose between the corresponding bits of two others, a function that takes the majority bit across three words, rotations, constants, and 32-bit additions. After the rounds, add the eight working words to the starting state word by word. The result becomes the state for the next block.

Chaining blocks this way lets SHA-256 process a file without storing the whole thing. Because computing a digest requires no secret, anyone who can replace the file can also compute a new digest. If you share a secret with the sender and want to authenticate the file, you can use SHA-256 as a building block for an authentication tag. How HMAC-SHA-256 works