Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 443
Vitalii Ponomar Avatar asked Sep 12 '26 19:09

Vitalii Ponomar


1 Answers

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.

like image 65
sharjeel Avatar answered Sep 15 '26 08:09

sharjeel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!