现代密码学-AES算法Python实现(没有使用库)

本次AES算法实现,我将AES算法拆成5个组成部分:轮密钥加、字节替换、行位移、列混淆、密钥扩展5个部分,本次使用的示例以书应用密码学(第四版)第128面的例子进行试验。

1.轮密钥加

def ADDROUNDKEY(p,k):#输入数组
    ARK = []  # 轮密钥加
    for i in range(4):
        x = p[i]
        y = k[i]
        z = eval("0b"+x) ^ eval("0b"+y)
        xor = format(z,'b').zfill(32)
        ARK.append(xor)
    return ARK#返回轮密钥加数组
############################################################
plaintext = "32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34".replace(" ","")
key = "2b 7e 15 16 28 ae d2 a6 ab f7 15 88 09 cf 4f 3c".replace(" ","")
p = []#存储明文二进制
k = []#存储密钥二进制
for i in range(0,len(plaintext),8):#将每4个字节存储为1列
    p.append(bin(int("0x" + plaintext[i:i+8],16))[2:].zfill(32))#获得明文二进制
for i in range(0,len(key),8):#将每4个字节存储为1列
    k.append(bin(int("0x" + key[i:i+8],16))[2:].zfill(32))#获得密钥二进制
print(p)
print(k)
#print(f'轮密钥加结果:{ADDROUNDKEY(p,k)}')
print(ADDROUNDKEY(p,k))
temp = hex(int("0b"+"".join(ADDROUNDKEY(p,k)),2))[2:]
ark = []#存储初始轮密钥加结果
for i in range(0,len(temp),2):
    ark.append(temp[i:i+2])
print(f"初始轮密钥加结果为:{' '.join(ark).upper()}")


'''
初始轮密钥加结果为:19 3D E3 BE A0 F4 E2 2B 9A C6 8D 2A E9 F8 48 08
'''

2.字节替换

        字节替换需要自己建立一个替换表格,如下面Subchart

def SubBytes(plaintext):#字节替换,输入数组
    Subchart = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
		        0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
		        0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
		        0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
		        0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
		        0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
		        0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
		        0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
		        0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
		        0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
		        0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
		        0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
		        0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
		        0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
		        0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
		        0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16]
    temp = []
    for i in plaintext:#输入十六进制,将列表的16个十六进制数分别转化二进制数
        temp.append(bin(int("0x" + i,16))[2:].zfill(8))
    table = []#存储字节替换的二进制
    for i in temp:
        x = int(eval("0b" + i[:4]))#行值,前四位作为行数
        y = int(eval("0b" + i[4:]))#列值,后四位作为列数
        #table.append(hex(int("0b"+bin(Subchart[x*16+y])[2:].zfill(8),2))[2:].zfill(2).upper())
        table.append(format(int(Subchart[x*16+y]),'x').upper())
    return table
plaintext = "19 3D E3 BE A0 F4 E2 2B 9A C6 8D 2A E9 F8 48 08".split(" ")
print(f'字节替换的结果为:{" ".join(SubBytes(plaintext))}')

'''
字节替换的结果为:D4 27 11 AE E0 BF 98 F1 B8 B4 5D E5 1E 41 52 30
'''

3.行位移

        行位移在AES算法里应该是最简单的一个步骤啦,如下面shiftrow1函数,输入一个列表,直接通过索引来自行变化每个元素的位置,或者按照下方的函数,通过列表ShiftROW_chart的每个数字再减去1作为新位置的索引。

def shiftrow1(s):
    return [s[0],s[5],s[10],s[15],
            s[4],s[9],s[14],s[3],
            s[8],s[13],s[2],s[7],
            s[12],s[1],s[6],s[11]]
plaintext = "D4 27 11 AE E0 BF 98 F1 B8 B4 5D E5 1E 41 52 30".split(" ")
print(" ".join(shiftrow1(plaintext)))

def ShiftRows(plaintext):#行位移,输入数组
    ShiftROW_chart = [1, 6, 11, 16,
                      5, 10, 15, 4,
                      9, 14, 3, 8,
                      13, 2, 7, 12]#构建位移表
    temp = [i for i in range(16)]#用于存储换位的表
    for i in range(len(ShiftROW_chart)):
        temp[i] = plaintext[ShiftROW_chart[i] - 1]
    return temp
