美文网首页
Python的AES解密出现乱码

Python的AES解密出现乱码

作者: 逆水寒Stephen | 来源:发表于2023-08-10 16:50 被阅读0次

    使用的代码如下

    import logging
    from Crypto.Cipher import AES
    from Crypto.Util.Padding import pad
    from Crypto.Util.Padding import unpad
    import binascii
    from all_log_service import settings
    logger = logging.getLogger(__name__)
    
    class AESUtil:
        def decrypt(self, decryptPwd, decryptIv, encryptLogStr):
            outputLogStr = ''
            try:
                encryptLogAry = encryptLogStr.split("\n")
                if encryptLogAry is not None and len(encryptLogAry) > 0:
                    # 创建用于解密的AES对象
                    cipher2 = AES.new(decryptPwd.encode('utf8'), AES.MODE_CBC, decryptIv.encode('utf8'))
                    for encryptLog in encryptLogAry:
                        encryptLogTmp = encryptLog.strip()
                        # print '========encryptLogTmp:',encryptLogTmp
                        if encryptLogTmp is not None and len(encryptLogTmp) > 0:
                            if 0 == len(encryptLogTmp) % 2:
                                # 将十六进制的数据转换成二进制
                                hex_data = binascii.a2b_hex(encryptLogTmp)
                                # 解密完成后,需要对数据进行取消填充,获取原来的数据
                                outputLogStr += (unpad(cipher2.decrypt(hex_data), 16) + "\n")
                            else:
                                outputLogStr += '======>odd str skip:'+str(encryptLog) + "\n"
                        else:
                            print '======>empty str skip:'+str(encryptLog) + "\n"
            except Exception as err:
                logging.error(err)
            print 'execLogDecrypt========over:',outputLogStr
    
    if __name__ == '__main__':
        encryptLogStr = "8FB19FDCEE9922E9B28703ED077EE197FCAF9E338506A8BF146D9A9FF1B0ED3E7D2DDDF0A3264063D3892443AD4D780152E9C5F00C2F5962C1AA1D8F7A124050E7011F7B7E92CB74F4C5D87123A36FBB5EBC83BDE160748710041E89E8318D98D31417EE71F8A758CC60BB7C88F416B629E2118A7F0A2D749E6F0C38A3C2B99589DD6A2BF30D83D227459EC7C896D77A\n8FB19FDCEE9922E9B28703ED077EE197FCAF9E338506A8BF146D9A9FF1B0ED3E7D2DDDF0A3264063D3892443AD4D7801D9337787C753EA29C2F3924AC485F24A273FE952E3E71A43B899C6513AE2FEFB189A89F28D87E358566435C6B2635C01F9E5C60699E3EC3D8B6A8E41F8A42857D766AEE417D1B97DFD295DF25D83FEAE1C3BF073C884765A8D38335ED503DE06"
        ase_util = AESUtil()
        ase_util.decrypt("xxxx", "xxxx", d.encode())
    

    各种折腾都出现乱码


    image.png

    最后排查到原因是:AES.new对象当时为了节省,在for循序里面复用了,所以解决方法每次AES.new即可!


    image.png

    相关文章

      网友评论

          本文标题:Python的AES解密出现乱码

          本文链接:https://www.haomeiwen.com/subject/wudzpdtx.html