Oihana PHP

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):

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
throws
RuntimeException

If the passphrase is empty, the salt has wrong length, the algorithm is unknown, or Argon2id is requested but the sodium extension is not loaded.

example
use function oihana\files\openssl\{ deriveKey , bestAvailableKdf } ;
use oihana\files\openssl\enums\EncryptionFormat;

$salt = random_bytes( EncryptionFormat::SALT_LENGTH ) ;
$algo = bestAvailableKdf() ;
$key  = deriveKey( 'my passphrase' , $salt , $algo ) ;
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

A 32-byte raw binary key.

bestAvailableKdf()

Returns the strongest KDF algorithm available in the current PHP environment.

bestAvailableKdf() : int

Use this when writing new encrypted files; for reading, the algorithm is dictated by the file header.

Tags
example
use function oihana\files\openssl\bestAvailableKdf;

$kdf = bestAvailableKdf() ;
// → KDF_ARGON2ID on PHP 8.4 with sodium (the usual case)
// → KDF_PBKDF2_SHA256 on stripped-down builds
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
int

One of EncryptionFormat::KDF_ARGON2ID or EncryptionFormat::KDF_PBKDF2_SHA256.

On this page

Search results