from Crypto.Cipher import AES import os def encrypt(msg,key,block_size): pad = block_size - len(msg) % block_size data = msg + pad * chr(pad) iv = os.urandom(block_size) cipheredtext = iv + AES.new(key, AES.MODE_CBC, iv).encrypt(data) return cipheredtext def decrypt(cipheredtext,key,block_size): iv = cipheredtext[:block_size] msg = AES.new(key, AES.MODE_CBC, iv).decrypt(cipheredtext[block_size:]) #remove the padding pad = ord(msg[-1]) msg = msg[:-pad] return msg if __name__ == '__main__' : block_size = 16 key_size = 32 key = os.urandom(key_size) msg1 = 'Guillaume is a genius!' msg2 = encrypt(msg1,key,block_size) msg3 = decrypt(msg2,key,block_size) print "original message: " + msg1 print "encrypted message: " + msg2.encode('hex') print 'verification: ' + msg3