Encrypt a date / time and create a token

advertisements

so i have been working on a remember me function for my site.

It currently works, but i have been using basic data and not encrypting as i wanted to know exactly what was happening whilst learning.

I am using a cookie and then a db which stores the same data and then the check is made. A new cookie / db entry is made on logging in each time.

So currently this would be the cookie: (the row for the id is a userid, this cookie is set in the login process)

 date_default_timezone_set('Europe/London');
 $token = '1';
 $cookiedate = date('d-m-y h:i:s a', time());
 $cookie_val = $row['id'] . ':' . $token . ':' . $cookiedate;

 setcookie (
"cookie",
$cookie_val,
time() + (10 * 365 * 24 * 60 * 60),
'/'
 );

What would be my next step from here in terms of some encpytion? Also im not quite sure about the token, should it be a random hash of chars just used as an extra security method?

the website isnt going to be massive, and from logging into someones account you wont be able to cause any damage really as sensitive pages are password promt protected.


An improvement on what you have would be:

  1. Generate a random token of, say, 20 characters, e.g.:

    bin2hex(openssl_random_pseudo_bytes(10));
    
    
  2. Store that token together with the user identifier (and other relevant data) in your database.

  3. Write the token value inside a cookie.

This prevents a few issues:

  1. The token data is only known on the server side, the client only gets the key.

  2. A user can revoke 'remember me' tokens to prevent future unauthorized access.

  3. Tampering with the cookie value will result in an unknown token value, so access will be rejected.

Upon a successful login you would generate a new token.

Generally, to avoid data tampering, you can use hash_hmac() to hash a particular value using a secret key.