2

The idea is to AES encrypt a string and send it to my server side, and then decrypt it there to get the real string. But it didn't work and oddly I found out the result is different even when you AES-256 encrypt a string on python and php respectively.

Python example:

from Crypto.Cipher import AES
import base64

original = "originalstring"
key = "12345678123456781234567812345678"
IV = "1234567812345678"

b64encodedOnly = base64.b64encode(original)

encryptCipher = AES.new(key, AES.MODE_CFB, IV)
encrypted = base64.b64encode(encryptCipher.encrypt(original))

decryptCipher = AES.new(key, AES.MODE_CFB, IV)
decrypted = decryptCipher.decrypt(base64.b64decode(encrypted))

print "original:", original
print "b64encoded only:", b64encodedOnly
print "AES-256 encrypted:", encrypted
print "AES-256 decrypted:", decrypted

Python output:

original: originalstring
b64encoded only: b3JpZ2luYWxzdHJpbmc=
AES-256 encrypted: Rl4MMQojmBm0e6iuCl8=
AES-256 decrypted: originalstring

PHP example:

<?php
$original = "originalstring";
$key = "12345678123456781234567812345678";
$IV = "1234567812345678";

$b64encodedOnly = base64_encode($original);
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $original, MCRYPT_MODE_CFB, $IV));
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($encrypted), MCRYPT_MODE_CFB, $IV);

echo "original: " . $original . "<br />";
echo "b64encoded only: " . $b64encodedOnly . "<br />";
echo "AES-256 encrypted: " . $encrypted . "<br />";
echo "AES-256 decrypted: " . $decrypted . "<br />";

?>

PHP output:

original: originalstring
b64encoded only: b3JpZ2luYWxzdHJpbmc=
AES-256 encrypted: +w9F6zLD2avTt9fj8aM=
AES-256 decrypted: originalstring

As you can see after a AES-256(CFB mode) encryption then a base64 encoding, "originalstring" turns to "Rl4MMQojmBm0e6iuCl8=" on python while "+w9F6zLD2avTt9fj8aM=" on PHP. Clearly base64 functions the same since the result of encoding the original string is the same, so the only problem appears to be on AES encryption side, I believe it's a same algorithm implemented in different platform, how come the results are different?

EDIT:

I found the problem: MCRYPT_RIJNDAEL_256 is not equivalent to AES_256.

Check this out: https://stackoverflow.com/a/17249813/402197

Community
  • 1
  • 1
Shane
  • 4,875
  • 12
  • 49
  • 87

0 Answers0