Simplest two-way encryption using PHP

Simplest two-way encryption using PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Moving Beyond RC4: Native PHP Encryption Options

If you are currently using a custom RC4 implementation to handle two-way encryption in PHP, you are likely dealing with significant security debt. While your primary goal is portability and simplicity rather than high-security standards, relying on RC4 is problematic because it has been cryptanalytically broken for years. The algorithm produces predictable keystream patterns that allow attackers to recover plaintext or the key itself without ever seeing the encrypted data.

The modern standard for symmetric encryption in PHP is AES (Advanced Encryption Standard). Unlike RC4, which requires a third-party class or an older OpenSSL extension that might not be present on every shared hosting environment, native PHP support for AES is robust and widely available via the openssl extension. This extension is enabled by default on most common PHP installations, including those running on LaravelCompany's infrastructure, ensuring your code remains portable across different servers without needing to bundle extra libraries.

To achieve two-way encryption with a string key, you must understand the mechanics of the underlying cryptographic operations. You cannot simply pass a password string directly into an encryption function; you need a symmetric key derived from that password. This process is known as Key Derivation Function (KDF) or Password-Based Key Derivation (PBKDF). If you skip this step and use your raw string as the key, changing a single character in the password will result in a completely different encrypted output every time, making decryption impossible without exact byte-for-byte matching.

The most straightforward approach using native PHP involves the openssl_encrypt and openssl_decrypt functions. Here is a practical example that derives a secure key from your user-provided string and uses AES-256-CBC mode:

function encryptData($data, $password) {
    // Derive a 32-byte (256-bit) key from the password
    $ivLength = openssl_cipher_iv_length('aes-256-cbc');
    
    // Generate a random initialization vector (IV)
    $iv = random_bytes($ivLength);
    
    // The salt is used by PBKDF2 to derive the key, ensuring uniqueness per session
    $salt = 'your-hardcoded-salt-or-random'; 
    
    $derivedKey = hash_pbkdf2('sha256', $password, $salt, 10000);
    
    // Encrypt the data
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', $derivedKey, OPENSSL_RAW_DATA, $iv);
    
    return base64_encode($iv . ':' . $encrypted . ':' . $salt);
}

function decryptData($encryptedString, $password) {
    $encoded = base64_decode($encryptedString);
    list($iv, $encrypted, $salt) = explode(':', $encoded);
    
    // Re-derive the exact same key using the same password and salt
    $derivedKey = hash_pbkdf2('sha256', $password, $salt, 10000);
    
    // Decrypt the data
    $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $derivedKey, OPENSSL_RAW_DATA, $iv);
    
    return $decrypted;
}

The critical detail here is how we handle the Initialization Vector (IV) and the Salt. In CBC mode, the IV must be unique for every encryption operation, even if the key remains the same. A predictable IV leads to deterministic encryption, which leaks information about the data structure. That is why we generate a random 16-byte IV before encrypting and prepend it to the output.

Similarly, the Salt in the PBKDF2 process must be consistent for decryption to work, but it should ideally be unique per user or stored securely. In this simplified example, we embed the salt inside the encrypted blob using a delimiter. This ensures that when you decrypt on the other end, the system can re-derive the exact same key from your password string.

A common pitfall is attempting to use ECB (Electronic Codebook) mode instead of CBC or GCM. ECB is deterministic and insecure because identical plaintext blocks produce identical ciphertext blocks, revealing patterns in the data. Always prefer CBC or, even better, GCM (Galois/Counter Mode), which provides authenticated encryption. However, GCM requires OpenSSL 1.0.2 or later and careful handling of the authentication tag. For maximum compatibility with older PHP versions while maintaining strong security, AES-256-CBC remains the pragmatic choice.

If you need to manage these keys at scale or require more sophisticated key rotation strategies, exploring dedicated packages or integrating with Laravel's encryption system might be beneficial. For instance, if your application is built on Laravel, checking out how Laravel handles encryption internally can provide a drop-in replacement that abstracts away these low-level details while maintaining the same underlying cryptographic strength found in native extensions.

Our network