【问题标题】:Python pycrypto module: why simplejson can't dumps encrypted string?Python pycrypto 模块:为什么 simplejson 不能转储加密字符串?
【发布时间】:2012-01-15 00:17:25
【问题描述】:

它显示 UnicodeError: 'utf8' codec can't decode byte 0x82 in position 0: unexpected code byte

代码如下:

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))

如何避免这个错误?

提前致谢!

【问题讨论】:

    标签: python pycrypto


    【解决方案1】:

    密码通常生成不可打印的二进制数据。 json 不可能转储不可打印的字符。

    一种解决方案是在 json 转储之前使用 base64 编码:

    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)))
    

    同样,在解密之前,您也必须对 base64 进行解码。

    【讨论】:

    • 是的,就是这样!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 2020-10-05
    • 2013-12-06
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    相关资源
    最近更新 更多