Re-commit Ping's patch to the cgi and cgitb documentation, using the
[python/dscho.git] / Lib / hmac.py
blobcae08002e55dfaa909dd00cd3f695a459415f907
1 """HMAC (Keyed-Hashing for Message Authentication) Python module.
3 Implements the HMAC algorithm as described by RFC 2104.
4 """
6 import string
8 def _strxor(s1, s2):
9 """Utility method. XOR the two strings s1 and s2 (must have same length).
10 """
11 return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2))
13 # The size of the digests returned by HMAC depends on the underlying
14 # hashing module used.
15 digest_size = None
17 class HMAC:
18 """RFC2104 HMAC class.
20 This supports the API for Cryptographic Hash Functions (PEP 247).
21 """
23 def __init__(self, key, msg = None, digestmod = None):
24 """Create a new HMAC object.
26 key: key for the keyed hash object.
27 msg: Initial input for the hash, if provided.
28 digestmod: A module supporting PEP 247. Defaults to the md5 module.
29 """
30 if digestmod == None:
31 import md5
32 digestmod = md5
34 self.digestmod = digestmod
35 self.outer = digestmod.new()
36 self.inner = digestmod.new()
37 self.digest_size = digestmod.digest_size
39 blocksize = 64
40 ipad = "\x36" * blocksize
41 opad = "\x5C" * blocksize
43 if len(key) > blocksize:
44 key = digestmod.new(key).digest()
46 key = key + chr(0) * (blocksize - len(key))
47 self.outer.update(_strxor(key, opad))
48 self.inner.update(_strxor(key, ipad))
49 if (msg):
50 self.update(msg)
52 ## def clear(self):
53 ## raise NotImplementedError, "clear() method not available in HMAC."
55 def update(self, msg):
56 """Update this hashing object with the string msg.
57 """
58 self.inner.update(msg)
60 def copy(self):
61 """Return a separate copy of this hashing object.
63 An update to this copy won't affect the original object.
64 """
65 other = HMAC("")
66 other.digestmod = self.digestmod
67 other.inner = self.inner.copy()
68 other.outer = self.outer.copy()
69 return other
71 def digest(self):
72 """Return the hash value of this hashing object.
74 This returns a string containing 8-bit data. The object is
75 not altered in any way by this function; you can continue
76 updating the object after calling this function.
77 """
78 h = self.outer.copy()
79 h.update(self.inner.digest())
80 return h.digest()
82 def hexdigest(self):
83 """Like digest(), but returns a string of hexadecimal digits instead.
84 """
85 return "".join([string.zfill(hex(ord(x))[2:], 2)
86 for x in tuple(self.digest())])
88 def new(key, msg = None, digestmod = None):
89 """Create a new hashing object and return it.
91 key: The starting key for the hash.
92 msg: if available, will immediately be hashed into the object's starting
93 state.
95 You can now feed arbitrary strings into the object using its update()
96 method, and can ask for the hash value at any time by calling its digest()
97 method.
98 """
99 return HMAC(key, msg, digestmod)