简体   繁体   中英

Encrypt Decrypt Python PHP convert AES

I have this issue where something is encrypted in python using aes 256 cbc encryption as shown in the python codes encrypt method .

I am trying to create a Decrypt method in php to actually decrypt whats encrypted using the python class .

Here is my attempt to convert the python decryption method to php does it look right or am I missing something in my conversion as every time i use the php version to decrypt it says hmac failed ?

anyhelp in converting the python class to php i will appreciate.

public function decrypt(){
        $encrypt_method ="AES-256-CBC";
        $secret_key =base64_decode('samekeyusedintheencryption');
        $encrypted=(string)'some encrypted text to be decrypted';
        $data=json_decode(base64_decode($encrypted),true);
        $secret_iv =base64_decode($data['iv']);
        $output = \openssl_decrypt($data['value'], 
        $encrypt_method,$secret_key,0,$secret_iv);
        return  json_encode($output);
    }


    def decrypt(self, payload):
        data = json_c.decode(base64.b64decode(payload))
        value =  base64.b64decode(data['value'])
        iv = base64.b64decode(data['iv'])
        crypt_object=AES.new(self.key,AES.MODE_CBC,iv)
        plaintext = crypt_object.decrypt(value)
        return loads(plaintext)

OK, I got it to work!

function decrypt($encryptedText, $secret_key){

$secret_key = base64_decode($secret_key);
$encrypt_method ="AES-256-CBC";

$data = json_decode(base64_decode($encryptedText),true);

$data['iv'] = base64_decode($data['iv']);
$data['value'] = base64_decode($data['value']);

return openssl_decrypt($data['value'], $encrypt_method, $secret_key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $data['iv']);

}

Some things I learned: If the options in the openssl function are set to '0' it expects a base64_encoded input for the cipher text. Also, if the default options is set to '0' the padding default is set to PKCS#7. This, I think, is why we were getting the bad block size error.

So, the cipher text needs to be base64_decoded and we need to set both options for the padding.

I was able to decrypt your provided cipher text and see the email addresses.

You are provided the MAC in the Data array so this would allow you to check the MAC in the PHP script. This allows you to make sure the data has not been tampered with.

I recently did an encryption project and started with the open ssl, but ended up changing to the libSodium library. I highly recommend you check it out for any further projects.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM