PHP 8.5 crypt() Function With Example

In PHP 8.5, the crypt() function works exactly the same as it did in PHP 8.0 through 8.4. There are no new features or changes specific to PHP 8.5 for this function. It still performs one-way string hashing, but it is not recommended for hashing passwords in modern applications.

Here is a breakdown of how it works, along with a practical example.

How crypt() Works?

The behavior of crypt() depends entirely on the $salt parameter you provide. The salt determines which hashing algorithm is used (like DES, Blowfish, or SHA-256) .

Salt is Required: Since PHP 8.0.0, the $salt parameter is mandatory. If you don not provide one, it will cause an error .
No Decryption: Because it is a one-way hashing function, there is no way to "decrypt" the output back to the original string .
Verification: To check if a password is correct, you must hash the user is input using the exact same salt and compare the result to the stored hash .

Example: Hashing with Blowfish

Here is an example of how you might use crypt() with a Blowfish salt (prefixed with $2y$).

<?php
$password = "MySecretPassword123";
// A Blowfish salt starts with $2y$, followed by a cost parameter (04-31), and 22 characters
$salt = $2y$10$usesomesillystringforsalt$ ;

// Create the hash
$hash = crypt($password, $salt);
echo "Hashed: " . $hash . " ";

// To verify a user is input later, use the stored hash as the salt
$userInput = "MySecretPassword123";
if (hash_equals($hash, crypt($userInput, $hash))) {
   echo "Password is valid!";
} else {
   echo "Invalid password.";
}
?>

4 Views