尝试将代码从python2导入Python3时,会出现此问题
<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' object has no attribute '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'>
如果您不知道stringlike对象是Python 2字符串(字节)还是Python 3字符串(unicode)。你可以有一个通用的转换器
Python3外壳:
在Python2上,这两个表达式的计算结果都是
True
:type("hello") == bytes
和type("hello") == str
。和type(u"hello") == str
计算为False
,而type(u"hello") == unicode
为True
在Python 3上
type("hello") == bytes
是False
,而type("hello") == str
是True
。并且type("hello") == unicode
会引发NameError
异常,因为unicode
未在3上定义Python 2外壳:
多亏了@Todd,他解决了这个问题。
(pad * chr(pad))
是字节,而问题在于aesEncrypt(text, secKey)
。第一次用text
作为str
调用它两次,第二次用bytes
调用它解决方案是确保输入
text
是str
类型由于
AES.new
的第一个参数是bytes/bytearray/memoryview,并且我假设text
已经是bytes
类型,那么我们只需要将焊盘部分从unicode
转换为bytes
为了更加安全,您可以在与pad连接之前有条件地对
text
进行编码相关问题 更多 >
编程相关推荐