4

我正在尝试按照Bruce Schneider 1998 年的论文中所述逐步实施 Twofish 密码。尽管如此,我已经在关键扩展上失败了。

我尝试将论文的细节1对1复制到python中,结果如下:

#! /usr/bin/python3.2

def expandKey256 (key):
    m = [0] * (32)
    for i in range (32):
        m [i] = (key >> (i * 8) ) & 0xff
        #m [31 - i] = (key >> (i * 8) ) & 0xff
    print ('m = {}\n'.format ( [hex (b) for b in m] ) )

    M = [0] * 8
    for i in range (8):
        for j in range (4):
            M [i] += m [4 * i + j] * 2 ** (8 * j)
    print ('M = {}\n'.format ( [hex (b) for b in M] ) )

    Me = [M [0], M [2], M [4], M [6] ]
    Mo = [M [1], M [3], M [5], M [7] ]
    print ('Me = {}\n'.format ( [hex (b) for b in Me] ) )
    print ('Mo = {}\n'.format ( [hex (b) for b in Mo] ) )

    RS = [ [0x01, 0xA4, 0x55, 0x87, 0x5A, 0x58, 0xDB, 0x9E],
        [0xA4, 0x56, 0x82, 0xF3, 0x1E, 0xC6, 0x68, 0xE5],
        [0x02, 0xA1, 0xFC, 0xC1, 0x47, 0xAE, 0x3D, 0x19],
        [0xA4, 0x55, 0x87, 0x5A, 0x58, 0xDB, 0x9E, 0x03] ]

    s = [ [0] * 4] * 4
    S = [0] * 4
    for i in range (4):
        for j in range (4):
            for k in range (8):
                s [i] [j] += m [8 * i + k] * RS [j] [k]
                s [i] [j] &= 0xff
            S [i] += s [i] [j] * 2 ** (8 * j)
    for i in range (4):
        print ('S{} = {}'.format (i, hex (S [i] ) ) )

expandKey256 (0x0123456789ABCDEFFEDCBA987654321000112233445566778899AABBCCDDEEFF)

但是,我的输出与测试向量中指定的不同。我已经尝试以相反的方式读取字节(注释行),但无济于事。

这些是测试向量的结果:

B89FF6F2
B255BC4B
45661061
8E4447F7

这些是我的:

S0 = 0x612a646d
S1 = 0x527cc87a
S2 = 0x1482c008
S3 = 0xa4d128ce

谁能看到我的错误?

4

1 回答 1

6

至少这条线

s = [ [0] * 4] * 4

可能没有做你认为它正在做的事情。它没有做同样的事情

s = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

但是,我没有浏览所有代码。

编辑

显然,OP需要更多证据。这里来自 IDLE 的一些输出显示了差异

>>> s = [ [0] * 4] * 4
>>> s
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> s[0][0] += 1
>>> s
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
>>> s = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> s
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> s[0][0] += 1
>>> s
[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> 

该表达式s = [ [0] * 4] * 4创建一个包含另一个零列表的列表,然后再制作 3 个对该列表的引用的副本。它相当于v = [0]*4; s=[v,v,v,v]

于 2012-11-29T00:22:55.620 回答