0
votes

So I store users password in database after hashed by password_hash() (php 5.5+). and then verify user when logging in using password_verify(). but now i want to also store password on users browser with cookies. i hash the same password using password_hash but this time the second part of hash is obviously different. (salt)

because of that, two hashes (the one in database and the one in cookie) are NOT equal. how do i verify them then???

2
"but now i want to also store password on users browser with cookies." - Just don't. Plus, I'd sure like to know which site that is, so that I won't register there.Funk Forty Niner
then how do i use cookies to log user in?Vahid Amiri
read about php's sessionsFederkun
I use them already, but they are not enough. they expire too soon.Vahid Amiri
Generate a random token, eg $token = md5(mt_rand()); store the token in the cookie, put the token and the user's IP in the database with a timestamp. When someone comes back with the cookie and the same IP within your chosen timeframe you can skip password-based login. Also, use SSL to avoid cookie hijacking.Sammitch

2 Answers

3
votes

DO NOT STORE THE PASSWORD ON THE CLIENT SIDE

What you're trying to do is recreate sessions. I'd suggest that you simply use a session.

If you can't for whatever reason, then generate a random string (use a library like random_compat).

$token = random_bytes(16);

Store the string in the database:

INSERT INTO user_to_token (user_id, token) VALUES (?, ?)

However, store the hash so that if your database leaks, an attacker won't know the original token and hence won't be able to steal the session.

$query->execute([$userId, hash('sha256', $token)]);

Then, set the cookie to the raw value, base64 encoded:

set_cookie("token", base64_encode($token));

Now, to validate, decode and then hash:

$token = hash('sha256', base64_decode($cookie));

Then look up the user id from the DB:

SELECT user_id FROM user_to_token WHERE token = ?

And you're done.

0
votes

store user credential on cookie is high risk.

If you store hashes password on database so you only need pass username and password then will hashes from other file and match it into your database.

ex. login.php post username and password

usercheck.php md5(password) and check it into database which already hashes password