Reputation: 83677
Here is my Python code, I can successfully encrypt and decrypt using M2Crypto:
from base64 import b64encode, b64decode
import M2Crypto
class AESEncryptionService(object):
def encrypt(self, key, msg):
return self.__cipher(key, msg, 1)
def decrypt(self, key, msg):
try:
decrypted = self.__cipher(key, msg, 0)
return decrypted
except:
return False
def __cipher(self, key, msg, op):
iv = '\0' * 16
iv.encode('ascii')
cipher = M2Crypto.EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=op)
v = cipher.update(msg)
v = v + cipher.final()
del cipher
return v
enc_service = AESEncryptionService()
cipher = b64encode(enc_service.encrypt("FD496E240E7822552BC0D63C03AB7ABB", "Hello Hello Hello Hello Hello Hello Hello"))
print cipher
plaintext = enc_service.decrypt("FD496E240E7822552BC0D63C03AB7ABB", b64decode(cipher))
print plaintext
Outputs:
oMkdgXOy49VvvbQksxuhBq3YqJWrEw++lZO3ZMYYyo6T7JpK+Ovp+tdm+FrVGPnN
Hello Hello Hello Hello Hello Hello Hello
I have written a simple test script in PHP hoping to get the same results:
<?php
$key = 'FD496E240E7822552BC0D63C03AB7ABB';
$plain = 'Hello Hello Hello Hello Hello Hello Hello';
$iv = '0000000000000000';
$cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plain, MCRYPT_MODE_CBC, $iv);
$plain = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $cipher, MCRYPT_MODE_CBC, $iv);
echo base64_encode($cipher), '<br>';
echo $plain;
Outputs:
v5QinnNaEkn8myZa31Ikl5DrrtSXrhebDERJz4uqUgWMvbZ3datyCbm9WHPGlAo7
Hello Hello Hello Hello Hello Hello Hello
Can you help me fix the Python code to output the same as PHP? I know PHP's implementation of AES is correct as I can decrypt it in .NET. The string outputted by M2Crypto Python library cannot be decrypted in .NET.
I think it might have something to do with padding.
M2Crypto.EVP.Cipher has padding parameter. I have tried setting it to 1, 2, 3, 128 but it doesn't seem to affect the cipher.
Upvotes: 0
Views: 1593
Reputation: 30157
Quick googling revealed the following snippet: http://www.example-code.com/python/crypt2_aes_matchPhp.asp
Maybe worth giving it a try?
Upvotes: 0
Reputation: 11051
Your PHP $iv
appears to be a string of ASCII zeros (so, byte 0x30
), where in the python iv
you appear to be using literal 0x00
bytes.
EDIT
You also appear to be passing the ciphertext through b64encode
and b64decode
. Are you quite sure these are exact inverses? No line breaks, formatting, trailing new lines, etc?
Upvotes: 1