AES decrypting in Python

Mike Driscoll kyosohma at
Wed Oct 7 17:55:52 CEST 2009

On Oct 7, 10:04 am, "M.-A. Lemburg" <m... at> wrote:
> 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

That's good to know. I had originally started with PyCrypto by
following the example here:

Unfortunately, no matter which base64 decoding method I use, I get a
padding error or in the case of b16decode, I get "TypeError: Non-
base16 digit found". AES decoding is something I've never done before,
so I apologize for my greenness.

I'll bug the guys on the pycrypto list as well.



More information about the Python-list mailing list