# AES S-Box Affine Mapping - how to do it?

For the byte substitution layer in AES how do we determine B(i)? I follow how to use the multiplicative inverse table and using that to get B(i), but how do I actually calculate the affine mapping? Is this normal matrix multiplication? • – Richie Frame Sep 21 '15 at 6:38

Yes it is a normal matrix multiplication but within Galois finite field. We have to use Galois defined operations of $+$ and $\cdot$. Example might clarify everything. Let's say we have the $b'$ vector, and it's value is $170 = 10101010b$ Just remember tat $b'_0$ is the least significant bit of that value.

$b_0 = (1 \wedge b'_0) \oplus (0 \wedge b'_1) \oplus (0 \wedge b'_2) \oplus (0 \wedge b'_3) \oplus (1 \wedge b'_4) \oplus (1 \wedge b'_5) \oplus (1 \wedge b'_6) \oplus (1 \wedge b'_7) \oplus (1) = (1 \wedge 0) \oplus (0 \wedge 1) \oplus (0 \wedge 0) \oplus (0 \wedge 1) \oplus (1 \wedge 0) \oplus (1 \wedge 1) \oplus (1 \wedge 0) \oplus (1 \wedge 1) \oplus (1) = 0 \oplus 0 \oplus 0 \oplus 0 \oplus 0 \oplus 1 \oplus 0 \oplus 1 \oplus (1) = 1 \oplus 1 \oplus (1) = 1$

$b_1 = (1 \wedge b'_0) \oplus (1 \wedge b'_1) \oplus (0 \wedge b'_2) \oplus (0 \wedge b'_3) \oplus (0 \wedge b'_4) \oplus (1 \wedge b'_5) \oplus (1 \wedge b'_6) \oplus (1 \wedge b'_7) \oplus (1) = (1 \wedge 0) \oplus (1 \wedge 1) \oplus (0 \wedge 0) \oplus (0 \wedge 1) \oplus (0 \wedge 0) \oplus (1 \wedge 1) \oplus (1 \wedge 0) \oplus (1 \wedge 1) \oplus (1) = 0 \oplus 1 \oplus 0 \oplus 0 \oplus 0 \oplus 1 \oplus 0 \oplus 1 \oplus (1) = 1 \oplus 1 \oplus 1 \oplus (1) = 0$

$\vdots$

Just remember that here also $b_0$ is the least significant bit of the result.

Here's a little python from my experimental implementation for You:

result = 0;

inverse = RijndaelHelper.Inverse(value)

for i in range(8):
row = (0xF1 << i | 0xF1 >> (8 - i))

t = row & inverse;

sum = 0;
for j in range(8):
sum ^= (t >> j) & 0x1;

result |= sum << i;

result ^= 0x63;
`

This is normal matrix multiplication, but when filling in b′ remember that b′0 is the least significant bit (this is the case for the answer too). The matrix multiplication and addition will result in numbers other than 0 and 1, but using the modular 2 it will reduce to 0 and 1 only.