I am trying to implement the MixColumns algorithm for AES in python, but I am having some trouble. Here is my code:
def multiply(b,a):
if b == 1:
return a
if b == 2:
return ((a<<1)&0xff)^0x1b
if b == 3:
return (((a<<1)&0xff)^0x1b)^a
s_mat1 = [np.copy(s) for s in s_mat]
for i in range(len(s_mat)):
for j in range(len(s_mat[i])):
s_mat[i][j] = multiply(mx_col[i][0],s_mat1[0][j])^multiply(mx_col[i][1],s_mat1[1][j])^multiply(mx_col[i][2],s_mat1[2][j])^multiply(mx_col[i][3],s_mat1[3][j])
here s_mat
is the state matrix and mx_col
is the mixcolumn matrix. I tried this code for this example:
However my code is giving different answer from the given. here is the answer given by my code:
[['ba', '84', 'e8', '1b'], ['6e', 'a4', '8d', '5b'], ['f4', '96', '6', '7d'], ['61', '29', 'e', '46']]
The first row is coming correct. But why are the other rows coming wrong? what mistake am I doing?
For
there is a case distinction which has not been considered in the code: The XOR
with 0x1b
is only performed for a > 127
, here. This changes the cases b == 2
and b == 3
:
def multiply(b,a):
if b == 1:
return a
tmp = (a<<1) & 0xff
if b == 2:
return tmp if a < 128 else tmp^0x1b
if b == 3:
return tmp^a if a < 128 else (tmp^0x1b)^a
With this change the expected result is obtained.