Tuesday, November 19, 2024
Google search engine
HomeLanguagesPHP openssl_pbkdf2() Function

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:

  • $password: The password that the key should be derived from.
  • $salt: A random salt value that should be used to help make the derived key unique.
  • $key_length: The length (in bytes) of the derived key.
  • $iterations: The number of iterations to use when deriving the key. More iterations will make the algorithm slower but also more secure.
  • $digest_algo: The digest algorithm to use when deriving the key. This should be one of the supported OpenSSL digest algorithms, such as “sha256” or “sha512”.

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




<?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




<?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

RELATED ARTICLES

Most Popular

Recent Comments