AES decrypting in Python

M.-A. Lemburg mal at
Wed Oct 7 17:04:16 CEST 2009

Mike Driscoll wrote:
> Hi,
> I am working on a project where I need to decrypt some data that has
> been encrypted with AES. It looks like M2Crypto is the module of
> choice for these sorts of things, but I cannot figure out how to do
> this stuff from the docs. I have the following PHP code that needs to
> be translated into Python:
> $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
> $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
> return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key,
> $data,MCRYPT_MODE_ECB, $iv),"\0");
> I can't find a method in M2Crypto that gets the "initialization
> vector" size. I found the right method in the tests, which appears to
> be EVP.Cipher. So I would assume, I would need to do something like:
> EVP.Cipher(alg="aes_256_ecb", key=SomeKey, iv=SomeIV, op=dec,
> padding=False)
> I don't really see where I pass the data that needs the decrypting
> though. Can someone shed some light on this?

If you just need AES, you're probably better of with pycrypto:

Still, to answer your question: AES uses blocks of 16 bytes (256 bits)
each, so the IV-size is always 16 bytes.

BTW: I'm not sure what the PHP code is trying to do ... ECB mode
doesn't use the IV at all. It's only used for chained modes and
there you include the IV in the encrypted data (usually at the
beginning), since you need it for decryption. The PHP code
apparently generates a random IV block for decryption. This
would never work in e.g. CBC mode.

Marc-Andre Lemburg

Professional Python Services directly from the Source  (#1, Oct 07 2009)
>>> Python/Zope Consulting and Support ...
>>> mxODBC.Zope.Database.Adapter ...   
>>> mxODBC, mxDateTime, mxTextTools ...

::: Try our new mxODBC.Connect Python Database Interface for free ! :::: Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611

More information about the Python-list mailing list