Search code examples
phppythonencryptioncross-language

Encrypt in PHP, Decrypt in Python


PHP code:

$key = "12345678abcdefgh12345678abcdefgh";
$iv = "12345678abcdefgh";
$plaindata = "This is a test string.";

$enc = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaindata, MCRYPT_MODE_CBC, $iv));

echo($enc);

Result:

QBN0Yue3D9hBrBuD01n5KWG+lv2doMf97cKm/AeusAI=

How can this be decrypted in Python?


Solution

  • Try something like this (altho i do have PyCrypto installed)

    from Crypto.Cipher import AES
    import base64
    
    AES.key_size=128
    iv="your iv"
    key="your key"
    crypt_object=AES.new(key=key,mode=AES.MODE_CBC,IV=iv)
    
    decoded=base64.b64decode(plain) # your ecrypted and encoded text goes here
    decrypted=crypt_object.decrypt(decoded)
    

    This will bring the decoded text but it will be padded with bytes for it to be a size multiple of 16.

    You should probably decide on a proper padding scheme and remove it afterwards accordingly