``If possible, cookies should contain information that allows the system to verify that the person using them is authorized to do so. A popular scheme is to include the following information in cookies:

1.the session ID or authorization information
2.the time and date the cookie was issued
3.an expiration time
4.the IP address of the browser the cookie was issued to
5.a message authenticity check (MAC) code

By incorporating an expiration date and time into the cookie, system designers can limit the potential damage that a hijacked cookie can do. If the cookie is intercepted, it can only be used for a finite time before it becomes invalid. The idea of including the browser's IP address into the cookie is that the cookie will only be accepted if the stored IP address matches the IP address of the browser submitting it. This makes it difficult for an interloper to hijack the cookie, because it is hard (although not impossible) to spoof an IP address.

The MAC code is there to ensure that none of the fields of the cookie have been tampered with. There are many ways to compute a MAC, most of which rely on one-way hash algorithms such as MD5 or SHA to create a unique fingerprint for the data within the cookie. Here's a simple but relatively secure technique that uses MD5:

This algorithm first performs a string concatenation of all the data fields in the cookie, then adds to it a secret string known only to the Web server. The whole is then passed to the MD5 function to create a unique hash. This value is again concatenated with the secret key, and the whole thing is rehashed. (The second round of MD5 hashing is necessary in order to avoid an attack in which additional data is appended to the end of the cookie and a new hash recalculated by the attacker.)

This hash value is now incorporated into the cookie data. Later, when the cookie is returned to the server, the software should verify that the cookie hasn't expired and is being returned by the proper IP address. Then it should regenerate the MAC from the data fields, and compare that to the MAC in the cookie. If they match, there's little chance that the cookie has been tampered with.'' -- Lincoln Stein.

In fact, this is the technique used by LibWeb to handle user/session authentication via cookies. LibWeb::Admin and LibWeb::Session use LibWeb::Digest::generate_MAC() to generate MACs. LibWeb::Digest::generate_MAC() uses Digest::HMAC and uses either Digest::MD5 or Digest::SHA1 as the digest algorithm.