Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

php - Hashing password using crypt does not work on the login it displays incorrect pass

I have a register page that allow user to insert password so i need to hash it to become more secure in the database this work fine

but when it come to the login the entered password do not match the register one how to fix this problemmm

this is my first time to use hash so it did not work as i want

This is the register code for hash:

   //ADD MD5 hash to the password 
function cryptPass($input, $rounds = 9)
{
    $salt = "";
    $saltChars = array_merge(range('A','Z'), range('a','z'), range('0','9'));
    for($i = 0; $i<22; $i++)
    {
        $salt  .=$saltChars[array_rand($saltChars)]; 
    }
    return crypt($input, sprintf('$2y$%02d$test$', $rounds) . $salt);
}
$hashedpass = cryptPass($pass1);      
echo $hashedpass;

the hashing password = $2y$09$test$5I9x8HWhA4UHi5TMu.AxfdWvZadDCE.LD6HCkrK3ZsqJeN7e

This is the login code for hash:

   function cryptPass($input, $rounds = 9)
{
    $salt = "";
    $saltChars = array_merge(range('A','Z'), range('a','z'), range('0','9'));
    for($i = 0; $i<22; $i++)
    {
        $salt  .=$saltChars[array_rand($saltChars)]; 
    }
    return crypt($input, sprintf('$2y$%02d$test$', $rounds) . $salt);
}
$hashedpass = cryptPass($pass);   
echo $hashedpass;

the hashing password = $2y$09$test$4ZGgCiXdKzgQvuzwu.AxfdWvZadDCE.LD6HCkrK3ZsqJeN7e

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Upon registration you create a unique salt. That salt is now part of the hash. If you look closely, you'll see it's embedded in the first part of the hash. To check the password, use the previous hashed password's salt, so you're using the same salt again.

$correctPasswordHash = getPasswordFromDatabase($_POST['username']);
$hash = crypt($_POST['password'], $correctPasswordHash);

if ($correctPasswordHash === $hash) ...

To make this easier and more foolproof, use the password_compat library, which wraps this in an easy to use API, which will also be integrated into a future version of PHP. Inspect its source code for the correct usage of crypt, since there are some pitfalls you need to take care of. The password_compat library is also using a custom binary comparison instead of a simple === to thwart timing attacks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...