# AES-128 encryption (one block), written without any library
# sbox is generated using inverse in GF(2^8) + affine transform

def xtime(a):
    a = a << 1
    if a & 0x100:
        a = a ^ 0x11b
    return a

def mul(a, b):
    r = 0
    while b:
        if b & 1:
            r ^= a
        a = xtime(a)
        b >>= 1
    return r

# make sbox
sbox = []
for i in range(256):
    inv = 0
    if i != 0:
        for j in range(1, 256):
            if mul(i, j) == 1:
                inv = j
    b = inv
    s = b
    for k in range(4):
        b = ((b << 1) | (b >> 7)) & 255
        s ^= b
    sbox.append(s ^ 0x63)

def expand_key(key):
    w = [list(key[i:i+4]) for i in range(0, 16, 4)]
    rcon = 1
    for i in range(4, 44):
        t = list(w[i-1])
        if i % 4 == 0:
            t = t[1:] + t[:1]
            t = [sbox[x] for x in t]
            t[0] ^= rcon
            rcon = xtime(rcon)
        w.append([w[i-4][j] ^ t[j] for j in range(4)])
    return w

def add_round_key(s, w, r):
    for c in range(4):
        for i in range(4):
            s[c*4+i] ^= w[r*4+c][i]

def sub_bytes(s):
    for i in range(16):
        s[i] = sbox[s[i]]

def shift_rows(s):
    t = s[:]
    for c in range(4):
        for r in range(4):
            s[c*4+r] = t[((c+r) % 4)*4+r]

def mix_columns(s):
    for c in range(4):
        a = s[c*4:c*4+4]
        s[c*4+0] = mul(a[0],2) ^ mul(a[1],3) ^ a[2] ^ a[3]
        s[c*4+1] = a[0] ^ mul(a[1],2) ^ mul(a[2],3) ^ a[3]
        s[c*4+2] = a[0] ^ a[1] ^ mul(a[2],2) ^ mul(a[3],3)
        s[c*4+3] = mul(a[0],3) ^ a[1] ^ a[2] ^ mul(a[3],2)

def encrypt(block, key):
    w = expand_key(key)
    s = list(block)
    add_round_key(s, w, 0)
    for r in range(1, 10):
        sub_bytes(s)
        shift_rows(s)
        mix_columns(s)
        add_round_key(s, w, r)
    sub_bytes(s)
    shift_rows(s)
    add_round_key(s, w, 10)
    return bytes(s)

key = bytes(range(16))                  # 00 01 02 ... 0f
plain = bytes.fromhex("00112233445566778899aabbccddeeff")

cipher = encrypt(plain, key)
print("plain  :", plain.hex())
print("key    :", key.hex())
print("cipher :", cipher.hex())
print("expected 69c4e0d86a7b0430d8cdb78070b4c55a")
