我发现了一个简单的纯python河豚实现,可满足我对特定项目的需求。重构此块密码键控功能
这里只有其中的一部分困扰我:
def initialize(key):
"""
Use key to setup subkeys -- requires 521 encryptions
to set p and s boxes. key is a hex number corresponding
to a string of 32 up to 448 1s and 0s -- keylen says
how long
"""
# Note that parray and sboxes are globals that have been pre-initialized.
hexkey = hex(key)[2:]
if hexkey[-1]=='L':
hexkey = hexkey[:-1]
if len(hexkey)%2==1:
hexkey = '0'+hexkey
lenkey = len(hexkey)/8
if lenkey==0:
pos=0
# XOR key segments with P-boxes
for i in range(18):
if lenkey>0:
pos = (i%lenkey)*8 # offset into key gives subkey
subkey = eval('0x'+hexkey[pos:pos+8]+'L')
parray[i] ^= subkey # immediate XOR -- Python 2.0+ syntax
# encrypt 0-data, then keep re-encrypting and reassigning P-boxes
output = 0L
for i in range(0,17,2):
output = bfencrypt(output)
parray[i], parray[i+1] = output>>32, output & 0xFFFFFFFFL
# re-encrypt and reassign through all the S-boxes
for i in range(4):
for j in range(0,255,2):
output = bfencrypt(output)
sbox[i][j],sbox[i][j+1] = output>>32, output & 0xFFFFFFFFL
# print "Initialization complete"
subkey = eval('0x'+hexkey[pos:pos+8]+'L')
?请告诉我有更好的方法来做到这一点。
是不是有一种方法来重构这个在字符串中使用实际整数类型而不是十六进制值?
它对schneier的测试向量正确执行:http://www.schneier.com/code/vectors.txt。也就是说,我将重写它与schneier的c代码(这不是很复杂),而不是混淆了这个字符串片段的愚蠢。 – 2009-06-15 21:54:23