How do you Encrypt and Decrypt a PHP String?

How do you Encrypt and Decrypt a PHP String?

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

Stefan Bogdanescu

Founder & Senior Architect

How do you Encrypt and Decrypt a PHP String?

When developers ask how to encrypt a string in PHP, they are often visualizing a simple transformation: take an original value like "hello world!" and a secret key like "ABCD1234", combine them, and produce a scrambled output. The reverse operation must be possible using the same key to retrieve the exact original text. This pattern—Original + Key → Encrypted, then Encrypted + Key → Original—is the fundamental requirement for symmetric encryption in application logic.

While the concept is straightforward, implementation details vary significantly depending on the cryptographic function chosen. You might recall attempts using Crypt_Blowfish (now part of the older PHP Cryptographic Extensions) or legacy functions like mcrypt. These approaches are increasingly problematic due to deprecated extensions and security vulnerabilities associated with weak algorithms in modern environments.

The most robust, supported, and recommended approach today is OpenSSL. Modern PHP installations include the OpenSSL extension by default, providing access to secure hashing and encryption primitives without requiring external libraries or legacy dependencies.

Using OpenSSL for Encryption

To encrypt a string, you cannot simply concatenate the key with the data and run it through a function; the algorithm must handle the mixing of the key and plaintext securely. In PHP 7.4 and later, the openssl_encrypt function offers a high-level interface that handles these complexities automatically when using authenticated encryption modes like GCM (Galois/Counter Mode).

Here is how you construct a secure encryption routine:

function encryptData(string $data, string $key): ?string {
    // We use AES-256-GCM for authenticated encryption.
    // The key must be 256 bits (32 bytes) long for this mode.
    
    if (strlen($key) < 32) {
        throw new InvalidArgumentException('Key must be at least 32 bytes.');
    }

    $ivLength = openssl_cipher_iv_length('aes-256-gcm');
    $encrypted = openssl_encrypt(
        $data, 
        'AES-256-GCM', 
        $key, 
        OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING // Zero padding is deprecated in PHP 8.1+, use explicit IV handling below
    );

    return $encrypted;
}

However, there is a critical nuance often missed: you must store the Initialization Vector (IV). In older tutorials or manual implementations using OPENSSL_RAW_DATA without an explicit IV generation step, developers might assume the IV is hidden or constant. This is incorrect for GCM modes. The IV must be random for every encryption operation to prevent pattern analysis attacks.

A secure implementation generates a random IV, encrypts the data, and then prepends the IV to the ciphertext so it can be retrieved during decryption:

function encryptSecure(string $data, string $key): string {
    if (strlen($key) < 32) {
        throw new InvalidArgumentException('Key must be at least 32 bytes.');
    }

    // Generate a random IV specific to this encryption operation
    $ivLength = openssl_cipher_iv_length('aes-256-gcm');
    $iv = random_bytes($ivLength);

    try {
        $encrypted = openssl_encrypt(
            $data, 
            'AES-256-GCM', 
            $key, 
            OPENSSL_RAW_DATA,
            $iv
        );

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

        // Prepend the IV to the encrypted data for storage/transmission
        return base64_encode($iv . $encrypted);
    } catch (Exception $e) {
        // Handle error appropriately
        throw new RuntimeException('Encryption failed: ' . $e->getMessage());
    }
}

Decryption Logic

Decryption is the inverse process but requires strict adherence to the data format established during encryption. You cannot pass the encrypted string directly to openssl_decrypt if it was prepended with an IV. The decoding logic must first extract the IV, then use that specific IV to decrypt the payload.

function decryptSecure(string $encryptedData, string $key): ?string {
    try {
        // Decode the combined IV + Ciphertext
        $decoded = base64_decode($encryptedData);

        if ($decoded === false) {
            throw new RuntimeException('Invalid encoded data');
        }

        // Extract the IV and the ciphertext
        $ivLength = openssl_cipher_iv_length('aes-256-gcm');
        $iv = substr($decoded, 0, $ivLength);
        $encrypted = substr($decoded, $ivLength);

        $decrypted = openssl_decrypt(
            $encrypted, 
            'AES-256-GCM', 
            $key, 
            OPENSSL_RAW_DATA,
            $iv
        );

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

        return $decrypted;
    } catch (Exception $e) {
        // In production, log this rather than throwing generic exceptions
        // to avoid leaking information about the key or IV validity.
        return null; 
    }
}

Key Management and Security Trade-offs

A common pitfall is assuming that the "key" can be a weak string like "password123". Cryptographic security relies heavily on entropy. If you must derive a key from a user-provided password (e.g., "ABCD1234"), you should not use it directly as the raw key for AES-256-GCM. Instead, use Argon2id or Bcrypt to hash the password first, ensuring that even if two users choose similar passwords, their derived keys remain unique and computationally expensive to guess.

Furthermore, never store the salt separately if you are using a key derivation function (KDF) like Argon2id, as these functions handle salting internally. However, for raw AES encryption where you generate a random key file or use a shared secret, that key must be stored securely outside of the application codebase, ideally in an environment variable or a secrets manager.

If you are building a larger framework and need to manage this complexity without reinventing the wheel, consider leveraging established packages like Laravel's encryption services, which abstract these low-level OpenSSL calls into secure, configurable classes. While specific resources like https://laravelcompany.com discuss broader architectural patterns, the underlying cryptographic principles remain identical: use authenticated encryption modes (GCM), manage IVs correctly, and derive keys from passwords rather than using them directly.

Our network