mrkirby153
mrkirby153

Reputation: 85

Cookie Encryption/Decryption

I have a website where the user can choose for the website to "remember me" (AKA set a cookie) and per advice on this website, I switched my password encryption in the database to php's password_hash() function. Now, I can't just compare any old hash to one another so I use php's password_verify(). Password verify requires plaintext and a password hash.

How can I store the user's password in a browser cookie without it being plaintext?

Upvotes: 2

Views: 2813

Answers (1)

jszobody
jszobody

Reputation: 28911

Storing the password in the cookie itself is a really bad idea, don't do that.

At a very high level, I would:

  1. Generate a token (with something like md5) that consists of a couple unique (yet consistent) attributes for this user
  2. Store both the user ID and this token in the cookie (separated by some known delimiter)
  3. When the user visits your site, you can split out the ID and the token
  4. Use the ID to fetch the user record from the database, create a new token from the DB record, and compare with the cookie token

So let's walk through this briefly. Say $hash is the password hash stored in the database, and you also have a $userId and $username variables for this user.

I would generate a cookie that looks something like this:

$token = md5($userId . $username . $hash);
$cookie = $userID . "|" . $token; // 1|XXXXXXXX

Now when a user visits your site and you retrieve this cookie:

$parts = explode("|",$cookie);
$userId = $parts[0];
$token = $parts[1];

Now you know who the user is claiming to be, but you need to verify.

Fetch the user record from the database, and then regenerate the token and compare.

// Assuming you just ran a SELECT query, and fetched the result into `$row`
$dbToken = md5($row['userId'] . $row['username'] . $row['hash']);
if($token == $dbToken) {
    // The user is who he claims to be! Log them in
} else {
    // The cookie token didn't match our re-generated token, don't trust this cookie
}

Make sense? You will likely need to modify this a bit for your situation. Hopefully this helps get you going in a good direction at least.

Upvotes: 3

Related Questions