Encrypting cookies

Author Topic: Encrypting cookies  (Read 1197 times)

Offline chinmay.sahooTopic starter

  • Trade Count: (0)
  • Full Member
  • ***
  • Thank You 2
  • Posts: 159
  • Karma: 0
    • Hot Shaper
Encrypting cookies
« on: 12-26-2015, 03:05:42 »
Cookies your site sends to a visitor’s browser contain information about that visitor. When the browser sends the cookie back, your site uses the information it contains to generate a new page. Don’t trust the network—sound familiar? A cookie could be modified or forged by a malicious user, perhaps fooling your site somehow. This extremely simple program will serve as an example:

$visits = $_COOKIE[‘visits’] + 1;
setcookie(“visits”, $visits);
<H1>You have been here <?php echo $visits ?> times</H1>

But with some help from mcrypt and a few friends, we can make this impossible:

$key = base64_decode(“NCiUmfiRByg=”);
if (IsSet($_COOKIE[‘visits’])) {
$encrypted = base64_decode($_COOKIE[‘visits’]);
$visits = mcrypt_cbc(MCRYPT_DES, $key, $encrypted,
$visits = $visits + 1;
$encrypted = mcrypt_cbc(MCRYPT_DES, $key, $visits,
setcookie(“visits”, base64_encode($encrypted));

mcrypt deals with strings full of binary data, so we can’t easily type them or send them to browsers without modification. In this case, we have chosen to use the PHP base64 functions to turn them into well-behaved strings. Before writing this program, we invented a DES key with the following code:

$key_size = mcrypt_get_key_size(MCRYPT_DES);
$key = mcrypt_create_iv($key_size, MCRYPT_DEV_RANDOM);
echo base64_encode($key);

We copied and pasted the resulting key (in base 64 encoding) into our cookie program’s first line. We store the number of visits in the cookie named visits, encrypted and in base 64 encoding. So if the visits variable is set, we first base64_decode it, then decrypt it. We then increment the counter, encrypt it, base64_encode it, and store it in a new cookie. The visitor sees cookie values such as IQ109yQCEgw%3D, which are not editable.

The program is not completely secure! The cookie value just given will always correspond to visit number 7. A crаcker wishing to make your site believe he had visited only seven times could simply substitut this value for the visits cookie. If you know it would not benefit a visitor to return to a prior cookie (in this case, if the visitor wants a large visit count), however, this method is adequate: There is no way to easily invent a cookie for a state that has not been seen yet.