Signed Cookie

As a cookie is stored in the client's computer it can be easily altered. The SignedCookie class, derived from the Cookie class, can be used to make sure the returned cookie was not altered. It creates cookies signed with a MD5 hash using the cookie's name, value and a string passed to it. When the cookie is returned a new hash is generated and compared to the cookie's stored hash.

If the cookie was altered its class will be the base Cookie class and not the SignedCookie class. Then testing the cookie class will show if the cookie was altered.

from mod_python import Cookie
import time

def index(req):

   # A secret non-empty string to sign the cookie
   secret = 'my_secret'

   # Pass the cookie class and the secret to get_cookies() 
   signed_cookies = Cookie.get_cookies(req, Cookie.SignedCookie, secret=secret)

   # Get the returned signed cookie
   returned_signed = signed_cookies.get('signed', None)
   
   # If the signed cookie exists 
   if returned_signed:
      # Check if the cookie was not altered
      if type(returned_signed) is not Cookie.SignedCookie:
         message = 'The cookie was altered'
      else:
         message = 'The cookie was not altered'
   else:
      message = 'This is your first visit'
      
   # Create a signed cookie
   send_signed = Cookie.SignedCookie('signed', 'this string is signed', secret)

   # The cookie will expire in 30 days.
   send_signed.expires = time.time() + 30 * 24 * 60 * 60
   
   # Add the cookie to the HTTP header.
   Cookie.add_cookie(req, send_signed)

   return """\
<html><body>
<p>%s</p>
<p><pre>%s</pre></p>
<p>%s</p>
</body></html>
""" % ('You have just received this cookie:', send_signed, message)