这是我的第一个Python脚本之一,我想知道它是否符合正确的约定。还有,有什么东西你会写不同的?我正在寻找一些好的评论,以便我可以开始改进我的Python代码从一开始。(我不应该在这里使用进口产品)
下面是我的简化DES实现:
__author__ = 'ßaron'
FIXED_IP = [2, 6, 3, 1, 4, 8, 5, 7]
FIXED_EP = [4, 1, 2, 3, 2, 3, 4, 1]
FIXED_IP_INVERSE = [4, 1, 3, 5, 7, 2, 8, 6]
FIXED_P10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
FIXED_P8 = [6, 3, 7, 4, 8, 5, 10, 9]
FIXED_P4 = [2, 4, 3, 1]
S0 = [[1, 0, 3, 2],
[3, 2, 1, 0],
[0, 2, 1, 3],
[3, 1, 3, 2]]
S1 = [[0, 1, 2, 3],
[2, 0, 1, 3],
[3, 0, 1, 0],
[2, 1, 0, 3]]
KEY = '0111111101'
def permutate(original, fixed_key):
new = ''
for i in fixed_key:
new += original[i - 1]
return new
def left_half(bits):
return bits[:len(bits)/2]
def right_half(bits):
return bits[len(bits)/2:]
def shift(bits):
rotated_left_half = left_half(bits)[1:] + left_half(bits)[0]
rotated_right_half = right_half(bits)[1:] + right_half(bits)[0]
return rotated_left_half + rotated_right_half
def key1():
return permutate(shift(permutate(KEY, FIXED_P10)), FIXED_P8)
def key2():
return permutate(shift(shift(shift(permutate(KEY, FIXED_P10)))), FIXED_P8)
def xor(bits, key):
new = ''
for bit, key_bit in zip(bits, key):
new += str(((int(bit) + int(key_bit)) % 2))
return new
def lookup_in_sbox(bits, sbox):
row = int(bits[0] + bits[3], 2)
col = int(bits[1] + bits[2], 2)
return '{0:02b}'.format(sbox[row][col])
def f_k(bits, key):
L = left_half(bits)
R = right_half(bits)
bits = permutate(R, FIXED_EP)
bits = xor(bits, key)
bits = lookup_in_sbox(left_half(bits), S0) + lookup_in_sbox(right_half(bits), S1)
bits = permutate(bits, FIXED_P4)
return xor(bits, L)
def encrypt(plain_text):
bits = permutate(plain_text, FIXED_IP)
temp = f_k(bits, key1())
bits = right_half(bits) + temp
bits = f_k(bits, key2())
print permutate(bits + temp, FIXED_IP_INVERSE)
def decrypt(cipher_text):
bits = permutate(cipher_text, FIXED_IP)
temp = f_k(bits, key2())
bits = right_half(bits) + temp
bits = f_k(bits, key1())
print permutate(bits + temp, FIXED_IP_INVERSE)
encrypt('11101010')
decrypt('10100010')发布于 2015-10-20 10:47:46
如果您使用的常量是集合,那么最好是让它们成为元组,而不是列表。尝试修改元组会导致错误,因为它们是不可变的,使用元组语法可以更清楚地看出这些常量是不变的。
FIXED_IP = (2, 6, 3, 1, 4, 8, 5, 7)
FIXED_EP = (4, 1, 2, 3, 2, 3, 4, 1)正如Caridorc所说,使用str.join更快(取决于您的版本)。它还允许您使permutate只需一行。
def permutate(original, fixed_key):
return ''.join(original[i - 1] for i in fixed_key)将bits和key中的所有值预转换为整数也会更快一些。您可以使用map向列表的每个成员应用一个函数,它比在列表中执行函数要快。您可以在创建zip对象时这样做。
def xor(bits, key):
new = ''
for bit, key_bit in zip(map(int, bits), map(int, key)):
new += str(((bit + key_bit) % 2))
return new当然,如果您想要的话,也可以将它做成一个str.join,尽管它很长:
def xor(bits, key):
return ''.join(str(((bit + key_bit) % 2)) for bit, key_bit in
zip(map(int, bits), map(int, key)))这里有很多函数,但没有很多文档。解释单独的函数会使您的代码更容易阅读。我怀疑您有一些不必要的重复函数,您可以传递一个参数,而不是定义一个全新的参数。但是很难知道什么时候我不完全理解你在这里的功能。
发布于 2015-10-19 20:33:22
总体上写得很好,但请记住,在循环中使用string += thing非常慢,为了提高效率,您应该使用join生成器表达式。
https://codereview.stackexchange.com/questions/108057
复制相似问题