在Python 3.6 XOR中获得简单错误

时间:2017-03-26 04:24:41

标签: python python-3.x encryption xor

我正在使用Python 3.6,并尝试使用XOR加密文件。我有一点简单的代码:

from itertools import cycle


def xore(data, key):
    return ''.join(chr(a ^ ord(b)) for (a, b) in zip(data, cycle(key)))

with open('C:\\Users\\saeed\\Desktop\\k.png', 'rb') as encry, open('C:\\Users\\saeed\\Desktop\\k_enc.png', 'wb') as decry:
    decry.write(xore(encry.read(), 'anykey'))

我到了;

Traceback (most recent call last):
  File "C:/Users/saeed/IdeaProjects/xorencrypt/XORenc.py", line 8, in <module>
    decry.write(xore(encry.read(), 'anykey'))
TypeError: a bytes-like object is required, not 'str'

这是什么意思,我该如何解决这个问题?还有办法解密文件吗?感谢。

1 个答案:

答案 0 :(得分:1)

使xore返回一个字节,而不是str。

def xore(data, key):
    return bytes(a ^ ord(b) for a, b in zip(data, cycle(key)))

写入以二进制模式打开的文件对象。

BTW,通过传递字节文字b'anykey'而不是字符串文字,您不需要调用ord,因为迭代字节会产生int s:

def xore(data, key):
    return bytes(a ^ b for a, b in zip(data, cycle(key)))

with open('...', 'rb') as encry, open('...', 'wb') as decry:
    decry.write(xore(encry.read(), b'anykey'))
    #                              ^^^^^^^^^ bytes literal