Two-way encryption: I need to store passwords that can be retrieved

Two-way encryption: I need to store passwords that can be retrieved

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

Stefan Bogdanescu

Founder & Senior Architect

Two-way encryption: I need to store passwords that can be retrieved

Storing and retrieving user-provided passwords in plaintext is a cardinal sin of web security, but your use case introduces a specific constraint: you must decrypt them later to send them to a hardware device. Since you cannot rely on hash comparisons, you are dealing with reversible encryption. This shifts the threat model significantly. You are no longer protecting against guessing; you are protecting against unauthorized decryption.

The safest algorithm for this scenario is AES-256-GCM (Galois/Counter Mode). Avoid older standards like AES-CBC or TripleDES, as they have known vulnerabilities regarding padding oracle attacks and lack authenticated encryption tags. GCM provides both confidentiality and integrity, ensuring that if an attacker modifies the ciphertext, you will detect it upon decryption rather than silently producing garbage output.

Implementation in PHP

To implement this in PHP, the native openssl extension is the standard tool. You need to generate a symmetric key (the "private key" for symmetric encryption) and an Initialization Vector (IV). The IV must be random and unique for every single encryption operation; never reuse it with the same key.

Here is a practical approach using PHP 8's OpenSSL functions:

function encryptData(string $data, string $key): string {
    // Generate a random 16-byte IV
    $iv = openssl_random_pseudo_bytes(16);
    
    // Encrypt with AES-256-GCM
    $tagLength = 16; // 128 bits of authentication
    $encrypted = '';
    $tag = '';
    
    if (openssl_encrypt($data, 'AES-256-GCM', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv, $encrypted, $tag)) {
        // Prepend IV and Tag to the ciphertext so they can be extracted later
        return base64_encode($iv . $encrypted . $tag);
    } else {
        throw new RuntimeException('Encryption failed');
    }
}

function decryptData(string $data, string $key): string {
    // Extract components from the stored value
    $decoded = base64_decode($data);
    $ivLength = 12; // 96 bits is standard for GCM
    $tagLength = 16; // 128 bits
    
    $iv = substr($decoded, 0, $ivLength);
    $tag = substr($decoded, -1 * $tagLength);
    $encrypted = substr($decoded, $ivLength, strlen($decoded) - ($ivLength + $tagLength));
    
    // Attempt decryption
    $decrypted = '';
    $authTagVerified = false;
    
    if (openssl_decrypt(
        $encrypted, 
        'AES-256-GCM', 
        $key, 
        OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, 
        $iv, 
        $decrypted, 
        $tag,
        true // Verify authentication tag
    )) {
        return $decrypted;
    } else {
        throw new RuntimeException('Decryption failed or invalid data');
    }
}

Key Management and Storage

You asked where to store the key. In a symmetric encryption scheme, the same secret is used for both locking (encrypting) and unlocking (decrypting). You must store this key securely alongside your database records, but never in plain text within a configuration file that might be version-controlled or accessible by web servers without proper permissions.

The industry standard is to derive the final key from a master secret using a Key Derivation Function (KDF) like PBKDF2, Argon2, or scrypt. If you store the raw symmetric key in your database, ensure that table has restricted file system permissions and, ideally, encrypt the entire column at rest using a separate hardware security module (HSM) or a dedicated key management service.

The "User Enters Key" Approach

You suggested requiring users to enter their private key every time they need a password decrypted. While this adds friction, it is often a poor user experience for trusted internal applications. If your users are indeed trusted and the application runs in a secure environment (e.g., behind a firewall, not exposed to the public internet), storing the key in a highly restricted database table or an encrypted configuration file accessible only by the application service account is more practical.

Requiring the user to input a decryption key shifts the burden of security entirely onto the user's memory and typing accuracy. If a user forgets their "decryption key," they lose access to their own passwords permanently. Unless your hardware device requires a specific authentication handshake that mandates external key verification, storing the key securely within the application is the standard pattern for administrative tools.

Threat Model: How Can This Be Stolen?

The primary risk with reversible encryption is Key Compromise. If an attacker gains read access to your database and also obtains your encryption key, they can decrypt every password instantly.

  1. Database Breach: If your DB is compromised, the data is useless unless the key is also exposed. Ensure your key storage location differs from your primary data store if possible (e.g., using a vault like HashiCorp Vault or AWS KMS).
  2. Memory Scraping: In PHP, keys loaded into memory can theoretically be extracted via ptrace on Unix systems or debuggers (gdb, lldb) by an attacker with low-level access to the server. Mitigate this by limiting process capabilities and running the web server in a hardened container or chroot environment.
  3. Backup Leakage: If you back up your database without excluding the key column, or if you back up your configuration files containing the key, you are creating offline copies that can be decrypted.

There is no "perfect" encryption. The security of this system relies entirely on the secrecy and strength of the key. If the key is stored in plaintext in a file readable by www-data, the encryption is effectively bypassed. Always treat the key with the same paranoia as the secrets themselves.

Our network