Open In App

PHP openssl_pbkdf2() Function

The openssl_pbkdf2() function is an inbuilt function in PHP that implements the Password-Based Key Derivation Function 2 (PBKDF2) algorithm provided by the OpenSSL library. The algorithm is designed to be slow and computationally intensive, making it resistant to brute-force attacks.

Syntax:



openssl_pbkdf2( 
    string $password, 
    string $salt, 
    int $key_length, 
    int $iterations, 
    string $digest_algo = "sha1" )
: string|false

Parameters: This function accepts five parameters that are described below:

Return Value: The return value of openssl_pbkdf2() is a binary string containing the derived key. If failure, it will return “false”.



Example 1: The following example demonstrates the openssl_pbkdf2() function.




<?php
$password = "this@ismypassword55839459144595";
  
// Saved hash from a previous run
$savedHash = "MjY4YjRkZDc1YzAzNzYzZGMwZDEzYjI3NmVlM2ZkNTE=";
  
$decodedHash = base64_decode($savedHash);
  
if (openssl_pbkdf2($password, $decodedHash, 32, 10000, "sha256") ===
    $decodedHash) {
    echo "Password is valid.";
} else {
    echo "Password is invalid.";
}
?>

Output
Password is invalid.

Example 2: The following example demonstrates the openssl_pbkdf2() function.




<?php
  
$userID = 'user123';
$deviceID = 'device456';
  
$secretKey = openssl_random_pseudo_bytes(32);
$salt = $userID . $deviceID;
  
$iterations = 50000;
$keyLength = 64;
  
$secureToken
      openssl_pbkdf2($secretKey
                   $salt,
                   $keyLength,
                   $iterations
                   'sha512');
  
// Display the secure token
echo "Secure Token: " . base64_encode($secureToken) . "\n";
?>

Output:

Secure Token: 
LWL+RuQr+TmOysJt8CBrKu5yC8vk2f9aMBH9y1xK82Nz4dDd88dd+8QqssBgoMDnGD9D5kTcmAlldzz7hUStjw==

Reference: https://www.php.net/manual/en/function.openssl-pbkdf2.php


Article Tags :