Ch.23: Algorithms: How SHA-256 Hashing Actually Works

Outline

Transcript

0:00 SHA-256 calculates a fixed-size fingerprint, called a digest, for checking whether data changed. It contains 256 bits, zeros or ones. How can a whole file affect something that short? By repeatedly updating eight working numbers. The file can grow while that workspace stays the same size. We'll follow one changed letter into those updates and calculate an actual output bit ourselves. Imagine a developer downloads an installer truncated in transit. Its digest fails to match the publisher's reference, so the developer catches the broken download before running it. Right. The US standards agency, NIST, publishes SHA's recipe and a separate worked example. Those links are in the description.

0:41 We'll use its three-letter input, a, b, c, and change the final letter to b. Small input, same calculation as a file. So the input begins with actual bytes. A byte contains 8 bits. Our lowercase letters a, b, c have byte values 97, 98 and 99, with no space or newline. Take a 1-bit change from c to b: the last value falls from 99 to 98. Their first 7 bits match; only the last bit differs. The encoding assigns these numbers to the letters; we're changing 1 byte's value. We can write those same byte values more compactly, in hexadecimal: base 16.

1:20 Each printed digit represents 4 bits, so two digits describe 1 byte. Our 3 bytes become six one, six two and six three. For example, six one means six sixteens plus 1: 97. Our changed last byte becomes six two. Same data, a shorter written notation. SHA-256 groups 4 bytes into a 32-bit word, one number with 32 bit positions. Our three input bytes need the preparation step before that grouping is complete. We don't even fill one word. How does the algorithm prepare such a small input without confusing it with the material it adds? First, padding completes the input block.

1:59 Append one 1-bit after the message, then zeros, leaving space for the original message length at the end. A block holds 512 bits: 16 32-bit words. Our 3 bytes contained 24 bits, and the ending records that length in its own 64-bit field. The message and padding before that field occupy 448 bits. Add the length field and the block totals 512. The delimiter and recorded length jointly distinguish the original input from padding. 64 bytes for three letters. Fairly generous wrapping. And if the ending won't fit, we need another block rather than quietly leaving out the length.

2:39 Our example does fit. The first word contains three letter bytes followed by the first padding byte. The last word records 24. Both inputs have exactly the same padding. Now the changed letter has a position inside a full word. Its byte is one place left of the rightmost padding byte. What does that position do to the one-unit decrease? Think of a decimal digit: moving one place left multiplies its value by 10. A byte has 256 possible values, so 1 byte-position left means a multiplier of 256. So that one-unit byte decrease makes the complete message word 256 smaller. The padding stays fixed.

3:21 Yes. We've prepared the message and located its change. Next that word joins the working numbers, where its influence can move beyond the input position. With the message word ready, SHA starts eight 32-bit working numbers at fixed public values. Call them a through h. Those labels name positions, not our three input letters. Arrange the positions as two rows of 4: a through d, then e through h. A round is one update of all eight numbers. Which calculation receives our message word? The first of two temporary sums: five numbers added together.

3:57 They are old h, two calculated numbers from the state, this round's public constant and the message word. We'll open those middle two calculations shortly. Both inputs start with identical working numbers and the same constant. Those four ingredients therefore match; only the message word falls by 256. Which makes the first sum fall by that amount in this pair. The word-width limit doesn't change that difference here. The second sum uses only the unchanged starting numbers, so its value stays fixed. New a adds the two sums.

4:29 One has fallen and one hasn't, so new a falls by 256. New e adds old d to the first sum, giving the same decrease. Two positions change immediately. The other six receive copies of old numbers. That leaves six matching values between our inputs after this first round. We can follow the difference without reading billion-sized values aloud. But I want to make something inside those sums, rather than accept their names. Can we calculate one actual bit? We can. Take the rightmost bit, with no lower position sending in a carry.

5:04 We need bit movement and three simple bit rules to calculate it. Now bit movement supplies the first operation for that calculation. Rotation is like an eight-seat carousel: what leaves one end returns at the other. A logical shift is an eight-slot conveyor: it drops what leaves and puts zeros into the opening. For example, picture an eight-position row with 1 at the far right and zeros elsewhere. Rotate that original row right by three places: the one wraps left, then moves twice more, ending 3rd from the left.

