2016-11-18 98 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:] 

它清除了所有问题。