Check out a similar module I wrote last year for mod_perl:
http://www.versatilia.com/downloads/Apache2/Cookie/Validated.pm
It's designed to store simple hashes.
I still haven't got around to putting it on CPAN but have been using it
happily for 18 months and it has a couple of features you might like to
borrow:
- a 'del' method to make cookie deletion easy
- strips path attribute quotes for older browser compatibility
cheers
John
Kurt George Gjerde wrote:
Hi,
Grateful for any feedback on the module podded below. Is the name ok
or should I perhaps change to CGI::Cookie::Fingerprint or something else?
Thanks,
-Kurt.
NAME
CGI::Cookie::Protected - Cookies with fingerprint
SYNOPSIS
use CGI qw(:standard);
use CGI::Cookie::Protected;
# Create a new protected cookie and send it
my $cookie = CGI::Cookie::Protected->new(
-name=>'ID', -value=>1234
);
$cookie->protect($privake_key);
print header( -cookie=>$cookie );
# Fetch existing cookie and unprotect it
my %cookies = CGI::Cookie::Protected->fetch();
my $id_cookie = $cookies{ID};
$id_cookie->unprotect($private_key);
$id = $id_cookie->value();
# Fetch existing cookie and validate it
my %cookies = CGI::Cookie::Protected->fetch();
my $id_cookie = $cookies{ID};
if ($id_cookie->validate($private_key)) {
print "Cookie OK";
} else {
die "Cookie not OK";
}
DESCRIPTION
CGI::Cookie::Protected is a subclass of CGI::Cookie. It provides the
ability of adding a fingerprint to the cookie, preventing the client
from altering the cookie's value(s).
NEW METHODS
protect($private_key)
Adds a fingerprint to the cookie. If the cookie's value is altered
after
calling protect() you will have to call protect() again.
unprotect($private_key, ...)
Removes the fingerprint from the cookie. This should be called before
retrieving the cookie's value(s). If the fingerprint does not
validate
against the $private_key, the cookie's value becomes undefined. On
success this method returns 1.
validate($private_key, ...)
If the cookie's fingerprint validates against the $private_key, this
method returns 1, otherwise it returns 0.
ABOUT THE PRIVATE KEY(S)
The unprotect() and validate() methods can take an list of private
keys
and will return success if any of the keys validate against the
cookie.
This might be useful in a key rotation scenario, where you can
validate
against the new key and the previous key.
The resulting cookie string (of name=mycookie and value=myvalue)
might
look like this:
mycooke=myvalue&ab34e32fbb12839adde21234dd824ca7; path=/
The current implementation uses MD5 to generate the fingerprint.