plaintext = "D4 27 11 AE E0 BF 98 F1 B8 B4 5D E5 1E 41 52 30".split(" ")
print(" ".join(ShiftRows(plaintext)))

'''
结果都是一样:D4 BF 5D 30 E0 B4 52 AE B8 41 11 F1 1E 27 98 E5
'''

4.列混淆

def MixColumns(sfr):
    def GF256(x, y):  # GF(256)算法
        def leftround(x):
            return x[1:8] + "0"
        x = x.replace(" ", "")
        y = y.replace(" ", "")
        x = bin(int("0x" + x, 16))[2:].zfill(8)
        y = bin(int("0x" + y, 16))[2:].zfill(8)
        if x.count("1") >= y.count("1"):  # 选择1最少的二进制
            num = y
            text = x
            temp = x
        else:
            num = x
            text = y
            temp = y
        px = 0b00011011  # 0x1B
        num = list(num)
        num.reverse()  # 将列表倒转,反向输出
        num = "".join(num)
        word = []
        for i in range(len(text)):
            if text[0] == "0":
                text = leftround(text)
                word.append(text)
            elif text[0] == "1":
                text = leftround(text)  # 将8位二进制左移一位,末尾填0
                xor = px ^ eval("0b" + text)
                text = format(xor, 'b').zfill(8)
                word.append(text)
        n = 0b00000000
        for index, value in enumerate(list(num)):
            if value == "1" and index == 0:  # 第一位为1时,将原二进制直接保留
                n ^= eval("0b" + temp)
            elif value == "1" and index > 0:
                n ^= eval("0b" + word[index - 1])
        n = format(n, 'b').zfill(8)
        return hex(int("0b" + n, 2))[2:].upper().zfill(2)

    def xor(word):
        key = []
        for i in word:
            key.append(bin(int("0x" + i, 16))[2:].zfill(8))
        n = 0b00000000
        for i in range(len(key)):
            n ^= eval("0b" + key[i])
        n = format(n, 'b').zfill(8)
        return hex(int("0b" + n, 2))[2:].upper().zfill(2)

    def exchange(s):  # 结果是按照行来输出,更改为按列输出
        return [s[0], s[4], s[8], s[12],
                s[1], s[5], s[9], s[13],
                s[2], s[6], s[10], s[14],
                s[3], s[7], s[11], s[15]]

    Mc_chart = [["02", "03", "01", "01"],
                ["01", "02", "03", "01"],
                ["01", "01", "02", "03"],
                ["03", "01", "01", "02"]]
    gf256 = []
    for round in range(4):
        for row in range(4):
            for col in range(4):
                temp = GF256(Mc_chart[round][col], sfr[col + row * 4])
                gf256.append(temp)
    temp = []
    for i in range(0, len(gf256), 4):
        temp.append(gf256[i:i + 4])
    result = []
    for i in temp:
        a = xor(i)
        result.append(a)
    b = exchange(result)
    print(f"列混淆结果为:{' '.join(b).upper()}")
    new_chart = []
    for v in range(0, len("".join(b)), 8):  # 将每4个字节存储为1列
        new_chart.append(bin(int("0x" + "".join(b)[v:v + 8], 16))[2:].zfill(32))
    return new_chart
print(MixColumns("D4 BF 5D 30 E0 B4 52 AE B8 41 11 F1 1E 27 98 E5".split(" ")))

'''
列混淆结果为:04 66 81 E5 E0 CB 19 9A 48 F8 D3 7A 28 06 26 4C
['00000100011001101000000111100101', '11100000110010110001100110011010', '01001000111110001101001101111010', '00101000000001100010011001001100']
'''

        在列混淆里,最难实现的也就是在GF的2的8次方域上的乘法,以下是相应代码:

再输入的两个变量里,先找出8个比特位里,1最少的二进制数来作为判断来减少计算的步骤,因为是从右向左来进行判断,所以将判断的列表用.reverse翻转,不然如果使用-1来作为索引会很麻烦

