class AesEbc16: # 按塊的大小, 一塊一塊的加密, 明文和密文長度一樣
def __init__(self):
self.key = b"123qweqqqwerqwer" # 加密和解密用同一個秘鑰, 長度為 每塊的長度
self.mode = AES.MODE_ECB # ECB加密模式, 也是默認的模式, 創建AES加密對象時可以不寫
self.block_size = 16 # 每塊16的bytes長度, 即是PKCS5 這種方式, 和秘鑰長度一致
def plaintext(self, s_text): # 轉bytes 並 補齊為16的倍數
b_text = str.encode(s_text)
count = len(b_text)
# text不是16的倍數那就補足為16的倍數
add_count = self.block_size - (count % self.block_size)
s_plaintext = s_text + (' ' * add_count)
b_plaintext = str.encode(s_plaintext)
return b_plaintext
def encrypt(self, str_text): # 加密
aes_cipher = AES.new(self.key, self.mode) # ECB模式無需向量iv
b_cipher= aes_cipher.encrypt(self.plaintext(str_text))
return b_cipher
def decrypt(self, b_text): # 解密
aes_cipher = AES.new(self.key, self.mode)
b_plaintext = aes_cipher.decrypt(b_text)
s_plaintext = bytes.decode(b_plaintext)
return s_plaintext