Search code examples
phpdeprecatedmcryptphp-openssl

How to decrypt after Mcrypt deprecation?


I have updated my php version to 7.1. I had functions where i encrypt data using mcrypt. Now this function is deprecated.

How can i decrypt the data anyway withoud going back to older versions of php.

This is the code i used:

public function encrypt($plaintext) {
    $ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
    $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
    $ciphertext = mcrypt_encrypt(self::CIPHER, $this->key, $plaintext, self::MODE, $iv);
    return base64_encode($iv.$ciphertext);
}

public function decrypt($ciphertext) {
    $ciphertext = base64_decode($ciphertext);
    $ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
    if (strlen($ciphertext) < $ivSize) {
        throw new Exception('Missing initialization vector');
    }

    $iv = substr($ciphertext, 0, $ivSize);
    $ciphertext = substr($ciphertext, $ivSize);
    $plaintext = mcrypt_decrypt(self::CIPHER, $this->key, $ciphertext, self::MODE, $iv);
    return rtrim($plaintext, "\0");
}

With Constants:

const CIPHER = MCRYPT_RIJNDAEL_128; // Rijndael-128 is AES
const MODE   = MCRYPT_MODE_CBC;

I saw that it was recommended to use OpenSSL. That is what i will use from now on. But how can i decrypt the older data using this method?

Thanks

Edit: I know i can use OpenSSL as alternative. Thats what i am doing for the content from now on. But i need to decrypt my mcrypted code from my old contents.

*Edit request @symcbean

Tried to decrypt with OpenSSL like this:

public function decrypt($ciphertext) {
    $ciphertext = base64_decode($ciphertext);

    if (!function_exists("openssl_decrypt")) {
       throw new Exception("aesDecrypt needs openssl php module.");
    }

$key    = $this->key;
$method = 'AES-256-CBC';
$ivSize = openssl_cipher_iv_length($method);
$iv     = substr($ciphertext,0,$ivSize);
$data   = substr($ciphertext,$ivSize);
$clear  = openssl_decrypt ($data, $method, $key, 'OPENSSL_RAW_DATA'|'OPENSSL_ZERO_PADDING', $iv);

return $clear;
}

Solution

  • I solved it. Don't know if its the right way (guess not) But connected remotely on a server with a lower php version. Decrypted all the content and encrypted with OpenSSL.

    Thanks for the suggestions!