问题描述
大家早上好! 我一直在尝试将用 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() 函数不是问题吗?预先非常感谢您!
解决方法
区别不在于ord()
,而在于binascii.unhexlify()
。在 Python 2 中,它返回一个字符串,如果您对该字符串进行索引,您将得到一个长度为 1 的字符串,您可以对其调用 ord()
。但在 Python 3 中,它返回一个 bytes
,如果你索引它,你会得到一个小整数,你不能在上面调用 ord()
,也不需要。