def GF256(x, y):  # GF(256)算法
    def leftround(x):
        return x[1:8] + "0"
    x = x.replace(" ", "")
    y = y.replace(" ", "")
    x = bin(int("0x" + x, 16))[2:].zfill(8)
    y = bin(int("0x" + y, 16))[2:].zfill(8)
    if x.count("1") >= y.count("1"):  # 选择1最少的二进制
        num = y
        text = x
        temp = x
    else:
        num = x
        text = y
        temp = y
    px = 0b00011011  # 0x1B
    num = list(num)
    print(num)
    num.reverse()#将列表倒转,反向输出
    num = "".join(num)
    print(num)
    word = []
    for i in range(len(text)):
        if text[0] == "0":
            text = leftround(text)
            print(text)
            word.append(text)
        elif text[0] == "1":
            text = leftround(text)  # 将8位二进制左移一位,末尾填0
            xor = px ^ eval("0b" + text)
            text = format(xor,'b').zfill(8)
            print(text)
            word.append(text)
            print(word)
    n = 0b00000000
    for index, value in enumerate(list(num)):
        if value == "1" and index == 0:  # 第一位为1时,将原二进制直接保留
            n ^= eval("0b"+temp)
        elif value == "1" and index > 0:
            n ^= eval("0b"+word[index - 1])
    n = format(n,'b').zfill(8)
    return hex(int("0b" + n, 2))[2:].upper().zfill(2)
print(GF256("0E","AC"))

5.密钥扩展

def SubBytes(plaintext):#字节替换,输入数组
    Subchart = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
		        0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
		        0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
		        0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
		        0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
		        0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
		        0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
		        0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
		        0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
		        0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
		        0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
		        0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
		        0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
		        0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
		        0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
		        0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16]
    temp = []
    for i in plaintext:#输入十六进制,将列表的16个十六进制数分别转化二进制数
        temp.append(bin(int("0x" + i,16))[2:].zfill(8))
    table = []#存储字节替换的二进制
    for i in temp:
        x = int(eval("0b" + i[:4]))#行值,前四位作为行数
        y = int(eval("0b" + i[4:]))#列值,后四位作为列数
        #table.append(hex(int("0b"+bin(Subchart[x*16+y])[2:].zfill(8),2))[2:].zfill(2).upper())
        table.append(format(int(Subchart[x*16+y]),'x').upper())
    return table
def rotwords(s):
    return s[2:4] + s[4:6] + s[6:8] + s[0:2]
chart = ["01000000","02000000","04000000","08000000","10000000",
         "20000000","40000000","80000000","1b000000","36000000"]
key = "2b 7e 15 16 28 ae d2 a6 ab f7 15 88 09 cf 4f 3c".replace(" ", "")
word = [[],[],[],[]]
n = 0
for i in range(0,len(key),8):
    word[n].append(key[i:i+8])
    n+=1#将16字节拆分为4个4字节,w[0]、w[1]、w[2]、w[3]
for i in range(4,44):
    word.append([])#每一轮开始,先添加一个空列表
    if i%4==0:
        subword = []
        a=rotwords(word[i-1][0])#存储向左移位的十六进制
        a=list(a)#先拆分为一个含有9个元素的列表
        for n in range(0,len(a),2):
            subword.append(a[n]+a[n+1])#每隔2个元素存储
        b="".join(SubBytes(subword))
        c=eval("0x"+b)^eval("0x"+chart[int(i/4-1)])^eval("0x"+word[i-4][0])
        word[i].append(format(c,'x').zfill(8))
    else:
        d=eval("0x"+word[i-1][0]) ^ eval("0x"+word[i-4][0])
        word[i].append(format(d,'x').zfill(8))#存储4字节十六进制
newkey=[]
w=0
for num in range(4,44,4):
    newkey.append([])
    newkey[w].append(format(eval("0x"+word[num][0]),'b').zfill(32))
    newkey[w].append(format(eval("0x"+word[num+1][0]),'b').zfill(32))
    newkey[w].append(format(eval("0x"+word[num+2][0]),'b').zfill(32))
    newkey[w].append(format(eval("0x"+word[num+3][0]),'b').zfill(32))
    w+=1
print(newkey)

在密钥扩展中还需要使用字节替换的一部分,在扩展中,每次循环都会先添加一个空列表,然后在里面存储4个二进制元素,来做最后一步轮密钥加

