Encrypt & Decrypt using PyCrypto AES 256

后端 未结 12 888
夕颜
夕颜 2020-11-22 13:07

I\'m trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message.

I found several links on

12条回答
  •  清酒与你
    2020-11-22 13:09

    Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes:

    import base64
    import hashlib
    from Crypto import Random
    from Crypto.Cipher import AES
    
    class AESCipher(object):
    
        def __init__(self, key): 
            self.bs = AES.block_size
            self.key = hashlib.sha256(key.encode()).digest()
    
        def encrypt(self, raw):
            raw = self._pad(raw)
            iv = Random.new().read(AES.block_size)
            cipher = AES.new(self.key, AES.MODE_CBC, iv)
            return base64.b64encode(iv + cipher.encrypt(raw.encode()))
    
        def decrypt(self, enc):
            enc = base64.b64decode(enc)
            iv = enc[:AES.block_size]
            cipher = AES.new(self.key, AES.MODE_CBC, iv)
            return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
    
        def _pad(self, s):
            return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
    
        @staticmethod
        def _unpad(s):
            return s[:-ord(s[len(s)-1:])]
    

提交回复
热议问题