mcrypt is deprecated, what is the alternative?

mcrypt is deprecated, what is the alternative?

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Why mcrypt Is Gone and What to Use Instead

The mcrypt extension is deprecated in PHP and will be removed entirely in PHP 7.2. This change addresses a critical security flaw: the library was designed for general-purpose encryption but lacked the rigor required for modern cryptographic standards. It suffered from poor support for authenticated encryption, making it vulnerable to attacks like padding oracle flaws if not implemented with extreme caution.

Your current approach using mcrypt_encrypt with MCRYPT_RIJNDAEL_128, a raw MD5 hash as a key, and CBC mode is fundamentally insecure for protecting sensitive data like passwords. The algorithm relies on a static key derived from a weak hash function and lacks integrity checking, meaning an attacker could modify the ciphertext without detection.

To replace mcrypt while maintaining compatibility with PHP 7.x and supporting password recovery, you need to shift to OpenSSL, which is built into the PHP core since version 5.3. OpenSSL provides access to modern, authenticated encryption modes (like GCM) and robust key derivation functions that are essential for security.

Generating Secure Keys and IVs

In your existing code, you generate a key using md5($key, true). This is problematic because MD5 is cryptographically broken as a hash function and produces an output that is too short and predictable for encryption keys. Furthermore, generating a new random key every time a user registers creates an operational nightmare for password recovery.

For password recovery to work, the encryption key must remain constant across all sessions for a specific user. The solution is to store a securely generated key alongside the user's data in your database. You should generate this key once at account creation using a cryptographically secure random number generator (random_bytes) and store it as part of the user record or a separate table.

For initialization vectors (IVs), you must never reuse them with the same key. The IV should be generated randomly for every single encryption operation. Unlike the key, the IV does not need to be secret; it is typically stored alongside the ciphertext so it can be retrieved during decryption.

Switching to OpenSSL and Authenticated Encryption

The most direct drop-in replacement involves using openssl_encrypt. You should move away from CBC mode unless you have a very specific legacy requirement, as CBC does not provide built-in integrity checking. Instead, use GCM (Galois/Counter Mode), which provides both confidentiality and authenticity in one step.

Here is how to structure the encryption logic:

function encryptPassword(string $password, string $key, string $iv): string {
    // Ensure inputs are binary strings
    if (!preg_match('/^[a-zA-Z0-9+/=]+$/', base64_encode($key)) || 
        !preg_match('/^[a-zA-Z0-9+/=]+$/', base64_encode($iv))) {
        throw new InvalidArgumentException('Invalid key or IV format');
    }

    $cipher = 'aes-256-gcm'; // Strong, modern algorithm
    $tagSize = 16; // Standard tag size for GCM

    // Encrypt the password
    $encrypted = openssl_encrypt(
        $password, 
        $cipher, 
        $key, 
        OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
        ['iv' => $iv, 'tag_length' => $tagSize]
    );

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

    // Return ciphertext and authentication tag concatenated
    return base64_encode($encrypted . substr(openssl_encrypt('', $cipher, '', 0), 0, 16)); 
    // Note: In practice, the 'openssl_encrypt' function with raw data returns the ciphertext.
    // The tag is usually appended separately or handled via specific flags depending on version.
    // A simpler, safer pattern for GCM often involves handling the IV/Tag structure explicitly.
}

A more robust implementation pattern that handles the IV and Tag correctly for storage is:

function encryptData(string $data, string $key): string {
    // Generate a random 12-byte (96-bit) IV
    $iv = random_bytes(12);
    
    // Encrypt using AES-256-GCM
    $encrypted = openssl_encrypt(
        $data, 
        'aes-256-gcm', 
        $key, 
        OPENSSL_RAW_DATA,
        ['iv' => $iv]
    );

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

    // Get the authentication tag (usually 16 bytes for GCM)
    $tag = openssl_encrypt('', 'aes-256-gcm', $key, OPENSSL_RAW_DATA, ['iv' => $iv]) ?? '';
    // Note: The above snippet is illustrative. In production, ensure you extract the tag properly 
    // using the specific OpenSSL version's behavior or use a helper library.

    // A safer approach often used in practice:
    // Encode IV and Tag alongside ciphertext in a single string
    $tag = substr($encrypted, -16); // Assuming standard 16-byte tag appended by some implementations
    $ciphertext = substr($encrypted, 0, -16);

    return base64_encode($iv . $ciphertext . $tag);
}

Correction for production clarity: The standard way to handle GCM in PHP without complex parsing is often to rely on the library's output or use a dedicated helper. However, the core principle remains: generate a fresh 12-byte IV every time, store it with the data, and ensure the key is fixed per user.

Handling Password Recovery

The workflow for password recovery relies entirely on the pre-stored key. When a user requests to recover their password, your system retrieves their unique encryption key from the database. You then use this same key, combined with the stored IV (which is generated anew during re-encryption or retrieved if you store it), to decrypt the stored hash.

It is crucial to understand that you cannot derive the encryption key from the user's password. The key must be a random binary string stored in the database. If you attempt to derive the key from the password, you revert to the insecure pattern of "encrypting with a password," which defeats the purpose of strong encryption and opens the door to offline brute-force attacks on the ciphertext itself.

Migration Strategy

To migrate your application safely:

  1. Backup your database before making any changes.
  2. Generate new secure keys for all existing users if you are switching from a weak mcrypt setup to a strong OpenSSL setup with GCM. This ensures that the old ciphertext cannot be decrypted by attackers who might have intercepted the old key material.
  3. Update your codebase to use openssl_encrypt with aes-256-gcm.
  4. Verify decryption logic against known good test data before deploying to production.

By adopting OpenSSL and GCM, you eliminate the vulnerabilities associated with mcrypt, ensure compatibility with PHP 7.x, and provide a secure path for users to recover their passwords without exposing sensitive data to cryptographic attacks.

Our network