Encrypting cookies

Started by chinmay.sahoo, 12-26-2015, 03:05:42

Previous topic - Next topic

chinmay.sahooTopic starter

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:


Quote<?php
$visits = $_COOKIE['visits'] + 1;
setcookie("visits", $visits);
?>
<HTML><HEAD></HEAD>
<BODY>
<H1>You have been here <?php echo $visits ?> times</H1>
</BODY>
</HTML>

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


Quote<?php
$key = base64_decode("NCiUmfiRByg=");
if (IsSet($_COOKIE['visits'])) {
$encrypted = base64_decode($_COOKIE['visits']);
$visits = mcrypt_cbc(MCRYPT_DES, $key, $encrypted,
MCRYPT_DECRYPT); }
$visits = $visits + 1;
$encrypted = mcrypt_cbc(MCRYPT_DES, $key, $visits,
MCRYPT_ENCRYPT);
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:

Quote<?php
$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.