Skip to content

Instantly share code, notes, and snippets.

@GordonOus
Created September 25, 2021 18:13
Show Gist options
  • Save GordonOus/a7e92d581eccb34d5bdf5d9c52d957d8 to your computer and use it in GitHub Desktop.
Save GordonOus/a7e92d581eccb34d5bdf5d9c52d957d8 to your computer and use it in GitHub Desktop.
cryptohack symmetric crypto series
def shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def inv_shift_rows(s):
tmp = s[13]
s[13] = s[9]
s[9] = s[5]
s[5] = s[1]
s[1] = tmp
tmp = s[10]
tmp2 = s[14]
s[10] = s[2]
s[14] = s[6]
s[2] = tmp
s[6] = tmp2
tmp = s[11]
s[11] = s[15]
s[15] = s[3]
s[3] = s[7]
s[7] = tmp
return s
# learned from http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mix_single_column(a):
# see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
u = a[0]
a[0] ^= t ^ xtime(a[0] ^ a[1])
a[1] ^= t ^ xtime(a[1] ^ a[2])
a[2] ^= t ^ xtime(a[2] ^ a[3])
a[3] ^= t ^ xtime(a[3] ^ u)
def mix_columns(s):
for i in range(4):
mix_single_column(s[i])
def inv_mix_columns(s):
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
u = xtime(xtime(s[i][0] ^ s[i][2]))
v = xtime(xtime(s[i][1] ^ s[i][3]))
s[i][0] ^= u
s[i][1] ^= v
s[i][2] ^= u
s[i][3] ^= v
mix_columns(s)
return s
state = [
[108, 106, 71, 86],
[96, 62, 38, 72],
[42, 184, 92, 209],
[94, 79, 8, 54],
]
fl = inv_shift_rows(sum(inv_mix_columns(state),[]))
print(''.join(chr(c) for c in fl))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment