使用的代碼如下
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:
# 創(chuàng)建用于解密的AES對(duì)象
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:
# 將十六進(jìn)制的數(shù)據(jù)轉(zhuǎn)換成二進(jìn)制
hex_data = binascii.a2b_hex(encryptLogTmp)
# 解密完成后,需要對(duì)數(shù)據(jù)進(jìn)行取消填充,獲取原來(lái)的數(shù)據(jù)
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())
各種折騰都出現(xiàn)亂碼
最后排查到原因是:AES.new對(duì)象當(dāng)時(shí)為了節(jié)省,在for循序里面復(fù)用了,所以解決方法每次AES.new即可!