0
votes

I used the crypt function with the blowfish algorithm(one-way hashing)and i saved my hashed string in db there no problem.

$hash=$2y$13$1wVxPniVSiKTjBmDxUhykeec08.v0UsujEkmhjHECIUgEiSuJFag 
 $actual=crypt("kumar",$hash);

These is how they used to validate the password is to took our current password and the hashed password which we can stored into the db.

On during these they compared with follwing code

 public function compareString($expected, $actual)
    {
        $expected .= "\0";
        $actual .= "\0";
        $expectedLength = StringHelper::byteLength($expected);
        $actualLength = StringHelper::byteLength($actual);
        $diff = $expectedLength - $actualLength;
        for ($i = 0; $i < $actualLength; $i++) {
            $diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
        }
        return $diff === 0;
    }

It return only 0 or 1 when the password is correct or not.

But My question is on these how they matched the current password with the hashed password which we save in db.Because the current password only contains the string and the hashed password contains the cost,salt,hashed password.

Is that they validate the password only or only the salt or how they do it?

I want the flow of validation of passwords of In-built crypt algorithm.

1

1 Answers

1
votes

For a starter I would recommend to use the functions password_hash() and password_verify() to check passwords, internally they use the crypt() function.

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

But you seem to be interested in how the crypt() is able to verify the password with its hash. When you create the first hash, you pass in the crypt-parameters as the second argument, it contains the algorithm, the cost factor and the salt (the format is explained in this answer).

For verification you can calculate the hash again, but you need the exact same crypt-parameters, then you get a comparable hash. The first hash starts with the crypt-parameters, and the crypt() function extracts those parameters from the first hash, when you pass it as the second argument.

$2y$13$1wVxPniVSiKTjBmDxUhyke

In your example this part of the hash contains the crypt-parameters, it is the start of your hash and it is used by crypt() again to verify the password.