方法一:抽象類版
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")) msg = self.aes.decrypt(res).decode("utf8") return self.unpad(msg) if __name__ == '__main__': text = '你是個小可愛' # 待加密文字 key = 'psjduiofnhsychs7' # 金鑰長度是16的倍數 eg = EncryptDate(key) res = eg.encrypt(text) # 加密函式 print("加密res:", res) res = eg.decrypt(res) # 解密函式 print("解密res", res)
方法二:單獨函式版
import base64
from Crypto.Cipher import AES
def encrypt(key_str, text_str):
aes_size = AES.block_size
count = len(text_str.encode("utf-8"))
add = aes_size - (count % aes_size)
text_str = text_str + (chr(add) * add)
res = AES.new(key_str.encode("utf-8"), AES.MODE_ECB).encrypt(text_str.encode("utf-8"))
enc_str = str(base64.b64encode(res), encoding="utf8").replace("\r\n", "").replace("+", "/add/")
return enc_str
def decrypt(key_str, enc_str):
res = base64.decodebytes(enc_str.encode("utf8"))
msg = AES.new(key_str.encode("utf-8"), AES.MODE_ECB).decrypt(res).decode("utf8")
unpad = lambda date: date[0:-ord(date[-1])]
return unpad(msg)
if __name__ == "__main__":
key_str = "8k6djkfhj78gfg65" # 鹽值長度16的倍數
text_str = '你是個小可愛' # 待加密的文字
print("待加密文字: ", text_str)
enc = encrypt(key_str, text_str)
print("加密文字:", enc)
dec = decrypt(key_str, enc)
print("解密文字:", dec)