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

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 ep

def 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类型

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章