. Advertisement .
..3..
. Advertisement .
..4..
Here is the program I run:
<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)
<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)
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'>
After I run, it returns an error:
AttributeError:'bytes' object has no attribute 'encode'
TypeError: can't concat str to bytes
Does anyone have any suggestions for the problem below: attributeerror: ‘bytes’ object has no attribute ‘encode’ in the python – How to correct it?
The cause: We can see that
(pad * chr(pad))
is bytes while issue inaesEncrypt(text, secKey).
It was called twice, the first time using text as thestr
parameter and the second time using the bytes parameter. This is the reason.Solution: To solve the error attributeerror: ‘bytes’ object has no attribute ‘encode’, the pad portion needs to be converted from
unicode
tobytes
.You might selectively encrypt
text
prior concatenating with pad to be additional safe.Thank you to @Todd for solving the problem.
(pad * chr(pad))
is bytes, whileaesEncrypt(text, secKey)
is the solution. It was called twice, once withtext
str
and againbytes
.You can solve this problem by ensuring that your input
text
type isstr
.