from hashlib import sha256 import base64 from Crypto import Random from Crypto.Cipher import AES BS = 16 pad = lambda s: bytes(s + (BS - len(s) % BS) * chr(BS - len(s) % BS), 'utf-8') unpad = lambda s : s[0:-ord(s[-1:])] class AESCipher: def __init__( self, key ): self.key = bytes(key, 'utf-8') def encrypt( self, raw ): raw = pad(raw) iv = Random.new().read( AES.block_size ) print(iv,raw) cipher = AES.new(self.key, AES.MODE_CBC, iv ) return (iv + cipher.encrypt( raw )).hex() def decrypt( self, enc ): enc = bytes.fromhex(enc) iv = enc[:16] print(iv,enc) cipher = AES.new(self.key, AES.MODE_CBC, iv ) return unpad(cipher.decrypt( enc[16:] )).decode('utf8') cipher = AESCipher('mysecretpassword') encrypted = cipher.encrypt('Secret') decrypted = cipher.decrypt(encrypted) print(encrypted) print(decrypted)