Recommended

2009-11-07

AES encpytion in Python using C extensions

This blog post gives example code how to do AES encryption and decryption in Python. The crypto implementations shown are written in C, but they have a Python interface. For pure Python implementations, have a look at Python_AES in tlslite or SlowAES.

Example Python code using the AES implementation in alo-aes:

#! /usr/bin/python2.4# by pts@fazekas.hu at Sat Nov 7 11:45:38 CET 2009# Download installer from http://www.louko.com/alo-aes/alo-aes-0.3.tar.gzimportaes# Must be 16, 24 or 32 bytes.key='(Just an example for testing :-)'# Must be a multiple of 16 bytes.plaintext='x'*16*3o=aes.Keysetup(key)# This uses ECB (simplest). alo-aes supports CBC as well (with o.cbcencrypt).ciphertext=o.encrypt(plaintext)assert(ciphertext.encode('hex')=='fe4877546196cf4d9b14c6835fdeab1a'*3)assertlen(ciphertext)==len(plaintext)assertciphertext!=plaintext# almost always truedecrypted=o.decrypt(ciphertext)assertplaintext==decryptedprint'benchmarking'plaintext=''.join(map(chr,xrange(237))+map(chr,xrange(256)))*9*16assertlen(plaintext)==70992foriinxrange(1000):assertplaintext==o.decrypt(o.encrypt(plaintext))