Xor加密/解密Python 2.7.5

2024-07-05 10:15:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道有一个内置的xor操作符可以在Python中导入。我正在尝试执行xor加密/解密。到目前为止,我已经:

def xor_attmpt():
    message = raw_input("Enter message to be ciphered: ")
    cipher = []
    for i in message:
        cipher.append(bin(ord(i))[2::])#add the conversion of the letters/characters
#in your message from ascii to binary withoout the 0b in the front to your ciphered message list
    cipher = "".join(cipher) 
    privvyKey = raw_input("Enter the private key: ")
    keydecrypt = []
    for j in privvyKey:
        keydecrypt.append(bin(ord(j))[2::]) #same
    keydecrypt = "".join(keydecrypt )#same

    print "key is '{0}'" .format(keydecrypt) #substitute values in string
    print "encrypted text is '{0}'" .format(cipher)
    from operator import xor
    for letter in message:
        print xor(bool(cipher), bool(keydecrypt))

这个:

^{pr2}$

是我的python开始出错的地方。在

The ouput looks like this
    Enter message to be ciphered: hello
Enter the private key: \@154>
key is '10111001000000110001110101110100111110'
encrypted text is '11010001100101110110011011001101111'
False
False
False
False
False

我要搞砸的是试图比较这两个二进制(密钥和加密的)并给出true(1)或false(0)。然后,xor应该给我一个通过比较二者得到的1和0二进制列表。有什么意见吗?在


Tags: thetokeyinfalsemessageforraw
2条回答

bool()构造函数将任何值转换为True或{}。因为在每种情况下,bool(cipher)和{}都传递给它一个非空字符串,True和{}是False。在

忘记转换为0和1的字符串,您实际需要做的只是异或调用ord()得到的字符代码,然后转换回带有chr()的字符。另外,您不需要导入函数,Python有一个功能完善的异或运算符^。在

这样的事情应该有用:

import itertools
print(''.join(chr(ord(k)^ord(c)) for c,k in zip(cipher,itertools.cycle(keydecrypt))))

你犯了一些错误:

  1. cipherkeydecrypt不是二进制的,它们是包含0和1个字符的字符串。在
  2. 不需要导入xor函数,您已经有了xor运算符^
  3. 如果string=='',在python中将字符串转换为boolean将得到False,而在其他情况下则为True,这不是您想要的。在
  4. 我不明白最后一个for应该做什么。在

下面是一个关于如何改进代码的示例:

import itertools
import binascii

encrypted = ''
for m, k in itertools.izip(message, itertools.cycle(key)):
    encrypted += chr(ord(m) ^ ord(k))

print binascii.hexlify(encrypted)

如果key小于message,也可以这样做。在

相关问题 更多 >