Using AES 128 CBC encryption with samekey and iv in php and mysql but getting different encrypted data, Why is this problem?

Below is my php code

<?php

class AES
{
    const KEY = '1234567890123456';
    const IV = '1234567890123456';

    public function decode($str)
    {
        $decrypted = openssl_decrypt(base64_decode($str), "AES-128-CBC", self::KEY, OPENSSL_RAW_DATA, self::IV);

        if ($decrypted === false) {
            throw new \Exception('Decryption failed');
        }

        return $decrypted;
    }

    public function encode($str)
    {
        $encrypted = openssl_encrypt($str, "AES-128-CBC", self::KEY, OPENSSL_RAW_DATA, self::IV);

        if ($encrypted === false) {
            throw new \Exception('Encryption failed');
        }

        return base64_encode($encrypted);
    }
}

try {
    $aes = new AES();
    $encryptedMessage = $aes->encode('My Secret Message');

    var_dump($encryptedMessage); // '4jZf0a8oV3Xa5e0TyI7EcLAI3FGstD9Hn6teGkzjFIQ=
    var_dump($aes->decode($encryptedMessage)); // My Secret Message
} catch (\Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Below is my Mysql query

select to_base64(AES_ENCRYPT(‘My Secret Message’, ‘1234567890123456’, ‘1234567890123456’));
//This query returns “s3X4cUy7BvhKYcZ/GJmJcoNlZA3qZxFe9XA9w2YYqgU=” as encrypted data

1 Like

The issue likely stems from differences in the encoding or padding methods used by PHP’s openssl_encrypt function and MySQL’s AES_ENCRYPT function. Ensure that both platforms are using the same encoding and padding options, such as OPENSSL_RAW_DATA in PHP and NULL in MySQL. Additionally, check that the input strings are identical and that there are no extra characters or whitespace causing discrepancies.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.