A trail of experiments

Rediscovering Keccak-256

Suppose you need to tell whether two files are the same without keeping both around. You get to keep a short fingerprint and one small piece of working memory. What do you put in that memory? What do you do when the next bytes come in?

Let’s try a few answers and keep the parts that work. This isn’t how Keccak was historically invented; it’s a route to seeing why its pieces fit together.

01 / Notice a change

A fingerprint the size of a byte

Say we send a byte over a noisy link. Sending a second copy would work, but can we send a short check that doesn’t grow with the message? A cyclic redundancy check (CRC) is a kind of binary long division: the divisor is a fixed bit pattern, and where long division would subtract, this one XORs. Keep the remainder and throw away the quotient. You can update that remainder as bits arrive.

Here’s CRC-8 with one byte to start. Flip a bit after the sender records the check. The receiver recomputes it from what arrived. Compare the two remainders.

We got two useful ideas: a fixed-size result and a small state that carries forward. But the knob we just turned simulates an accident, not someone choosing a replacement. A CRC’s XOR arithmetic is linear, so it’s not designed to make matching checks hard to construct. Also, if someone can replace both the message and the expected fingerprint, even a cryptographic hash alone doesn’t authenticate it; we need a trusted fingerprint or something like a signature.

Any fixed-size fingerprint has collisions: more possible files than possible answers. For a cryptographic hash, the goal is to make finding collisions or a replacement for a given file computationally hard, not impossible in principle.

02 / Carry something forward

Don’t start each block from scratch

What if we hash each chunk on its own? Keeping a list of the results would make our fingerprint grow with the file. Keeping only the last result would forget every earlier chunk. Let the previous result be an input instead. Now every block can affect the next step, but we still only need room for one block and one state.

Follow the carried state, not the message bytes. Each arrow takes it into another call.
  1. Startinitial state
  2. First blockF(state, block₁)
  3. Second blockF(state, block₂)
  4. Finishfinal state
state = initial_state
for block in pad_with_length(message):
    state = compress(state, block)
return state

This is the shape of Merkle–Damgård hashing. MD4 and MD5 used it; SHA-256, from the SHA-2 family, uses the same general construction with a different compression function. “Compression” here isn’t ZIP: the input is a state plus a block, and the output is just one new state. The construction is worth keeping in mind even though MD4 and MD5 are no longer safe choices where collision resistance matters.

We’ll keep the idea that the last state feeds the next block. But let’s try a different division of labor: a small operation to let bytes in, and a mixer that only knows about the state.

03 / Give the state a window

Mix more than you can see

Instead of giving the mixer a separate input block, line the block up with the front of the state and XOR it in. That leaves the rest untouched—for now. Then mix the whole state. On the way out, read only from the front. The part we touch directly is the rate; the rest is the capacity.

The four-byte toy below gives both regions the same size. Keccak-256 uses a 136-byte rate and a 64-byte capacity.

Rate
XOR in here. Read out here.

Capacity
Only the mixer touches these bytes.

Step once to XOR in a block and once to mix. Which two bytes sit still during XOR? Do they stay still during the mix? Repeat for the next block: the first block isn’t waiting anywhere else, but it still affects what happens.

What does “mix” do in this toy?

Name the rate bytes a, b and the capacity bytes c, d. The assignments here are sequential; each one uses the values we have at that point. rotl8 shifts the bits left and wraps the top bit around to the bottom.

c ^= a
d ^= b
a ^= rotl8(d, 1)
b ^= rotl8(c, 1)
return [b, c, d, a]

To reverse it, undo the shuffle, then undo each XOR in reverse order. That’s how something can be a permutation even though it does more than just move bytes around.

There’s no need for a new operation to get bytes out. Read the rate after the last mix. Reading again without changing anything would repeat the same bytes. If we need another window’s worth, mix again rather than reading the hidden half. Try that last step in the toy.

state = all_zeroes(rate_size + capacity_size)
for block in padded_blocks:         # each is one rate wide
    state.rate ^= block
    state = permute(state)          # mixes rate AND capacity

result = read(state.rate, up_to = desired_length)
while length(result) < desired_length:
    state = permute(state)
    result += read(state.rate, up_to = remaining_length)
return result

That’s the sponge construction: absorb blocks, then squeeze bytes. A permutation is a reversible rearrangement of the set of possible states. The hash as a whole isn’t reversible: we don’t publish the whole state or even the whole rate. The toy shows the wiring, not security; its state is tiny and its mixer is deliberately simple.

