Python pycrypto module: why simplejson can't dumps encrypted string?

二次信任 提交于 2019-12-05 02:51:21

问题


It shows UnicodeError: 'utf8' codec can't decode byte 0x82 in position 0: unexpected code byte

Here is code:

from Crypto.Cipher import AES
import simplejson as json

key = '0123456789abcdef'
mode = AES.MODE_CBC
encryptor = AES.new(key, mode)
text = '1010101010101010'

json.dumps(encryptor.encrypt(text))

How to avoid this error?

Thanks in advance!


回答1:


The Cipher usually generates non-printable binary data. It is not possible for json to dump non-printable characters.

One solution could be to use base64 encoding prior to json dump:

from Crypto.Cipher import AES
import simplejson as json
import base64

key = '0123456789abcdef'
mode = AES.MODE_CBC
encryptor = AES.new(key, mode)
text = '1010101010101010'

json.dumps(base64.encodestring(encryptor.encrypt(text)))

Similarly, before decryption, you'll have to decode base64 as well.



来源:https://stackoverflow.com/questions/8863423/python-pycrypto-module-why-simplejson-cant-dumps-encrypted-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!