6.完整代码实现

def ADDROUNDKEY(p,k):#输入2个数组
    ARK = []  # 轮密钥加
    for i in range(4):#四次循环
        x = p[i]
        y = k[i]
        z = eval("0b"+x) ^ eval("0b"+y)
        xor = format(z,'b').zfill(32)#补足32位比特
        ARK.append(xor)
    return ARK#返回轮密钥加数组,含有4个元素
############################################################
def ShiftRows(plaintext):#行位移,输入数组
    ShiftROW_chart = [1, 6, 11, 16,
                      5, 10, 15, 4,
                      9, 14, 3, 8,
                      13, 2, 7, 12]#构建位移表
    temp = [i for i in range(16)]#用于存储换位的表
    for i in range(len(ShiftROW_chart)):
        temp[i] = plaintext[ShiftROW_chart[i] - 1]
    return temp
############################################################
def SubBytes(plaintext):#字节替换,输入数组
    Subchart = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
		        0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
		        0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
		        0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
		        0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
		        0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
		        0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
		        0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
		        0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
		        0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
		        0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
		        0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
		        0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
		        0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
		        0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
		        0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16]
    temp = []
    for i in plaintext:#输入十六进制
        temp.append(bin(int("0x" + i,16))[2:].zfill(8))
    table = []#存储字节替换的二进制
    for i in temp:
        x = int(eval("0b" + i[:4]))#行值
        y = int(eval("0b" + i[4:]))#列值
        table.append(format(int(Subchart[x*16+y]),'x').zfill(2).upper())
    return table
############################################################
def MixColumns(sfr):#传入列表
    def GF256(x, y):  # GF(256)算法
        def leftround(x):
            return x[1:8] + "0"
        x = x.replace(" ", "")
        y = y.replace(" ", "")
        x = bin(int("0x" + x, 16))[2:].zfill(8)
        y = bin(int("0x" + y, 16))[2:].zfill(8)
        if x.count("1") >= y.count("1"):  # 选择1最少的二进制
            num = y
            text = x
            temp = x
        else:
            num = x
            text = y
            temp = y
        px = 0b00011011  # 0x1B
        num = list(num)
        num.reverse()  # 将列表倒转,反向输出
        num = "".join(num)
        word = []
        for i in range(len(text)):
            if text[0] == "0":
                text = leftround(text)
                word.append(text)
            elif text[0] == "1":
                text = leftround(text)  # 将8位二进制左移一位,末尾填0
                xor = px ^ eval("0b" + text)
                text = format(xor, 'b').zfill(8)
                word.append(text)
        n = 0b00000000
        for index, value in enumerate(list(num)):
            if value == "1" and index == 0:  # 第一位为1时,将原二进制直接保留
                n ^= eval("0b" + temp)
            elif value == "1" and index > 0:
                n ^= eval("0b" + word[index - 1])
        n = format(n, 'b').zfill(8)
        return hex(int("0b" + n, 2))[2:].upper().zfill(2)
    def xor(word):
        key = []
        for i in word:
            key.append(bin(int("0x" + i, 16))[2:].zfill(8))
        n = 0
        for i in range(len(key)):
            n += int(key[i])
        n = str(n).zfill(8)
        xor = []
        for i in range(len(n)):
            z = int(n[i]) % 2
            xor.append(str(z))
        return hex(int("0b" + "".join(xor), 2))[2:].upper().zfill(2)
    def exchange(s):
        return [s[0],s[4],s[8],s[12],
                s[1],s[5],s[9],s[13],
                s[2],s[6],s[10],s[14],
                s[3],s[7],s[11],s[15]]
    Mc_chart = [["02","03","01","01"],
                ["01","02","03","01"],
                ["01","01","02","03"],
                ["03","01","01","02"]]
    gf256 = []
    for round in range(4):
        for row in range(4):
            for col in range(4):
                temp = GF256(Mc_chart[round][col],sfr[col+row*4])
                gf256.append(temp)
    temp = []
    for i in range(0,len(gf256),4):
        temp.append(gf256[i:i+4])
    result = []
    for i in temp:
        a = xor(i)
        result.append(a)
    b = exchange(result)
    print(f"列混淆结果为:{' '.join(b).upper()}")
    new_chart=[]
    for v in range(0, len("".join(b)), 8):  # 将每4个字节存储为1列
        new_chart.append(bin(int("0x" + "".join(b)[v:v + 8], 16))[2:].zfill(32))
    return new_chart

