Skip to main content
 首页 » 编程设计

python之在 Python 3.6 XOR 中获取简单错误

2025年02月15日6lhb25

我正在使用 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' 

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

请您参考如下方法:

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

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

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


顺便说一句,通过传递字节文字 b'anykey' 而不是字符串文字,您不需要调用 ord,因为迭代字节会产生 ints:

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