5:36 Start from the original row again and shift right by three. The only one falls off, so all eight positions become zero. We're illustrating with 8 bits; the real words have 32. So the contrast is what happens at the boundary: rotation keeps a departing bit in the result; the shift discards it from the result and zero-fills. The sums use several rotated copies together. XOR, exclusive or, combines their corresponding bit positions. It outputs one when an odd number of the input bits are one. For 3 bits, one, zero, zero gives one.

6:11 One, zero, one gives zero because two inputs are one. I can calculate that without holding an entire word. And rotating each copy by a different distance brings different original positions together. XOR then makes one output bit depend on several source positions. The exact distances are specified by the public recipe. Oh, I see. The copies line up different sources before they are combined. Now we also need the rules that combine different working numbers. Now combine words using Choose. Its first input is a selector: one chooses the second input's bit; zero chooses the 3rd.

6:47 It's a switch picking between two possible answers. Let me run one position. Inputs one, zero, one. The selector says take the second input, so Choose gives zero. What would Majority do with that same triple? Majority gives 1: at least two inputs are one. Instead of obeying a selector, it takes a three-person vote. Both rules work separately at every position across the word. Selection versus voting. Same three inputs, different rule and result. So selection and voting stay in their own positions.

7:19 Addition can reach the next position through a carry. In binary, one plus one writes zero here and carries one into the next position on the left. Like decimal addition carrying past nine, but a binary position has only zero and one. And the complete word keeps its fixed width. For example, 8-bit 250 plus 10 gives 260. Remove a span of 256 and four remains. That's wrapped addition. Actual SHA-256 retains 32 bits, discarding overflow beyond that width. Carries inside the word still pass into the next position; they aren't discarded at every byte.

7:56 We have the pieces now: rotated copies and XOR, selection, voting and addition with carries. Our actual one-position calculation can use each rule with tiny numbers. Let's use the real starting state. We'll calculate the rightmost bit of both temporary sums, then use those bits to calculate new a and new e. Now take the initial e for our real bit calculation. It has ones in its seven rightmost positions. Count from position zero at the right edge. One specified rotation moves that word right by six.

8:26 So the original bit six places left of the edge moves into the rightmost position. It's one of those seven ones. That rotated copy ends in one. Right. The other two copies rotate by 11 and 25; their rightmost bits are zero. Our three versions contribute one, zero and zero. We can combine them now. XOR gives one, because one input bit is set. Choose receives the actual e, f and g bits one, zero, one. With e selecting f, Choose takes f's zero at this position. Old h ends in one. This round's constant and message word both end in zero.

9:02 So the five ingredients at this position are one, one, zero, zero and zero. That totals two. We put zero in that rightmost position and carry one to the left as we finish that word. Keep that rightmost 0: it's our first temporary result's bit. Keeping the first result's zero, let's calculate the second. The rotated copies of a contribute one, one and zero here; XOR makes zero. Majority of the actual old a, b and c bits one, one, zero makes one. Zero plus one makes the second temporary result end in one.

9:36 Add that one to the zero we kept: new a ends in one. For new e, old d's last bit is zero, as is the first sum's. Adding them leaves zero in new e. Our calculated bits agree with the official first-round row. We followed one real position; the full words still have 31 others. The carry keeps participating farther left. Our changed input bit was a byte-position over, so this isn't a claim that we traced that same bit. We calculated a and e. Where do the other six working values go? Now those six values move through copies in our two four-position rows.

10:13 Each newly calculated number enters the front of its row; the previous first three move one position over. I think I'd lose eight moving positions in one long row. In the first row, new a pushes old a into b and the next values toward d. New e similarly pushes old e into f. My first thought is to overwrite a as soon as we've calculated it. In a code review, I'd watch for a later calculation accidentally reading that new value when it still needs the old one. That would mix two versions of the state inside one round.

