【发布时间】:2021-09-25 06:18:26
【问题描述】:
早安各位! 我一直在尝试将用 Python 2 编写的 this code 转换为 Python 3。这是一个使用 XOR 加密字符串的简单函数。到目前为止我所拥有的:
import binascii
def encrypt(content: str, key: str) -> str:
key_id = 0
xored = ""
for c in content:
xored += chr(ord(key[key_id % len(key)]) ^ ord(c))
key_id += 1
return binascii.hexlify(xored.encode())
def decrypt(content: str, key: str) -> str:
key_id = 0
xored = ""
for c in binascii.unhexlify(content):
xored += chr(ord(key[key_id % len(key)]) ^ ord(c))
key_id += 1
return binascii.hexlify(xored.encode())
Python 2 中的代码完美运行,但是在测试上面的代码时(在 Python 3 中),我在解码消息时遇到了问题。 (encrypt() 函数似乎运行良好。) 发生以下错误:
>>> encrypt("foo", "123")
b'575d5c'
>>> decrypt(b"575d5c", "123")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
decrypt(b"575d5c", "123")
File "/home/user/Code/Python/xorcrypt.py", line 15, in decrypt
xored += chr(ord(key[key_id % len(key)]) ^ ord(c))
TypeError: ord() expected string of length 1, but int found
我检查了两个文档,但无法确定版本之间的任何差异:ord() in Python 2 和 ord() in Python 3。此外,我搜索了其他来源,但没有发现任何提及该问题的内容:
Porting Python 2 Code to Python 3
我在看正确的位置吗?或者在这种情况下 ord() 函数不是问题吗?非常感谢您!
【问题讨论】:
-
加密没有按照规范工作。它应该返回一个字符串,但返回一个字节对象。这些在 py 2 中相同,但在 py 3 中不同
-
另外,
for key_id, c in enumerate(content):是即使在 py2 中也要走的路 -
感谢您的回答!我将 encrypt() 的返回值和第一个参数 decrypt() 更改为字节。我还在字符串中包含 enumerate() 函数。感谢您指出这一点。