我試圖按照1998 paper of Bruce Schneider中所述的步驟執行Twofish密碼。不過,我已經在關鍵擴張方面失敗了。Twofish密鑰擴展
我試着用紙1對1的細節複製到蟒蛇,結果如下:
#! /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 (0xABCDEFFEDCBA00112233445566778899AABBCCDDEEFF)
然而,作爲test vectors指定我的輸出是不一樣的。我已經嘗試以相反的方式讀取字節(註釋行),但無濟於事。
這些測試向量的結果:
B89FF6F2
B255BC4B
45661061
8E4447F7
而這些都是我的
S0 = 0x612a646d
S1 = 0x527cc87a
S2 = 0x1482c008
S3 = 0xa4d128ce
任何人都可以看到我的錯誤?
目前存在針對Python的Twofish實現;當然你可以得到其中的一個,爲它和你的實現添加豐富的打印語句,並找出你出錯的地方? – kindall
python常用的做法是'expandKey256(key)'被寫入時沒有空格,'expandKey256(key)'http://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-和聲明 – monkut