Home > Dev > Crypto > Implementing a PBKDF2 Key Derivation Function

Implementing a PBKDF2 Key Derivation Function

This code snippet demonstrates how to use PBKDF2 for securely deriving keys from passwords.

function pbkdf2($password, $salt, $iterations, $length, $algo = 'sha256') {
    $key = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
    return base64_encode($key);
}

// Usage example
$password = 'your-password';
$salt = bin2hex(random_bytes(16));
$iterations = 100000;
$key_length = 32;

$derived_key = pbkdf2($password, $salt, $iterations, $key_length);
echo "Derived Key: " . $derived_key . "\n";
Back