简体   繁体   中英

How to Store Passwords in Databases and Cookies (PHP/MySQL)

Having read this article and many others out there on how to store passwords in databases and cookies, I'm wondering now I should do it... 存储在数据库和饼干密码,我现在不知道我应该办呢?

What I've come up so far (after reading around a bit) is taking the clear-text user password, padding it with salt till it fills up 512 bits (64 bytes => 64 chars, since the page is non-unicode), and then doing

$pwhash = hash('sha512', $saltedpw);
for ($i=0; $i<1000; $i++)
      $pwhash = hash('sha512', $pwhash);

Then I would store (UserName, HashedPw, Salt) in the database, but what do I do about the cookie (to identify users that want to stay loogend-on after the session has expired)?

First, calling hash 1000 times does not help anything, once is enough.

For remembering the user login in cookie you have two options:

  1. As has been said, you can generate a random token and store it in the database along with the user information. When a user with no session cookie enters the site, you check if there is a cookie with the token and do a DB lookup. If you found a user with such a token, log them in. You might want to do some additional checks, like whether the current IP is the same as the IP when they first logged in.
  2. You can store the user ID in the cookie, but then you have to sign the data using a secret key to make sure the user can't just modify it. HMAC -SHA-1 is a good way to do that. The advantage is that you don't have to store any additional data in the database. You only have to verify the signature and do a lookup on the user ID. The disadvantage is that you have to make sure the signature code is secure (HMAC-SHA-1 with a longer secret key should do that).

In the database store only password hashcode, and cookie should contain session id, often called SID . In another table store all SID (with userID ) and thats all. But don't forget that PHP has build in very simple and usefull session api, use it better :)

You do not have to store the password of the user in the cookie. You can generate a long random string (similar to a sessionid) that you store in the database and in the cookie. You can change that string everytime the session expires and the user comes back. When a user accesses the site you can check the cookie value against the database and see who the user is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM