hmac — Keyed-Hashing for Message Authentication

This module implements the HMAC algorithm as described by RFC 2104.[msg[digestmod]])
Return a new hmac object. If msg is present, the method call update(msg) is made. digestmod is the digest constructor or module for the HMAC object to use. It defaults to the hashlib.md5()constructor

When you are setting the cookies with "counter = 10", how would you prevent the user from changing its value in the dirty way?

The answer is to associate the value of counter with a hash value. See as follows:

"counter = 10, 1e48c4420b7073bc11916c6c1de226bb"

Another problem is that what if the user figured out your hash algorithm? This could be pretty easy since the frequently used ones are not many (sha1, md5, )

Oh well, you can blend the value of counter with a secret key. As you probably know that for a given hash algorithm H(x) = y, it is almost impossible to figure out x by only y. Therefore, if you donot let others know the secret key, you would be safe.

Do in this way:
H(x + secretkey) = y 

In python, you could actually use hmac package."secretkey", "10").hexdigest()

of course, you could also do it with just hashlib:
hashlib.md5("secretykey" + 10).hexdigest()

A little bit code here for reuse.


def hash_str (s):
  return, s).hexdigest()

def make_secure_val(s):
  return "%s|%s" % (s, hash_str(s))

def check_secure_val(h):
  val = h.split('|')[0]
  if h == make_secure_val(val):
      return val


Popular Posts