04 / Build the mixer

Get a bit out of its own neighborhood

We could shuffle the bytes, but then each output byte would still come from just one input byte. We could XOR nearby words, but if we only use XORs, rotations and rearrangements, changes still propagate by linear rules. We need to move information across the grid and make the effect of a change depend on what else is there.

Keccak-f[1600] lays out 1,600 bits as 25 words of 64 bits, called lanes, in a 5×5 grid. It repeats five moves. You can see the effect of each one in the real state below.

  1. θ · Across columnsXOR each column down to a parity word. Use the neighboring columns’ parities to influence every lane of the current column.
  2. ρ · Within a laneRotate bits by an offset tied to the lane’s position, so bits don’t stay lined up in the same positions.
  3. π · Across the gridMove entire lanes to new coordinates. For example, (1, 0) goes to (0, 2); the word itself doesn’t change in this move.
  4. χ · Across a rowUse a bit from one neighbor to decide whether another neighbor flips a bit here. The AND makes this step nonlinear.
  5. ι · Break symmetryXOR a round-specific constant into (0, 0). The other four moves alone would keep an all-zero state at zero.
Exact round pseudocode and tables

Indices x and y wrap modulo 5. Every value is a 64-bit word; ~ flips exactly those 64 bits. Assignments over a grid are simultaneous: don’t overwrite a neighbor while you still need it.

for rc in round_constants:               # 24 rounds
    C[x] = A[x,0] ^ A[x,1] ^ A[x,2] ^ A[x,3] ^ A[x,4]
    D[x] = C[x-1] ^ rotl64(C[x+1], 1)
    T[x,y] = A[x,y] ^ D[x]                 # θ
    R[x,y] = rotl64(T[x,y], offset[y][x])  # ρ
    B[y, 2*x + 3*y] = R[x,y]               # π
    A[x,y] = B[x,y] ^ (~B[x+1,y] & B[x+2,y]) # χ
    A[0,0] ^= rc                          # ι

Rotation offsets in decimal, one row per y:

 0   1  62  28  27
36  44   6  55  20
 3  10  43  25  39
41  45  15  21   8
18   2  61  56  14

Round constants in hex, read left to right, top to bottom:

0000000000000001  0000000000008082
800000000000808a  8000000080008000
000000000000808b  0000000080000001
8000000080008081  8000000000008009
000000000000008a  0000000000000088
0000000080008009  000000008000000a
000000008000808b  800000000000008b
8000000000008089  8000000000008003
8000000000008002  8000000000000080
000000000000800a  800000008000000a
8000000080008081  8000000000008080
0000000080000001  8000000080008008

The motivations get us to the right kinds of operations. They don’t magically derive these exact offsets, constants, or number of rounds; those are parameters of the published design.

05 / Assemble it

From a message to Keccak-256

One loose end: our sponge takes whole blocks, and a message can stop anywhere. Just filling with zeros would make a message and the same message with an extra zero byte look alike. Put a marker right after the data, then another at the end of the last block. Reserve space for those markers even if the data fits exactly.

For byte-aligned input, original Keccak starts that padding with 01, uses zeros as needed, and sets the 80 bit in the last byte. When only one slot is left, the two markers share it (81). SHA3-256 uses the same permutation and dimensions but starts with 06 instead.

function keccak256(message_bytes):
    padded = copy(message_bytes)
    padded.append(0x01)
    while length(padded) % 136 != 0:
        padded.append(0x00)
    padded[last] |= 0x80

    A = 25 zero lanes                    # 200 bytes
    for block in split_every(padded, 136):
        for i = 0 … 16:                  # 136-byte rate
            A[i] ^= load_u64_le(block, offset = 8*i)
        A = keccak_f_1600(A)              # all 25 lanes, 24 rounds

    return store_u64_le(A[0], A[1], A[2], A[3])

A[i] means lane (i mod 5, floor(i / 5)). Both loading and storing put the first byte at the least significant end of its lane. Four lanes are already 32 bytes, so we don’t need a second squeeze.

Try abc. The first XOR gives lane (0, 0) the value 0000000001636261. Open Inspect the 25 lanes to follow it into the first round. Then use Show final output lanes to jump to round 24. The first byte of the digest is the rightmost byte of the first output lane. That’s a useful check that the diagram and pseudocode use the same byte order.

If you want to keep pulling on this thread, Inside Keccak-256 has a full byte view and every intermediate round. To compare the construction with its reference, see the Keccak team’s specification summary and FIPS 202.