BabyBlock is small enough to do by hand, but it’s a Feistel cipher, and the Advanced Encryption Standard (AES) isn’t. AES is too big to do by hand. Simplified AES (S-AES) sits in between. It was designed for students in 2003 by Mohammad Musa, Edward Schaefer and Stephen Wedig, and it uses the same four steps as AES on a much smaller block.
| BabyBlock | S-AES | AES | |
|---|---|---|---|
| Block size | 4 bits | 16 bits | 128 bits |
| Key size | 4 bits | 16 bits | 128 bits (or 192 or 256) |
| Rounds | 3 | 2 | 10 (or 12 or 14) |
| Structure | Feistel | substitute and mix | substitute and mix |
| By hand? | easy | yes, carefully | not really |
S-AES is built from four operations:
Nibbles, Hexadecimal and the State¶
A nibble is 4 bits, which is exactly one hexadecimal digit (see positional number systems).
| Hex | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Bits | 0000 | 0001 | 0010 | 0011 | 0100 | 0101 | 0110 | 0111 | 1000 | 1001 | 1010 | 1011 | 1100 | 1101 | 1110 | 1111 |
A 16-bit block is four nibbles, or four hex digits. For example, 0011 0110 0111 1001 is 3679.
S-AES arranges the four nibbles in a 2×2 grid called the state. The grid is filled down the columns: the 1st nibble goes top left, the 2nd bottom left, the 3rd top right and the 4th bottom right. So 3679 becomes
with 3, 6 in the left column and 7, 9 in the right column. Every step changes this grid, and at the end you read it back out the same way, down the columns.
In Python, we’ll keep the state as a list of 4 nibbles in that order, [s0, s1, s2, s3], where s0 and s1 are the left column and s2 and s3 are the right column.
def to_state(block):
# Split a 16-bit number into 4 nibbles: [top left, bottom left, top right, bottom right]
return [(block >> 12) & 15, (block >> 8) & 15, (block >> 4) & 15, block & 15]
def from_state(state):
return (state[0] << 12) | (state[1] << 8) | (state[2] << 4) | state[3]
def print_state(state):
print(f'{state[0]:X} {state[2]:X}')
print(f'{state[1]:X} {state[3]:X}')
print_state(to_state(0x3679))3 7
6 9
In Python, 0x3679 is the number written in hex, and the format code X prints a number in hex.
Our Example¶
This page follows one encryption all the way through.
plaintext
3679=0011 0110 0111 1001key
AD76=1010 1101 0111 0110
The key is used three times, as the round keys , and . All three come from the one 16-bit key. For this key they are = AD76 (the key itself), = A8DE and = 66B8. The section on the key schedule shows how to make them.
Here is the whole plan. Round 2 has no mix columns step.
Step 1: Add Round Key¶
XOR each nibble of the state with the matching nibble of the round key. This is the only step that uses the key.
For example, the top left nibble is 0011 ⊕ 1010 = 1001 = 9. The new state is 9B0F.
def add_round_key(state, round_key):
key_state = to_state(round_key)
return [state[i] ^ key_state[i] for i in range(4)]
state = add_round_key(to_state(0x3679), 0xAD76)
print_state(state)9 0
B F
Step 2: Nibble Substitution¶
Replace every nibble with its entry in the S-box. Each nibble changes on its own, and nothing moves.
| in | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| out | 9 | 4 | A | B | D | 1 | 8 | 5 | 6 | 2 | 0 | 3 | C | E | F | 7 |
Every output appears exactly once, so this step can be undone. For our state, S(9) = 2, S(B) = 3, S(0) = 9 and S(F) = 7, so 9B0F becomes 2397.
S_BOX = [0x9, 0x4, 0xA, 0xB, 0xD, 0x1, 0x8, 0x5, 0x6, 0x2, 0x0, 0x3, 0xC, 0xE, 0xF, 0x7]
def substitute(state, box=S_BOX):
return [box[nibble] for nibble in state]
state = substitute(state)
print_state(state)2 9
3 7
Why an S-box?¶
The LFSR ciphers fell to known-plaintext attacks because everything in them was linear: just XORs, so a system of equations could solve them (see LFSR security). The S-box isn’t linear. A linear function would satisfy , and the S-box doesn’t.
print(f'S(1 ⊕ 2) = S(3) = {S_BOX[1 ^ 2]:X}')
print(f'S(1) ⊕ S(2) = {S_BOX[1]:X} ⊕ {S_BOX[2]:X} = {S_BOX[1] ^ S_BOX[2]:X}')S(1 ⊕ 2) = S(3) = B
S(1) ⊕ S(2) = 4 ⊕ A = E
The S-box is the confusion step from the introduction to block ciphers.
Step 3: Shift Rows¶
The top row stays put, and the bottom row swaps its two nibbles. After this step, each column holds nibbles that started in different columns.
The state 2397 becomes 2793.
def shift_rows(state):
# Swap the two nibbles in the bottom row (positions 1 and 3)
return [state[0], state[3], state[2], state[1]]
state = shift_rows(state)
print_state(state)2 9
7 3
Step 4: Mix Columns¶
Mix columns combines the two nibbles in each column, so that each new nibble depends on both of the old ones:
But what do and mean for nibbles? Ordinary arithmetic doesn’t work, so we need a new kind.
The problem with ordinary multiplication¶
Ordinary multiplication gives answers that are too big: = 100100, which needs 6 bits. A nibble only holds 4.
You might try wrapping around, the way the Caesar cipher works mod 26. Here is for every nibble .
print('x ', ' '.join(f'{x:X}' for x in range(16)))
print('4x mod 16 ', ' '.join(f'{4 * x % 16:X}' for x in range(16)))x 0 1 2 3 4 5 6 7 8 9 A B C D E F
4x mod 16 0 4 8 C 0 4 8 C 0 4 8 C 0 4 8 C
All 16 inputs land on just 4 outputs. For example, , so the receiver couldn’t tell which one was sent and couldn’t decrypt. We need a multiplication that can always be undone.
Treat a nibble as a polynomial¶
Write each nibble as a polynomial whose coefficients are its bits, just like the characteristic polynomials of LFSRs:
| bits | 1 | |||
|---|---|---|---|---|
| 1011 | 1 | 0 | 1 | 1 |
So 1011 , 0100 , and 1001 . Every coefficient is 0 or 1.
Adding is XOR. Add matching coefficients mod 2. Since , matching terms cancel:
Multiplying by is a shift. Multiplying by raises every power by one, so the bits move one place to the left: 0101 times is = 1010. But sometimes a bit falls off the left end. For example, 1001 times is , and doesn’t fit in 4 bits.
The wrap-around rule: ¶
When we work mod 26, the number 26 counts as 0. Here, the polynomial counts as 0. So , which means
(Subtracting is the same as adding when coefficients are mod 2.) In bits: if a 1 spills off the left end, drop it and XOR 0011. For example, 1001 times is 10010. A 1 spilled, so drop it to get 0010, then XOR 0011 to get 0001. Check with polynomials: .
The polynomial is a maximum-period 4-bit LFSR polynomial. That’s no accident: it can’t be factored, which is what makes every multiplication undoable.
def times_x(nibble):
# Multiply a nibble by x: shift left, and if a 1 spills off the left, drop it and XOR 0011
nibble = nibble << 1
if nibble & 0b10000:
nibble = (nibble & 0b1111) ^ 0b0011
return nibble
def gf_multiply(a, b):
# Multiply two nibbles: add (XOR) a, a·x, a·x², a·x³ for each 1 bit of b
result = 0
for i in range(4):
if b & 1:
result ^= a
a = times_x(a)
b = b >> 1
return result
print(f'1001 times x = {times_x(0b1001):04b}')1001 times x = 0001
Multiplying by 4¶
Since 4 = 0100 , multiplying by 4 means multiplying by twice. For :
1001→ shift →10010→ a 1 spilled, so drop it and XOR0011→00010001→ shift →0010(no spill)
So . Check with polynomials: , and , so the product is = 0010.
Here’s the whole times-4 table, next to the mod 16 version that failed.
times_4 = [gf_multiply(4, x) for x in range(16)]
print('x ', ' '.join(f'{x:X}' for x in range(16)))
print('4x mod 16 ', ' '.join(f'{4 * x % 16:X}' for x in range(16)))
print('4 · x (new)', ' '.join(f'{y:X}' for y in times_4))
print('different outputs:', len(set(times_4)))x 0 1 2 3 4 5 6 7 8 9 A B C D E F
4x mod 16 0 4 8 C 0 4 8 C 0 4 8 C 0 4 8 C
4 · x (new) 0 4 8 C 3 7 B F 6 2 E A 5 1 D 9
different outputs: 16
The new row hits all 16 values, each exactly once, so multiplying by 4 can always be undone.
You only need two rules to use it: add with XOR, and replace with .
Solution to Exercise 1
1101→ shift →11010→ a 1 spilled, so drop it and XOR0011→10011001→ shift →10010→ a 1 spilled, so drop it and XOR0011→0001
So , which matches the table. Check with polynomials: , and , so the product is .
Mix columns, worked out¶
For each column, with for addition and the times-4 table for multiplication:
If you’ve seen matrices, this is the matrix times the column.
Our state is 2793, with columns 2, 7 and 9, 3.
Left column: new top =
0010⊕1111=1101= D. New bottom =1000⊕0111=1111= F.Right column: new top =
1001⊕1100=0101= 5. New bottom =0010⊕0011=0001= 1.
After mix columns the state is DF51.
def mix_columns(state, matrix=(1, 4)):
# With matrix (a, b), each column (top, bottom) becomes (a·top ⊕ b·bottom, b·top ⊕ a·bottom)
a, b = matrix
new_state = []
for top, bottom in [(state[0], state[1]), (state[2], state[3])]:
new_state.append(gf_multiply(a, top) ^ gf_multiply(b, bottom))
new_state.append(gf_multiply(b, top) ^ gf_multiply(a, bottom))
return new_state
state = mix_columns(state)
print_state(state)D 5
F 1
Finishing the Example¶
Round 1 ends by adding round key = A8DE. Round 2 substitutes, shifts rows and adds = 66B8, with no mix columns.
state = add_round_key(state, 0xA8DE)
print(f'after round 1: {from_state(state):04X}')
state = substitute(state)
print(f'round 2 substitute: {from_state(state):04X}')
state = shift_rows(state)
print(f'round 2 shift rows: {from_state(state):04X}')
state = add_round_key(state, 0x66B8)
print(f'ciphertext: {from_state(state):04X}')after round 1: 778F
round 2 substitute: 5567
round 2 shift rows: 5765
ciphertext: 31DD
Why skip mix columns at the end?¶
Mix columns doesn’t use the key. It’s a fixed, public recipe. If the last round ended with mix columns, anyone could undo it from the ciphertext, without the key. It would cost work and add no security. Real AES also skips mix columns in its last round.
The Key Schedule¶
The round keys come from the key one byte (8 bits, two nibbles) at a time. Split the key into two bytes, and . Together they are . Then
so and . Everything depends on the function , which does three things to a byte:
The S-box is there for the same reason as before. Without it, the round keys would just be XORs of key bits, which is linear, like an LFSR.
The round constants are powers of , made with the same rule as mix columns. Round 1 uses = 1000, and round 2 uses = 0011. Each one is the last one times : 1000 → shift → 10000 → drop the 1 and XOR 0011 → 0011. The right nibble of each round constant is 0000. (AES does the same thing with bytes: 01, 02, 04, 08, ....)
For the key AD76, = AD and = 76.
| Step | Bits | Hex |
|---|---|---|
| Start: | 0111 0110 | 76 |
| Rotate (swap nibbles) | 0110 0111 | 67 |
| Substitute each nibble: S(6) = 8, S(7) = 5 | 1000 0101 | 85 |
| XOR round constant | 1000 0000 | 80 |
| 0000 0101 | 05 | |
| AD ⊕ 05 | A8 | |
| A8 ⊕ 76 | DE |
So = A8DE. The same steps on = DE with the round 2 constant give = 66B8.
def g(byte, round_constant):
left, right = byte >> 4, byte & 15
rotated = (right << 4) | left # swap the nibbles
substituted = (S_BOX[rotated >> 4] << 4) | S_BOX[rotated & 15]
return substituted ^ round_constant
def key_expansion(key):
w0, w1 = key >> 8, key & 255
w2 = w0 ^ g(w1, 0b10000000)
w3 = w2 ^ w1
w4 = w2 ^ g(w3, 0b00110000)
w5 = w4 ^ w3
return [(w0 << 8) | w1, (w2 << 8) | w3, (w4 << 8) | w5]
[f'{k:04X}' for k in key_expansion(0xAD76)]['AD76', 'A8DE', '66B8']The Whole Cipher¶
Putting it all together:
def saes_encrypt(plaintext, key, trace=False):
K0, K1, K2 = key_expansion(key)
steps = [('plaintext', to_state(plaintext))]
state = add_round_key(to_state(plaintext), K0)
steps.append(('add round key K0', state))
# Round 1
state = substitute(state)
steps.append(('round 1: substitute', state))
state = shift_rows(state)
steps.append(('round 1: shift rows', state))
state = mix_columns(state)
steps.append(('round 1: mix columns', state))
state = add_round_key(state, K1)
steps.append(('round 1: add round key K1', state))
# Round 2 (no mix columns)
state = substitute(state)
steps.append(('round 2: substitute', state))
state = shift_rows(state)
steps.append(('round 2: shift rows', state))
state = add_round_key(state, K2)
steps.append(('round 2: add round key K2', state))
if trace:
for name, s in steps:
value = from_state(s)
print(f'{name:28}{value:04X} {value >> 8:08b} {value & 255:08b}')
return from_state(state)
ciphertext = saes_encrypt(0x3679, 0xAD76, trace=True)plaintext 3679 00110110 01111001
add round key K0 9B0F 10011011 00001111
round 1: substitute 2397 00100011 10010111
round 1: shift rows 2793 00100111 10010011
round 1: mix columns DF51 11011111 01010001
round 1: add round key K1 778F 01110111 10001111
round 2: substitute 5567 01010101 01100111
round 2: shift rows 5765 01010111 01100101
round 2: add round key K2 31DD 00110001 11011101
The ciphertext is 31DD.
Decrypting S-AES¶
To decrypt, run every step backwards, using the round keys in reverse order.
Add round key: XOR the same round key again. It cancels.
Shift rows: swap the bottom row again.
Nibble substitution: use the inverse S-box (read the table from the bottom row up).
Mix columns: use the same recipe with 9 and 2 in place of 1 and 4. The matrix undoes .
BabyBlock, a Feistel cipher, decrypted by running its own steps again. S-AES needs an undo for every step.
INVERSE_S_BOX = [S_BOX.index(n) for n in range(16)]
print('inverse S-box:', ' '.join(f'{n:X}' for n in INVERSE_S_BOX))
# Check that [9 2; 2 9] undoes [1 4; 4 1] for all 256 possible states of one column
undoes = all(mix_columns(mix_columns([a, b, 0, 0]), (9, 2)) == [a, b, 0, 0] for a in range(16) for b in range(16))
print('[9 2; 2 9] undoes mix columns:', undoes)
def saes_decrypt(ciphertext, key):
K0, K1, K2 = key_expansion(key)
state = add_round_key(to_state(ciphertext), K2)
state = shift_rows(state)
state = substitute(state, INVERSE_S_BOX)
state = add_round_key(state, K1)
state = mix_columns(state, (9, 2))
state = shift_rows(state)
state = substitute(state, INVERSE_S_BOX)
state = add_round_key(state, K0)
return from_state(state)
print(f'{saes_decrypt(0x31DD, 0xAD76):04X}')inverse S-box: A 5 9 B 1 7 8 F 6 0 2 3 C 4 D E
[9 2; 2 9] undoes mix columns: True
3679
How Far Does One Change Spread?¶
Flip one bit of the plaintext, encrypt again with the same key, and compare the states after each step. The code below does this for 2,000 random plaintexts and keys and all 16 bit positions.
import random
random.seed(4200)
def all_states(plaintext, key):
# Every state during encryption: plaintext, add K0, round 1 (4 steps), round 2 (3 steps)
K0, K1, K2 = key_expansion(key)
states = [to_state(plaintext)]
state = add_round_key(states[0], K0); states.append(state)
state = substitute(state); states.append(state)
state = shift_rows(state); states.append(state)
state = mix_columns(state); states.append(state)
state = add_round_key(state, K1); states.append(state)
state = substitute(state); states.append(state)
state = shift_rows(state); states.append(state)
state = add_round_key(state, K2); states.append(state)
return states
def bits_different(state1, state2):
return bin(from_state(state1) ^ from_state(state2)).count('1')
def nibbles_different(state1, state2):
return sum(1 for i in range(4) if state1[i] != state2[i])
step_names = ['start', '+K0', 'sub', 'shift', 'mix', '+K1', 'sub', 'shift', '+K2']
bit_totals = [0] * 9
column_after_round_1 = set() # which nibbles differ after round 1
ciphertext_nibbles = set() # how many ciphertext nibbles differ
trials = 0
for _ in range(2000):
plaintext, key = random.randrange(65536), random.randrange(65536)
states = all_states(plaintext, key)
for bit in range(16):
flipped = all_states(plaintext ^ (1 << bit), key)
for i in range(9):
bit_totals[i] += bits_different(states[i], flipped[i])
column_after_round_1.add(tuple(i for i in range(4) if states[5][i] != flipped[5][i]))
ciphertext_nibbles.add(nibbles_different(states[8], flipped[8]))
trials += 1
print('after ', ' '.join(f'{name:>5}' for name in step_names))
print('bits changed', ' '.join(f'{total / trials:5.1f}' for total in bit_totals))
print('nibbles that differ after round 1:', sorted(column_after_round_1))
print('number of ciphertext nibbles that differ:', ciphertext_nibbles)after start +K0 sub shift mix +K1 sub shift +K2
bits changed 1.0 1.0 2.0 2.0 4.0 4.0 4.2 4.2 4.2
nibbles that differ after round 1: [(0, 1), (2, 3)]
number of ciphertext nibbles that differ: {2}
Follow the change through the steps.
Adding a round key and substituting keep the change inside one nibble. The S-box can change more bits of that nibble, but nothing leaves it.
Shift rows moves that nibble but doesn’t spread it.
Mix columns spreads it to both nibbles of its column. After round 1, exactly 2 nibbles differ, always a whole column: nibbles 0 and 1 (the left column) or nibbles 2 and 3 (the right column).
In round 2, substitution keeps the change in those 2 nibbles, and shift rows moves the bottom one into the other column.
There’s no mix columns in round 2, so nothing spreads it further.
So one flipped plaintext bit always changes exactly 2 of the 4 ciphertext nibbles: the top of one column and the bottom of the other, on a diagonal. That’s about 4 of the 16 bits, short of the goal of about half (8 bits).
S-AES falls short because its two rounds contain only one mix columns step. If round 2 also mixed its columns, the two changed nibbles, now in different columns, would each spread through their own column, and all 4 nibbles would change. You can check that with the experiment below.
def saes_with_extra_mix(plaintext, key):
# NOT real S-AES: round 2 also mixes columns, to see how far a change would spread
K0, K1, K2 = key_expansion(key)
state = add_round_key(to_state(plaintext), K0)
state = add_round_key(mix_columns(shift_rows(substitute(state))), K1)
state = add_round_key(mix_columns(shift_rows(substitute(state))), K2)
return state
counts = set()
for _ in range(500):
plaintext, key = random.randrange(65536), random.randrange(65536)
for bit in range(16):
counts.add(nibbles_different(saes_with_extra_mix(plaintext, key), saes_with_extra_mix(plaintext ^ (1 << bit), key)))
print('ciphertext nibbles that differ:', counts)ciphertext nibbles that differ: {4}
Real AES has a bigger state, so a change needs two full rounds to reach every byte. After that it uses many more rounds as a safety margin. The next page shows how.
From S-AES to AES¶
AES uses the same four steps on a bigger state.
| S-AES | AES-128 | |
|---|---|---|
| Block | 16 bits | 128 bits |
| State | 2×2 grid of nibbles | 4×4 grid of bytes |
| S-box | 16 entries | 256 entries |
| Shift rows | swap the bottom row | shift the rows by 0, 1, 2 and 3 places |
| Mix columns | 1’s and 4’s, on nibbles | 1’s, 2’s and 3’s, on bytes |
| Rounds | 2 | 10 |
| Last round | no mix columns | no mix columns |
If you can do S-AES, you understand AES.
Source: M. Musa, E. Schaefer and S. Wedig, “A Simplified AES Algorithm and Its Linear and Differential Cryptanalyses,” Cryptologia 27(2), 2003.