【发布时间】:2020-02-24 02:50:44
【问题描述】:
尝试将代码从python2导入python 3,出现这个问题
<ipython-input-53-e9f33b00348a> in aesEncrypt(text, secKey)
43 def aesEncrypt(text, secKey):
44 pad = 16 - len(text) % 16
---> 45 text = text.encode("utf-8") + (pad * chr(pad)).encode("utf-8")
46 encryptor = AES.new(secKey, 2, '0102030405060708')
47 ciphertext = encryptor.encrypt(text)
AttributeError:'bytes' 对象没有属性 'encode'
如果我删除 .encode("utf-8") 错误是“无法将 str 连接到字节”。显然pad*chr(pad) 似乎是一个字节串。它不能使用encode()
<ipython-input-65-9e84e1f3dd26> in aesEncrypt(text, secKey)
43 def aesEncrypt(text, secKey):
44 pad = 16 - len(text) % 16
---> 45 text = text.encode("utf-8") + (pad * chr(pad))
46 encryptor = AES.new(secKey, 2, '0102030405060708')
47 ciphertext = encryptor.encrypt(text)
TypeError: can't concat str to bytes
然而,奇怪的是,如果我只是尝试这个部分。 encode() 工作正常。
text = { 'username': '', 'password': '', 'rememberLogin': 'true' }
text=json.dumps(text)
print(text)
pad = 16 - len(text) % 16
print(type(text))
text = text + pad * chr(pad)
print(type(pad * chr(pad)))
print(type(text))
text = text.encode("utf-8") + (pad * chr(pad)).encode("utf-8")
print(type(text))
{"username": "", "password": "", "rememberLogin": "true"}
<class 'str'>
<class 'str'>
<class 'str'>
<class 'bytes'>
【问题讨论】:
-
chr返回一个字符串,该字符串被相乘并编码为字节。这里的问题是text是字节。你怎么打电话给aesEncrypt?您需要提供minimal reproducible example。 -
Python2 字符串是隐式字节对象,而 Python3 字符串是 unicode。所以这是有道理的。这对我来说似乎是正确的方法 - 您添加 .encode('utf-8') 的方式。但这不会与 Python2 向后兼容——这就是问题所在吗? @RoyDai
-
也许一种控制编解码器的便携方式是导入
codec并使用它的encode()和decode()模块函数。 -
pad = 16 - len("dummy") % 16; (pad * chr(pad)).encode('utf-8') b'\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b'在 Python3 上运行良好.. 除非存在无法编码的填充字节。 -
@Todd 非常感谢您的回复。我试过 .encode('utf-8') 适用于隔离会话,但它不适用于第一种情况,我现在不知道为什么。
标签: python python-2to3