1 """HMAC (Keyed-Hashing for Message Authentication) Python module.
3 Implements the HMAC algorithm as described by RFC 2104.
7 """Utility method. XOR the two strings s1 and s2 (must have same length).
9 return "".join(map(lambda x
, y
: chr(ord(x
) ^
ord(y
)), s1
, s2
))
11 # The size of the digests returned by HMAC depends on the underlying
12 # hashing module used.
15 # A unique object passed by HMAC.copy() to the HMAC constructor, in order
16 # that the latter return very quickly. HMAC("") in contrast is quite
18 _secret_backdoor_key
= []
21 """RFC2104 HMAC class.
23 This supports the API for Cryptographic Hash Functions (PEP 247).
26 def __init__(self
, key
, msg
= None, digestmod
= None):
27 """Create a new HMAC object.
29 key: key for the keyed hash object.
30 msg: Initial input for the hash, if provided.
31 digestmod: A module supporting PEP 247. *OR*
32 A hashlib constructor returning a new hash object.
33 Defaults to hashlib.md5.
36 if key
is _secret_backdoor_key
: # cheap
41 digestmod
= hashlib
.md5
43 if callable(digestmod
):
44 self
.digest_cons
= digestmod
46 self
.digest_cons
= lambda d
='': digestmod
.new(d
)
48 self
.outer
= self
.digest_cons()
49 self
.inner
= self
.digest_cons()
50 self
.digest_size
= self
.inner
.digest_size
53 ipad
= "\x36" * blocksize
54 opad
= "\x5C" * blocksize
56 if len(key
) > blocksize
:
57 key
= self
.digest_cons(key
).digest()
59 key
= key
+ chr(0) * (blocksize
- len(key
))
60 self
.outer
.update(_strxor(key
, opad
))
61 self
.inner
.update(_strxor(key
, ipad
))
66 ## raise NotImplementedError, "clear() method not available in HMAC."
68 def update(self
, msg
):
69 """Update this hashing object with the string msg.
71 self
.inner
.update(msg
)
74 """Return a separate copy of this hashing object.
76 An update to this copy won't affect the original object.
78 other
= HMAC(_secret_backdoor_key
)
79 other
.digest_cons
= self
.digest_cons
80 other
.digest_size
= self
.digest_size
81 other
.inner
= self
.inner
.copy()
82 other
.outer
= self
.outer
.copy()
86 """Return the hash value of this hashing object.
88 This returns a string containing 8-bit data. The object is
89 not altered in any way by this function; you can continue
90 updating the object after calling this function.
93 h
.update(self
.inner
.digest())
97 """Like digest(), but returns a string of hexadecimal digits instead.
99 return "".join([hex(ord(x
))[2:].zfill(2)
100 for x
in tuple(self
.digest())])
102 def new(key
, msg
= None, digestmod
= None):
103 """Create a new hashing object and return it.
105 key: The starting key for the hash.
106 msg: if available, will immediately be hashed into the object's starting
109 You can now feed arbitrary strings into the object using its update()
110 method, and can ask for the hash value at any time by calling its digest()
113 return HMAC(key
, msg
, digestmod
)