Best way to use PHP to encrypt and decrypt passwords?

Best way to use PHP to encrypt and decrypt passwords?

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

Stefan Bogdanescu

Founder & Senior Architect

Best way to use PHP to encrypt and decrypt passwords?

The core misunderstanding in the original question stems from conflating encryption with hashing. You are attempting to store foreign account credentials (like Rapidshare) so you can retrieve them later. This requirement dictates that you must use encryption, not hashing. Hashing is a one-way mathematical transformation designed specifically to obscure data; once hashed, the original value is mathematically impossible to recover without the specific salt and algorithm parameters used at creation time, which defeats the purpose of storing reversible credentials.

Base64 encoding is strictly for transport or storage serialization, not security. It is deterministic and easily reversible by anyone with a text editor or a standard library function. Using Base64 alone provides zero protection against an attacker who gains access to your database. If you simply Base64 encode the password, you are effectively storing it in plain text under a different encoding scheme.

To achieve reversible encryption in PHP, you must use a symmetric algorithm like AES (Advanced Encryption Standard). The standard function for this is openssl_encrypt and its counterpart openssl_decrypt. However, implementing this correctly requires handling three distinct components: the key, the initialization vector (IV), and the padding mode.

You cannot hardcode a static key or IV into your code. If you do, every time the application restarts or deploys to a new server, the decryption will fail because the environment no longer possesses the exact same cryptographic state as the one used for encryption. Furthermore, using a static IV is a critical security flaw; it allows attackers to detect patterns in encrypted data.

The correct implementation pattern involves generating a random IV for every single encryption operation. You must store this IV alongside the encrypted ciphertext in your database. When decrypting, you retrieve the stored IV and pass it back into the decryption function. This ensures that even if two users have identical passwords, their encrypted storage values will be completely different.

Here is a practical implementation using the AES-256-CBC cipher:

function encryptPassword(string $password): string {
    // Generate a random 16-byte (128-bit) IV for every encryption
    $ivLength = openssl_cipher_iv_length('aes-256-cbc');
    $iv = random_bytes($ivLength);
    
    // Generate a secure key from your master password or secret
    // In production, derive keys using PBKDF2 from a stored master secret
    $key = hash('sha256', 'YOUR_MASTER_SECRET_KEY_HERE'); 
    
    $options = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;

    return base64_encode(opensl_encrypt($password, $key, 'aes-256-cbc', ['iv' => $iv], $options));
}

function decryptPassword(string $encryptedPassword): string {
    // Split the ciphertext and IV from the Base64 encoded string
    $decoded = base64_decode($encryptedPassword);
    
    // Extract the first 16 bytes as the IV (assuming standard AES block size)
    $ivLength = openssl_cipher_iv_length('aes-256-cbc');
    $iv = substr($decoded, 0, $ivLength);
    $ciphertext = substr($decoded, $ivLength);

    // Decrypt using the same key and IV
    $key = hash('sha256', 'YOUR_MASTER_SECRET_KEY_HERE');
    
    $options = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;

    return openssl_decrypt($ciphertext, 'aes-256-cbc', $key, $options, $iv);
}

A critical pitfall to avoid is storing the IV in a separate column or sending it over the network separately. While technically possible, the industry standard is to prefix the IV directly to the ciphertext because most cryptographic libraries expect the IV as the first part of the data stream when using CBC mode. Storing them together in a single text or longtext column simplifies database schema design without compromising security, provided you parse them correctly upon retrieval.

Another significant trade-off involves key management. In the example above, we derive a key from a static string (YOUR_MASTER_SECRET_KEY_HERE). If this secret is hardcoded in your application, changing it requires a full migration of all stored passwords. A more robust approach for high-security applications involves storing a single master salt in the database (or environment variables) and using random_bytes combined with that salt to derive keys dynamically, or utilizing a key derivation function like PBKDF2 if encrypting user-provided secrets directly with a password they know.

For modern Laravel applications, you generally do not need to write this logic manually unless you are storing third-party credentials in a custom table. The framework provides robust tools for hashing via Hash::make(), but for reversible encryption of external accounts, you should consider whether the application needs to ever decrypt those specific values. If the goal is solely to verify login credentials later, storing a hash is often sufficient and significantly more secure than encryption. However, if business logic requires retrieving the original username or password to interact with the third-party API, symmetric encryption with dynamic IVs is the only viable path forward.

If you are building this on top of Laravel, ensure you validate that your database column type supports large strings, as encrypted data expands in size. Use text columns for AES-256-CBC ciphertext rather than varchar, which may truncate the output depending on length limits. Always verify that your PHP version is 7.3 or higher to ensure full support for modern OpenSSL configurations and constant definitions like OPENSSL_ZERO_PADDING.

Our network