For the full details on HMAC, check out the RFC-2104
Python provide some basic cryptographic services such as HMAC. The use of HMAC in python is pretty straightforward. Here is an example:
import hmac hmac_engine = hmac.new('This Is My Super Secret KEY') f = open('/etc/services', 'rb') try: for block in f: hmac_engine.update(block) finally: f.close() print hmac_engine.hexdigest()
When run, the code reads its source file and computes an HMAC signature for it:
$ python hmactest.py
01c274a3eaca826fcd1b645e074bf99b
You can use HMAC in web applications to check the integrity of URLs or cookies.
Your application need to send a cookies with some information for example the login. Of course you don't want some to temper with this cookie and change the user name. One solution is to sign the cookie with an HMAC digest.
Here is a code snippet example:
import hmac import cherrypy user_login = 'mallory' hmac_engine = hmac.new('This Is My Very-Super-Secret KEY!') hmac_engine.update(user) digest = hmac_engine.hexdigest() cherrypy.response.simple_cookie['user'] = user cherrypy.response.simple_cookie['digest'] = digest