2017-02-27 21 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