python AES解密


AES解密

安裝

pip install Crypto

copy可用

import base64
from Crypto.Cipher import AES


class EncryptDate:
    def __init__(self, key):
        self.key = key.encode('utf-8')  # 初始化密鑰
        self.length = AES.block_size  # 初始化數據塊大小
        self.aes = AES.new(self.key, AES.MODE_ECB)  # 初始化AES,ECB模式的實例
        # 截斷函數,去除填充的字符
        self.unpad = lambda date: date[0:-ord(date[-1])]

    def pad(self, text):
        """
        #填充函數,使被加密數據的字節碼長度是block_size的整數倍
        """
        count = len(text.encode('utf-8'))
        add = self.length - (count % self.length)
        entext = text + (chr(add) * add)
        return entext

    def encrypt(self, encrData):  # 加密函數
        res = self.aes.encrypt(self.pad(encrData).encode("utf8"))
        msg = str(base64.b64encode(res), encoding="utf8")
        return msg

    def decrypt(self, decrData):  # 解密函數
        res = base64.decodebytes(decrData.encode("utf8"))
        print(res)
        msg = self.aes.decrypt(res).decode("utf8")
        print(msg)
        return self.unpad(msg)


text = 'Password0313!'  # 待加密文本
key = '123'  # 密鑰

eg = EncryptDate(key)  # 這里密鑰的長度必須是16的倍數

res = eg.encrypt(text)  # 加密函數
print(res)

res = eg.decrypt(res)  # 解密函數
print(res)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM