Skip to content
Advertisement

crypt password storage and retrival php

I am trying to set up a secure login & register system using crypt() as I have read that that is php’s stored function for bcrypt

I am registering a user but taking their password and and then crypting it.

$hashed_password = crypt($mypassword);

I then store $hashed_password in the db

then when the user logs in I am trying to match the password to whats stored.

I found this function on php.net but cant get it to work

$password is the stored crypted password and $mypassword is the users input

if ($password == crypt($mypassword, $password)) {
    echo "Success! Valid password";
}

I understand that crypt generates a unique hash each time its called so I dont understand how the function can work.

Am I completeley missing the point as I read that crypt() is a one function and decrypt does not exist?

any help greatly appreciated in not only showing the error of my ways but also in completing this secure login

Advertisement

Answer

You’re using second parameter in your crypt() call, so it’s treated as salt. To compare properly, you can use:

if ($password == crypt($mypassword)) 
{
    echo "Success! Valid password";
}

But PHP provides native functionality for hashing routines – it is introduced if 5.5 version and called password hashing.

For PHP versions below 5.5 down to 5.3.7, there is a backported compatibility function that does the same: https://github.com/ircmaxell/password_compat Just include it and use it.

But note that you have to read the hashed password from the database and then compare it with PHP. You cannot query the database with a newly created password hash to find the user.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement