Encryption

For data your app needs to read back later (unlike Hash, which is one-way, for passwords). AES-256-GCM is authenticated: a wrong key or a tampered ciphertext throws, never returns partially- or incorrectly-decrypted data.

Methods

Encryption::generateKey(): string                       // 32 random bytes, suitable for this cipher
Encryption::encrypt(string $plaintext, string $key): string // base64 payload: iv + tag + ciphertext
Encryption::decrypt(string $payload, string $key): string   // throws RuntimeException on wrong key or tampering
$key = Encryption::generateKey();                 // store this — losing it makes ciphertext unrecoverable
$ciphertext = Encryption::encrypt('sensitive data', $key);
$plaintext = Encryption::decrypt($ciphertext, $key); // 'sensitive data'

Encryption::decrypt($ciphertext, Encryption::generateKey());
// throws RuntimeException: "Decryption failed: ciphertext is invalid or has been tampered with."

The key must be exactly 32 bytes — generateKey() guarantees this; a key from anywhere else (an env var, a KMS) must match that length or encrypt()/decrypt() throw InvalidArgumentException before touching OpenSSL at all.

Next steps

  • Hash — one-way hashing for passwords, not reversible encryption.