2016-11-18 44 views
1

我試圖讓使用XOR運算符一個密碼。現在,這是我有:XOR加密的蟒蛇 - 奇數長度字符串

from binascii import hexlify, unhexlify 
from itertools import cycle 

s = '636174' 
key = '13' 
def cipherkey(s, key): 
    bin_key = bin(int(key))[2:] 
    bin_s = bin(int(s, 16))[2:] 
    k = [] 
    if len(bin_key) < len(bin_s): 
     for i, j in zip(cycle(bin_key), bin_s): 
      k.append('{}'.format(i)) 
    else: 
     for i, j in zip(bin_key, cycle(bin_s)): 
      k.append('{}'.format(i)) 
    return int("".join(k),2) 

def xor_cipher(s,key): 
    n = cipherkey(s, key) 
    out = n^int(s,16) 
    return hex(out) 
print(unhexlify(xor_cipher(s, key))) 

我敢肯定,這是超級低效的代碼,但我想盡可能多的它保持越好。我已經開始對此有一段時間了,並且還沒有發現這個錯誤。在我如何重複zip(cycle(bin_key), bin_s)的過程中一定有一個錯誤。

+0

填寫'hex'的返回值,如[見] [這裏](http://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string) –

回答

1

嘗試更換的最後一行:此代碼

print(unhexlify(xor_cipher(s, key))) 

res=xor_cipher(s, key)[2:] # remove '0x' from the begining of the hex code 
if res.__len__()%2 ==1: # if res length is odd, 
    res="0{}".format(res) #  append '0' at the begining to make it even 
print unhexlify(res) 
+0

這確實產生了一個結果,儘管我不知道爲什麼。你能解釋你做了什麼嗎?我的代碼的其餘部分聽起來不錯? 另外,我忘了說,這是蟒蛇3 – Astrum

+0

我已經添加到代碼中的一些註釋。 –

+0

它的工作原理大多正確,雖然似乎有一些小問題。當使用正確的解密密鑰時,它產生「b」\ x03ooking MC就像一磅燻肉「」,而不是「b'cooking MC的......」。任何想法爲什麼? – Astrum

2

我有,因爲我實現了密碼incvorecctly問題。做到這一點的方式只是:

def xor_cipher(s, hexkey): 
    key = '' 
    for i,j in zip(s, cycle(hexkey)): 
     key += j 
    return hex(int(s,16)^int(key,16))[2:] 

它清除了所有問題。