Encrypt & Decrypt using PyCrypto AES 256

后端 未结 12 1037
夕颜
夕颜 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:13

    Grateful for the other answers which inspired but didn't work for me.

    After spending hours trying to figure out how it works, I came up with the implementation below with the newest PyCryptodomex library (it is another story how I managed to set it up behind proxy, on Windows, in a virtualenv.. phew)

    Working on your implementation, remember to write down padding, encoding, encrypting steps (and vice versa). You have to pack and unpack keeping in mind the order.

    import base64
    import hashlib
    from Cryptodome.Cipher import AES
    from Cryptodome.Random import get_random_bytes
    
    __key__ = hashlib.sha256(b'16-character key').digest()
    
    def encrypt(raw):
        BS = AES.block_size
        pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    
        raw = base64.b64encode(pad(raw).encode('utf8'))
        iv = get_random_bytes(AES.block_size)
        cipher = AES.new(key= __key__, mode= AES.MODE_CFB,iv= iv)
        return base64.b64encode(iv + cipher.encrypt(raw))
    
    def decrypt(enc):
        unpad = lambda s: s[:-ord(s[-1:])]
    
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(__key__, AES.MODE_CFB, iv)
        return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))
    

提交回复
热议问题