python AES加密 ECB PKCS5


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

 


免責聲明!

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



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