Michael Gracie

Technology, Finance, and Time Spent On or In the Water

  • About
  • Blog
  • Contact

I like my cookies with encryption on top

February 11, 2009 4 Comments

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.

Filed Under: Office Tagged With: cookies, encryption, mcrypt, PHP

« 18 Merchants of Mayhem
Ode to Baja California Sur, and ‘lethal weapons’ »

Comments

  1. Fat Guy Alex says

    February 12, 2009 at 3:37 pm

    uh, what?

    Reply
    • Michael Gracie says

      February 12, 2009 at 3:58 pm

      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.

      Reply
  2. Fat Guy Alex says

    February 13, 2009 at 3:14 pm

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

    Reply
    • Michael Gracie says

      February 14, 2009 at 9:32 am

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

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Top
  • Notes
  • Office
  • Outdoors
  • Spamroll
  • Thoughtmarket

© 2018 · Michael Gracie - Some Rights Reserved