How to Use crypt() Function in PHP 8.2 With Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

Hello Friends Today, through this tutorial, I will tell you How to Use `crypt()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP, the `crypt()` function is used for one-way hashing of data, typically for securely storing passwords. It uses a cryptographic algorithm to hash the given data and can be used to generate hashed strings for password storage. Here’s how you can use `crypt()` function in PHP 8.2 with an example:

<?php

// Define the password to be hashed
$password = 'secret_password';

// Generate a salt for the hash
// Note: You can use the PASSWORD_DEFAULT constant instead of 'bcrypt' for automatic algorithm selection
$salt = '$2y$10$' . bin2hex(random_bytes(22));

// Hash the password using bcrypt algorithm and the generated salt
$hashedPassword = crypt($password, $salt);

// Output the hashed password
echo "Hashed Password: " . $hashedPassword . "\n";

// You can verify the password using password_verify() function
$enteredPassword = 'secret_password';
if (hash_equals($hashedPassword, crypt($enteredPassword, $hashedPassword))) {
echo "Password is correct.\n";
} else {
echo "Password is incorrect.\n";
}

?>

In this example:

1. We define a password (`$password`) that we want to hash.
2. We generate a salt using `random_bytes()` function, which provides a secure way to generate random bytes. We prepend the bcrypt algorithm identifier `$2y$10$` and convert the bytes to hexadecimal format.
3. We then use `crypt()` function with the password and the generated salt to obtain the hashed password (`$hashedPassword`).
4. Finally, we output the hashed password and demonstrate how to verify a password using `password_verify()` function.