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.
16 """RFC2104 HMAC class.
18 This supports the API for Cryptographic Hash Functions (PEP 247).
21 def __init__(self
, key
, msg
= None, digestmod
= None):
22 """Create a new HMAC object.
24 key: key for the keyed hash object.
25 msg: Initial input for the hash, if provided.
26 digestmod: A module supporting PEP 247. Defaults to the md5 module.
32 self
.digestmod
= digestmod
33 self
.outer
= digestmod
.new()
34 self
.inner
= digestmod
.new()
35 self
.digest_size
= digestmod
.digest_size
38 ipad
= "\x36" * blocksize
39 opad
= "\x5C" * blocksize
41 if len(key
) > blocksize
:
42 key
= digestmod
.new(key
).digest()
44 key
= key
+ chr(0) * (blocksize
- len(key
))
45 self
.outer
.update(_strxor(key
, opad
))
46 self
.inner
.update(_strxor(key
, ipad
))
51 ## raise NotImplementedError, "clear() method not available in HMAC."
53 def update(self
, msg
):
54 """Update this hashing object with the string msg.
56 self
.inner
.update(msg
)
59 """Return a separate copy of this hashing object.
61 An update to this copy won't affect the original object.
64 other
.digestmod
= self
.digestmod
65 other
.inner
= self
.inner
.copy()
66 other
.outer
= self
.outer
.copy()
70 """Return the hash value of this hashing object.
72 This returns a string containing 8-bit data. The object is
73 not altered in any way by this function; you can continue
74 updating the object after calling this function.
77 h
.update(self
.inner
.digest())
81 """Like digest(), but returns a string of hexadecimal digits instead.
83 return "".join([hex(ord(x
))[2:].zfill(2)
84 for x
in tuple(self
.digest())])
86 def new(key
, msg
= None, digestmod
= None):
87 """Create a new hashing object and return it.
89 key: The starting key for the hash.
90 msg: if available, will immediately be hashed into the object's starting
93 You can now feed arbitrary strings into the object using its update()
94 method, and can ask for the hash value at any time by calling its digest()
97 return HMAC(key
, msg
, digestmod
)