2017-02-27 18 views
-1

我想拿一个文本文件,并做一些XOR的密文。当我运行这个脚本时,我得到了将密文1与其他密文异或的错误。有人可以帮我吗?密文XOR错误

Traceback (most recent call last): 
    File "./letters.py", line 45, in <module> 
    print xorTwoLists(c[0],c[x], lenTarget) 
    File "./letters.py", line 22, in xorTwoLists 
    xorValue = int(l1[x],16)^int(l2[x],16) 
IndexError: list index out of range 

这里是我的代码:

#!/usr/bin/python 

def splitIntoHexBytes (s) : 
    l = [] 
    for x in range(0, len(s)/2) : 
     y = x*2 
     hexStr = '0x'+ s[y:(y+2)] 
     l.append(hexStr) 
    return l 


def makeLen4string(s) : 
    if len(s) < 4 : 
     return s[0:2] + '0' + s[2] 
    else : 
     return s 


def xorTwoLists(l1, l2, length) : 
    resultList = [] 
    for x in range(length) : 
     xorValue = int(l1[x],16)^int(l2[x],16) 
     hexXorValue = hex(xorValue) 
     hexString = makeLen4string(hexXorValue) 
     resultList.append(hexString) 
    return resultList 



infile = open('ctexts.txt', 'r') 
ciphertexts = infile.readlines() 
infile.close() 
target = splitIntoHexBytes(ciphertexts[0]) 

c=[] 
for x in range(len(ciphertexts)-1) : 
    c.append(splitIntoHexBytes(ciphertexts[x+1])) 


lenTarget = len(target) 

# Check the first ciphertext for blanks 
print "the folllowing is the output of XORing ciphertext 1 with the others ciphertexts :" 
for x in range(1, len(c)): 
    print xorTwoLists(c[0],c[x], lenTarget) 
print 
print "the folllowing is the output of XORing ciphertext 1 with the target :" 
print xorTwoLists(c[0],target, lenTarget) 
+0

这与XORing无关。确保你传递的列表长度相同,长度本身计算正确。 – ForceBru

+1

您的错误是“IndexError:列表索引超出范围”。在'xorTwoLists'中,你传递了两个列表'l1'和'l2'。您需要确保“长度”不超过两者的最小长度。你可以在函数的第一行加上'length = min(len(l1)-1,len(l2)-1,length)'来提供一些验证。 – thodic

+0

最后一件事。我的输出列表非常大。我有大约15个列表,每个列表大约有25个条目。有没有一种方法可以格式化输出,使每个条目出现在其他列表中相应的条目下?目前,他们都在这个地方 – johndoe12345

回答

0

如果你想XOR整数的两个列表,然后尝试以下方法:

def xorTwoLists(l1, l2): 
    xorBytes = lambda (x, y): x^y # lambda function to XOR individual bytes 
    return map(xorBytes, zip(l1, l2)) # zip the two lists then apply xorBytes to the byte tuples 

而对于输入:

c1 = [224, 22, 149, 10, 65, 125, 77, 58] 
c2 = [11, 162, 186, 182, 69, 175, 52, 75, 13, 119, 8, 176, 0, 39, 205, 74] 

您将得到两个列表的XOR较小列表的长度。 在这种情况下:

>>> xorTwoLists(c1, c2) 
[235, 180, 47, 188, 4, 210, 121, 113] 

希望它有帮助。

+0

得到意想不到的令牌附近的语法错误c1 – johndoe12345

+0

我复制并粘贴它,似乎对我来说没问题。你能更精确地说明错误吗? – Szabolcs