python 中对 aes加密json数据,进行解密时注意点

来源:互联网 发布:淘宝客网站建站模板 编辑:程序博客网 时间:2024/05/20 14:44
from Crypto.Cipher import AES    def params_aes_encrypt(self,text):    '''数据加密'''    text = text.replace(" ", "")    BS = 16    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)    text = pad(text)    o_aes = AES.new(self.aes__key.encode(), AES.MODE_CBC, self.aes_iv.encode())    esb = o_aes.encrypt(text.encode("UTF8"))    ep = base64.b64encode(esb).decode("UTF8")    return epdef params_aes_dncrypt(self,text):    '''数据解密'''    o_aes = AES.new(self.aes__key.encode(), AES.MODE_CBC, self.aes_iv.encode())    plain_text = o_aes.decrypt(base64.b64decode(text))    return plain_text

// aes采用的是pycryptodome包中的aes
1.self.aes__key 和 self.aes_iv 值必须是字节类型
2.大坑,aes在对数据解密时,返回的是bytes类型,会在数据最后添加空格,这样在json.loads()时会爆出
source code string cannot contain null bytes错误。解决办法时在数据解密后,调用bytes的strip()方法删除空格,再json.loads 是就可以了
3.需要注意网页返回数据的格式,可以采用chardet包的detect(string) string需要时bytes类型

阅读全文
0 0
原创粉丝点击