############################################################
plaintext = "32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34".replace(" ","")
key = "2b 7e 15 16 28 ae d2 a6 ab f7 15 88 09 cf 4f 3c".replace(" ","")
p = []#存储明文二进制
k = []#存储密钥二进制
for i in range(0,len(plaintext),8):#将每4个字节存储为1列
    p.append(bin(int("0x" + plaintext[i:i+8],16))[2:].zfill(32))#获得明文二进制
for i in range(0,len(key),8):#将每4个字节存储为1列
    k.append(bin(int("0x" + key[i:i+8],16))[2:].zfill(32))#获得密钥二进制
############################################################
def rotwords(s):
    return s[2:4] + s[4:6] + s[6:8] + s[0:2]
chart = ["01000000","02000000","04000000","08000000","10000000",
         "20000000","40000000","80000000","1b000000","36000000"]
word = [[],[],[],[]]
n = 0
for i in range(0,len(key),8):
    word[n].append(key[i:i+8])
    n+=1
for i in range(4,44):
    word.append([])
    if i%4==0:
        subword = []
        a=rotwords(word[i-1][0])
        a=list(a)
        for n in range(0,len(a),2):
            subword.append(a[n]+a[n+1])
        b="".join(SubBytes(subword))
        c=eval("0x"+b)^eval("0x"+chart[int(i/4-1)])^eval("0x"+word[i-4][0])
        word[i].append(format(c,'x').zfill(8))
    else:
        d=eval("0x"+word[i-1][0]) ^ eval("0x"+word[i-4][0])
        word[i].append(format(d,'x').zfill(8))
newkey=[]
w=0
for num in range(4,44,4):
    newkey.append([])
    newkey[w].append(format(eval("0x"+word[num][0]),'b').zfill(32))
    newkey[w].append(format(eval("0x"+word[num+1][0]),'b').zfill(32))
    newkey[w].append(format(eval("0x"+word[num+2][0]),'b').zfill(32))
    newkey[w].append(format(eval("0x"+word[num+3][0]),'b').zfill(32))
    w+=1
############################################################
############################################################
temp = hex(int("0b"+"".join(ADDROUNDKEY(p,k)),2))[2:]
ark = []#存储初始轮密钥加结果
for i in range(0,len(temp),2):
    ark.append(temp[i:i+2])
print(f"初始轮密钥加结果为:{' '.join(ark).upper()}")
############################################################
import time
for i in range(10):
    if i <=8:
        time.sleep(1)
        print(f"第{i+1}轮:")
        sub = SubBytes(ark)
        print(f"字节替换结果为:{' '.join(sub).upper()}")
        sfr = ShiftRows(sub)
        print(f"行位移结果为:{' '.join(sfr).upper()}")
        mixcol = MixColumns(sfr)
        temp = hex(int("0b" + "".join(ADDROUNDKEY(mixcol,newkey[i])), 2))[2:]
        ark = []  # 存储轮密钥加结果
        for i in range(0, len(temp), 2):
            ark.append(temp[i:i + 2])
    else:
        time.sleep(1)
        print(f"第{i + 1}轮:")
        sub = SubBytes(ark)
        print(f"字节替换结果为:{' '.join(sub).upper()}")
        sfr = ShiftRows(sub)
        print(f"行位移结果为:{' '.join(sfr).upper()}")

sfr=''.join(sfr)
last = []
for i in range(0,len(sfr),8):
    last.append(bin(int("0x"+sfr[i:i+8],16))[2:].zfill(32))
result = ADDROUNDKEY(last,newkey[9])
result = format(eval('0b'+''.join(result)),'x').upper()
outcome = []
for i in range(0,len(result),2):
    outcome.append(result[i:i+2])
print(f"最后结果为:{' '.join(outcome)}")




最后在输出结果的时候使用了time模块来是结果输出更加清晰。

以上为AES算法Python实现的所有内容,如有更好更加简洁的代码希望可以一起交流共同进步。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值