'How to add string var inside php code in python

I saw a php code to decrypt an encrypted AES-256-CBC string in PHP. But I'm using python, so I looked for a way to add a PHP script inside python.

This is how I did it as I saw from this link:

def decrypt(encrypted_data, password):
code = """<?php
  function decryptionM($data, $key) {
    $secretkey = str_pad($key, 32, '*'); 
    echo('secretkey: ');
    echo($secretkey);
    echo("\n");
    
    $iv_with_ciphertext = base64_decode(str_replace('plusencr', '+', $data));
    echo('iv_with_ciphertext: ');
    echo($iv_with_ciphertext);
    echo("\n");
    
    $iv_length = openssl_cipher_iv_length('AES-256-CBC');
    echo('iv_length: ');
    echo($iv_length);
    echo("\n");
    $iv = substr($iv_with_ciphertext, 0, $iv_length);
    echo('iv: ');
    echo($iv);
    echo("\n");
    $ciphertext = substr($iv_with_ciphertext, $iv_length);
    echo('ciphertext: ');
    echo($ciphertext);
    echo("\n");
    $text = openssl_decrypt($ciphertext, 'aes-256-cbc', $secretkey, OPENSSL_RAW_DATA, $iv);
    echo('text: ');
    echo($text);
    echo("\n");
    $asArr = explode(',', $text);
    echo('asArr: ');
    echo($asArr);
    echo("\n");
    foreach ($asArr as $val) { 
        $tmp = explode('=', $val);
        echo('tmp: ');
        echo($tmp[0]);
        echo("\n");
        $finalArray[trim($tmp[0])] = str_replace('+', '', $tmp[1 ]); 
    }
    echo('finalArray: ');
    echo($finalArray);
    echo("\n");
    return $finalArray; 
}

  echo decryptionM(""" + encrypted_data + """, """ + password + """);

?>
"""
res = php(code.encode())

return res

But the line echo decryptionM(""" + encrypted_data + """, """ + password + """); is outputting an error:

[2022-03-24 02:06:50,202: WARNING/MainProcess] b"PHP Parse error:  syntax error, unexpected '=', expecting ')' in Standard input code on line 55\n\nParse error: syntax error, unexpected '=', expecting ')' in Standard input code on line 55\n"

which I figured is caused by not having quotes surrounding the parameters which are strings when the echo decryptionM(""" + encrypted_data + """, """ + password + """); is transformed to PHP code.

decryptionM(data, key); should be decryptionM('data', 'key');

How do I do this in python or PHP?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source