Menu

Michael Gracie

I like my cookies with encryption on top

Quick and dirty mcrypt usage

I don’t know where I discovered the original idea, but in messing around with a PHP app I found the need to encrypt session cookies. Here’s how it was done, with the mcrypt library:

//encrypt session cookie
function encryptUserCookie($value)
{
if(!$value) {
return false;
}
$key = SESSION_SALT;
$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
}

Decoding the cookie was much the same…

//decrypt session cookie
function decryptUserCookie($value)
{
if(!$value) {
return false;
}
$key = SESSION_SALT;
$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);
}

SESSION_SALT was of course something I called from a variables file.

These snippets were used in an online directory system, where I didn’t want attendees inspecting the cookies for the purpose of setting up multiple listings under the same login.

Simple stuff, but hope it is useful to someone.

Comments

uh, what?

Alex: Silly man – I use this encryption stuff to fool the fish! You mean you’ve never heard of a fly called the Diffie-Hellman? There’s even an encryption algorithm called Twofish, derived from another called Blowfish.

It’s a small, small world.

Can I have some of that stuff your smoking? You nut. Cookies are for eating.

It’s a drug-free environment over here. But, on occasion, Guinness is my acting supervisor.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.