iRule: Encrypting a cookie

The topic recently came up as to how to correctly encrypt and decrypt a HTTP cookie from within an iRule.

...is there a way to have a static key and not generate the key for each request and use this key to encrypt and decrypt.

unRuleY passed along his 2 cents as follows:

Use the RULE_INIT event to create the encryption key:

when RULE_INIT {
   set ::key [AES::key]
}

Then in the response event from the server, you first extract the un-encrypted cookie "MyCookie" (replace with whatever your cookie name is), remove it, encrypt and Base64 encode it, and then re-insert the encrypted value as the cookie "MyCookie".

when HTTP_RESPONSE {
   set decrypted [HTTP::cookie "MyCookie"]
   HTTP::cookie remove "MyCookie"
   set encrypted [b64encode [AES::encrypt $::key $decrypted]]
   HTTP::cookie insert name "MyCookie" value $encrypted
}

Now, on subsequent client requests you get the encrypted value of "MyCookie", remove that cookie, Base64 decode and decrypt it, and then re-insert the decrypted value.

when HTTP_REQUEST {
   set encrypted [HTTP::cookie "MyCookie"]
   HTTP::cookie remove "MyCookie"
   set decrypted [AES::decrypt $::key [b64decode $encrypted]]
   HTTP::cookie insert name "MyCookie" value $decrypted
}

Pretty simple huh?

One thing to keep in mind is that you might want to check for the existence of the cookie "MyCookie" in each of these events before performing the encoding/encryption/etc.

Check out the original thread here.

-Joe

 

[Listening to: Everybody Wake Up (Our Finest Hour Arrives) - Dave Band Matthews - Stand Up (04:17)]
Published Oct 19, 2005
Version 1.0

Was this article helpful?

1 Comment

  • Hi Joe, Can you Encrypt on one LTM and Decrypt on another both running same OS level, lets say 11.4.1 please?