Eamonn

人生苦短,我用Python

· Python · · 842次浏览

Python实现AES加密

python实现AES加密,进行反爬虫破解

"""
aes加密算法
padding : PKCS7
"""
from Crypto.Cipher import AES
import base64
class AESUtil(object):    
    def __init__(self):        
        self.key="uA4x6790@23_56a@"    #这两个值在网页源代码中可以找到
        self.iv="uA4x6790@23_56a@"    
        __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size    
    def encryt(self,data):        
        cipher = AES.new(self.key.encode("utf8"), AES.MODE_CBC,self.iv.encode("utf8"))        
        x = AESUtil.__BLOCK_SIZE_16 - (len(data) % AESUtil.__BLOCK_SIZE_16)        
        # print(x)        
        if x != 0:            
            data = data + "_"*x       #进行补全
            # print(data)        
            msg = cipher.encrypt(data.encode("utf8"))        
            # msg = base64.urlsafe_b64encode(msg).replace(‘=‘, ‘‘)        
            msg = base64.b64encode(msg)        
            return msg    
    def decrypt(self,enStr):        
        cipher = AES.new(self.key.encode("utf8"), AES.MODE_CBC, self.iv.encode("utf8"))        
        # enStr += (len(enStr) % 4)*"="        
        # decryptByts = base64.urlsafe_b64decode(enStr)        
        decryptByts = base64.b64decode(enStr)        
        msg = cipher.decrypt(decryptByts)        
        paddingLen = msg[len(msg)-1]        
        return msg[0:-paddingLen]

if __name__ == '__main__':    
    main()
评论 (0条)