开发者

encrypting and decrypting information stored in cookies

I need to securely crypt and decrypt information about users (user_id and password) in cookies.

What is the best way to do this ? What encryption and decryption functions do I need ?

I'm using PHP and MySQL and exampl开发者_StackOverflowe will be participated ?


for example

Set encrypted cookie:
<?php

$time = time()+60*60*24*30*12; //store cookie for one year
setcookie('cookie_name', encryptCookie('cookie_value'),$time,'/');

?>

Get encrypted cookie value:

<?php

$cookie_value = decryptCookie($_COOKIE['cookie_name']);

?>

here is the function to encrypt decrypt cookie:

    <?php

function encryptCookie($value){
   if(!$value){return false;}
   $key = 'The Line Secret Key';
   $text = $value;
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
   return trim(base64_encode($crypttext)); //encode for cookie
}

function decryptCookie($value){
   if(!$value){return false;}
   $key = 'The Line Secret Key';
   $crypttext = base64_decode($value); //decode cookie
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
   return trim($decrypttext);
}

?>

You can read more about the mcrypt function here: php mcrypt function


Don't store passwords in a cookie. Never do this kind of things. If you want some way for you user to not have to enter its login and password to login, you can genrate some random token when he logs in (sha1(mt_rand()) for example) and store this value in the cookie and database.

Then when trying to identify a user, you just have to check if the value found in his cookie can be found in your database. Generate a new value everytime he logs in (using name + password or with this cookie).


There is no good way to "securely crypt and decrypt information about users in cookies" because storing that information in cookies is inherently insecure.

The recommended technique is to generate a random session identifier and use that as the only piece of information stored in cookies. This session id is then used on the server side to look up the user's actual account information (and any state regarding what they're doing) in a database or file so that you're only sending a small amount of otherwise meaningless data back and forth across the network with each request made by the user. If such a cookie is intercepted by The Bad Guys, it will only compromise the user's session (allowing the attacker to temporarily impersonate the user until the session is ended); the user's password will remain secure because it is not in the cookie and (presumably) is not ever displayed on any page of your application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