Safer Cookies

Safer Cookies

Setting Cookie with Hash
  1. $server_side_salt = 'random string';
  2.  
  3. $cookie_hash = sha1 ($user_id . $server_side_salt);
  4. setcookie ('MYSITE', $user_id . ':' . $cookie_hash);
HTTP Headers
  1. Cookie: MYSITE=23:5ae4cea15a227e781846203737cba11c
Validating
  1. list ($cookie, $cookie_hash) = explode (':', $_COOKIE['MYSITE']);
  2. if (sha1 ($cookie . $server_side_salt) !== $cookie_hash) {
  3.     // Invalid cookie.
  4.     exit; // or error
  5. }
Regarding SHA1 and its integrity
http://www.schneier.com/blog/archives/2005/02/cryptanalysis_o.html
http://en.wikipedia.org/wiki/SHA_hash_functions