How to Use the mhash_keygen_s2k() Function in PHP

PHP has an inbuilt mhash_keygen_s2k() function, used for creating a key according to the given hash with the help of a user-provided password.

It is the salted S2K algorithm, indicated in the OpenPGP document (RFC 2440). It is especially handy for computing checksums, message digests, and so on.

Note that for checking the key, the salt should also be known.

Watch a course Learn object oriented PHP

The syntax of the mhash_keygen_s2k() function is demonstrated below:

string mhash_keygen_s2k(int $hash, string $password, string $salt, int $bytes)

From the syntax, you can see that this function accepts four parameters. The description of those parameters are given below:

  • $Hash: keeps the hash ID. In other words, it holds one of the mhash_name constants.
  • $Password: keeps the password of the user.
  • $Salt: It is a random data used as an additional input for a one-way function, which hashes a password, data or passphrase. Its length is fixed (8 bytes).
  • $Bytes: TIt defines the key by the length of the key, in bytes.

After defining the parameters of the function, let’s see what value it can return. On success, it will return the created key as a string, and FALSE, otherwise.

For a better perception, let’s illustrate an example:

<?php

$inputString = "p4ssw0rd";
$salt = "agejkhgeuka";

$bytes = "8";

// bin2hex is used to convert binary
// to hex string

print_r(bin2hex(mhash_keygen_s2k(MHASH_MD5, $inputString, $salt, $bytes)));

?>
e2dfb845290aae21