1

I want to convert some existing AES code from M2Crypto to the equivalent pycrypto but the documentation is thin, especially for M2Crypto. I have reduced the relevant code to a gist. The main issues are:

  • Pycrypto requires the input to be multiple of 16 in length, m2crypto does not.
  • Even when the input length is multiple of 16, the ciphertext differs. After experimenting with M2Crypto cipher parameters, it turns out that setting padding and key_as_bytes to false encrypts to the same ciphertext with pycrypto. So I need to emulate padding=True and key_as_bytes=True in pure python.

Any help would be much appreciated.

EDIT: Solved - the gist has been updated with the equivalent M2Crypto/pycrypto code and tests, I'll leave it there in case someone finds it useful in the future.

gsakkis
  • 1,569
  • 1
  • 15
  • 24

1 Answers1

2

You will have to implement PKCS#7 padding/unpadding, which is kind of simple and specified in the publicly available standard from RSA labs, and of course on Wikipedia. Also see this answer:

AES 256 Encryption with PyCrypto using CBC mode - any weaknesses?

Note that PKCS#7 padding and PKCS#5 padding are identical, although the latter is officially only for 8 byte block ciphers (e.g. DES/TDEA). OpenSSL uses PKCS#7 padding by default.

Community
  • 1
  • 1
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Thanks, that fixed the padding issue! I updated the gist and verified that the ciphertexts match when changing KEY_AS_BYTES to false. Now need to figure out what `key_as_bytes` does. – gsakkis Jan 17 '13 at 11:29
  • If you are not so lucky it is a misnamed `EVP_BytesToKey`(3). I say unlucky because OpenSSL uses a proprietary key derivation function, which would probably mean implementing it in Python. That is doable, and if you test well, it is not really an issue regarding security, but it does require some crypto understanding. – Maarten Bodewes Jan 18 '13 at 14:40
  • I figured it out eventually mainly thanks to [this answer](http://stackoverflow.com/questions/8008253/c-sharp-version-of-openssl-evp-bytestokey-method) and updated the gist with more extensive tests. – gsakkis Jan 19 '13 at 13:00