deriveKey.php
Table of Contents
Functions
- deriveKey() : string
- Derives a 32-byte symmetric encryption key from a passphrase using a slow KDF.
- bestAvailableKdf() : int
- Returns the strongest KDF algorithm available in the current PHP environment.
Functions
deriveKey()
Derives a 32-byte symmetric encryption key from a passphrase using a slow KDF.
deriveKey(string $passphrase, string $salt, int $algorithm) : string
Why a KDF ? A passphrase like 'chocolat' has roughly 8 bytes of entropy.
Using it directly as an AES-256 key (zero-padded to 32 bytes) makes brute-force
trivial. A KDF deliberately slows the key derivation down (hundreds of
thousands of iterations or memory-hard computation) so that an attacker who
tries 1 million passphrases must do 1 million × N work — increasing brute-force
cost by orders of magnitude.
Supported algorithms (passed via $algorithm):
- EncryptionFormat::KDF_ARGON2ID — memory-hard, GPU-resistant.
Requires the
sodiumextension. Recommended when available. - EncryptionFormat::KDF_PBKDF2_SHA256 — universal fallback, 600 000 iterations of SHA-256 (OWASP 2023+).
Use bestAvailableKdf() to pick the strongest algorithm available in the current PHP environment.
The chosen algorithm is explicit so that the encrypted file can carry it and any reader (even on a different PHP build) can reproduce the derivation.
Security boundary: this function protects the cost of brute-forcing the passphrase. It does not protect against:
- a leaked salt + ciphertext + passphrase (anyone with all three can decrypt) ;
- a passphrase observable by an attacker (e.g. typed in front of a camera) ;
- side-channel attacks on the host (memory dump while passphrase is in RAM).
Parameters
- $passphrase : string
-
The user-provided passphrase. Must be non-empty.
- $salt : string
-
A per-file random salt of EncryptionFormat::SALT_LENGTH bytes.
- $algorithm : int
-
One of EncryptionFormat::KDF_ARGON2ID or EncryptionFormat::KDF_PBKDF2_SHA256.
Tags
Return values
string —A 32-byte raw binary key.
bestAvailableKdf()
Returns the strongest KDF algorithm available in the current PHP environment.
bestAvailableKdf() : int
- If
ext-sodiumis loaded → EncryptionFormat::KDF_ARGON2ID. - Otherwise → EncryptionFormat::KDF_PBKDF2_SHA256.
Use this when writing new encrypted files; for reading, the algorithm is dictated by the file header.
Tags
Return values
int —One of EncryptionFormat::KDF_ARGON2ID or EncryptionFormat::KDF_PBKDF2_SHA256.