In PHP, the crypt() function is often used to encrypt passwords. It can support a variety of hashing algorithms, such as standard DES, MD5, SHA-256, and SHA-512, and its behavior depends on the incoming "salt value". The salt value not only increases the complexity of the password, but also determines the method and result of hashing. Once the salt value is incorrect, even if the user enters the correct original password, it cannot pass the verification.
The basic syntax of crypt() is as follows:
$hashed_password = crypt('Original password', 'Salt value');
During verification, the password entered by the user is usually re-encrypted using the previously stored hash as the salt value:
if (crypt($input_password, $stored_hash) === $stored_hash) {
// Correct password
}
Note that the key point here is: the hash itself is passed in as part of the salt value to ensure that the use of completely consistent algorithms and salt values.
There are two main functions of salt value:
Prevent Rainbow Table Attack: Even if two users use the same password, their hash results will be different after adding different salt values.
Tell crypt() which encryption algorithm and its parameters to use.
For example, the following salt value specifies the use of the SHA-512 algorithm and iterate 5000 times:
$salt = '$6$rounds=5000$usesomesillystringforsalt$';
If you try to re-encrypt the same password with different salt values (even if only one is different), the results will be completely different. This is exactly the characteristic of the hash function: a slight change will lead to a huge difference in output results .
Imagine a scenario:
$original_hash = crypt('mySecretPassword', '$6$rounds=5000$m66.net$');
When the user logs in again, the program verifies as follows:
if (crypt('mySecretPassword', '$6$rounds=5000$wrongdomain.com$') === $original_hash) {
echo 'Correct password';
} else {
echo 'Error password';
}
Although the user entered the correct password, crypt() will generate a completely different hash due to different salt values, causing verification to fail.
It's like you use the same recipe (password), but using different ingredients (salt), the dish (hash) that ends up making is naturally different.
Wrong practice:
Generate a new random salt value every time you verify it.
The original hash value is not used as the salt value during verification.
Manually truncate or modify stored hash values.
Correct way to do it:
Using high-level APIs such as password_hash() and password_verify() , they automatically manage salt values and algorithms.
If you use crypt() , the original hash is always used as the salt value when validating.