aes01.py

# =========================================================
# encrypt/decrypt using AES secret key
# =========================================================

from Crypto.Cipher import AES

# ---------------------------------------------------------
# pad string with '}' characters on the end
# make string length a multiple of 16
# ---------------------------------------------------------

def pad(s):
    return s + ((16-len(s) % 16) * '{')

def encrypt(plaintext):
    global cipher
    return cipher.encrypt(pad(plaintext))

def decrypt(ciphertext):
    global cipher
    dec =  cipher.decrypt(ciphertext).decode('utf-8')
    # remove attached '{' characters
    l = dec.count('{')
    return dec[:len(dec)-l]


# AES encrypt/decrypt key (generated externaly)

key = b'\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e[EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18'

##print('Key Len: ', len(key))

# create cypher object with AES key

cipher = AES.new(key)

# plaintext message

message = 'secret message just for you'

encrypted = encrypt(message)
decrypted = decrypt(encrypted)

print('  Message: {}'.format(message))
print('Encrypted: {} (len={})'.format(encrypted,len(encrypted)))
print('Decrypted: {}'.format(decrypted))