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
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'))