10:47 Keep the old values available for both sums and all six copies, then install the complete update together. And old h has no copy position after it. Did we discard its contribution? Old h already contributed to the first temporary sum, helping calculate new a and new e. New h receives old g. Ah, its effect is already in those calculated results. Our original-input state matches every published row, and our separately computed changed-input result lets us check where the difference goes next. In the second round, the changed a moves into b and the changed e into f.

11:24 The new sums also calculate a and e from changed inputs. So in this exact pair, four positions now differ: a, b, e and f. Two differences came through copies, alongside the two freshly calculated positions. Yes. The message word for that second round is zero in both inputs; the changed working state is already carrying the effect forward. This isn't a rule saying the count doubles each round. We've followed two updates, but the input block holds 16 message words. Where do the message inputs for 64 rounds come from?

11:57 A separate message schedule supplies those round inputs. Its entries come from the prepared block and from earlier entries, while the working state keeps its eight positions. So the message schedule uses a separate sequence. Picture numbered recipe cards: their numbers are addresses, while each holds a word. The first 16 cards hold the block's words, at addresses zero through 15. Our changed letter is in card zero. When we make the next card, 16, does that change reach it? Yes. That entry reads cards 14, nine, one and zero.

12:30 It mixes the words at 14 and one, then adds those mixed results to the words at nine and zero, retaining 32 bits. For both our inputs, 14, nine and one hold zero. Rotating or shifting zero still gives zero. So their three contributions disappear from this addition, leaving card zero's word. Which makes card 16 equal card zero in this example. Change the letter, and card 16 becomes 256 smaller too. The change now has another place to enter a later round. Expansion adds entries, then, without guaranteeing different values.

13:04 The two mixes still matter for inputs whose source words aren't zero. They XOR differently rotated versions with a copy shifted right and filled with zeros. Each mix has its own fixed distances in the full recipe. The source addresses move as we create entries. For card 17, looking two addresses back reaches 15, which holds our length word, 24. And when a scheduled value repeats, the working state and round constant have changed. Reusing a value doesn't restart the entire round from its original inputs.

13:35 We calculate 64 schedule entries and consume one each round. The message keeps entering the updates without turning the eight working positions into 64. Now the block's 64 rounds have finished. Are the eight working numbers already the digest? One addition remains. Add each final working number to its corresponding incoming state number, retaining 32 bits. First to first, second to second, through all eight. That's called feedforward. The incoming numbers were copied before the block's rounds began.

14:05 For our single block, they're the standard's initial values. A longer input sends the state we just calculated into the next block. That block gets its own message schedule and 64 rounds, then performs the same final addition. So we don't restart from the published initial values each time. Each completed block affects the state passed to the next, while we carry only eight hash-state numbers between blocks. Once the last block finishes, place its eight 32-bit state words end to end. Eight times 32 gives the 256 bits of the final digest.

14:39 So the output stays small while the number of blocks grows. Does our calculated digest match the published result? Now we can check the final digest against NIST's worked example. Our implementation and Python's SHA-256 implementation match it exactly. Written in hexadecimal, it has 64 digits, 4 bits per digit. And our input a, b, b differs by just 1 bit from a, b, c, with the same 24-bit length. How far did that difference spread by the end? Our independent calculation finds 124 changed digest bits.

15:14 We followed two differing working words, then four, before the later updates produced a very different fingerprint. Huh, close to half the output. That's a measurement for this pair, not an exact-half rule for every input or a proof that the algorithm is secure. Some inputs must share a digest: there are more possible files than 256-bit outputs. Those shared outputs are called collisions; the cryptographic design aims to make finding them difficult. So a digest helps compare data. If somebody replaces both an installer and its reference digest, would the match tell us who supplied it?

15:50 So no. A replacement file can match its replacement reference. We still need that reference to come from somewhere we trust. A tiny input can also be guessed. For example, if it's one decimal digit, zero through nine, hash those 10 candidates and compare. The guesses use the same calculation. Back to calculating a file's digest, each block receives the same schedule expansion and round processing. More input means more blocks of work; the carried hash state stays at eight words. I can picture the work behind that short fingerprint now.

16:22 We calculated 1 bit and tracked the input's effect through two updates. Thanks for listening to Learning Podcasts.