1 """HMAC (Keyed-Hashing for Message Authentication) Python module.
3 Implements the HMAC algorithm as described by RFC 2104.
5 (This file is modified from the standard library version to do faster
10 """Utility method. XOR the two strings s1 and s2 (must have same length).
12 return "".join(map(lambda x
, y
: chr(ord(x
) ^
ord(y
)), s1
, s2
))
14 # The size of the digests returned by HMAC depends on the underlying
15 # hashing module used.
19 """RFC2104 HMAC class.
21 This supports the API for Cryptographic Hash Functions (PEP 247).
24 def __init__(self
, key
, msg
= None, digestmod
= None):
25 """Create a new HMAC object.
27 key: key for the keyed hash object.
28 msg: Initial input for the hash, if provided.
29 digestmod: A module supporting PEP 247. Defaults to the md5 module.
35 if key
== None: #TREVNEW - for faster copying
38 self
.digestmod
= digestmod
39 self
.outer
= digestmod
.new()
40 self
.inner
= digestmod
.new()
41 self
.digest_size
= digestmod
.digest_size
44 ipad
= "\x36" * blocksize
45 opad
= "\x5C" * blocksize
47 if len(key
) > blocksize
:
48 key
= digestmod
.new(key
).digest()
50 key
= key
+ chr(0) * (blocksize
- len(key
))
51 self
.outer
.update(_strxor(key
, opad
))
52 self
.inner
.update(_strxor(key
, ipad
))
57 ## raise NotImplementedError, "clear() method not available in HMAC."
59 def update(self
, msg
):
60 """Update this hashing object with the string msg.
62 self
.inner
.update(msg
)
65 """Return a separate copy of this hashing object.
67 An update to this copy won't affect the original object.
69 other
= HMAC(None) #TREVNEW - for faster copying
70 other
.digest_size
= self
.digest_size
#TREVNEW
71 other
.digestmod
= self
.digestmod
72 other
.inner
= self
.inner
.copy()
73 other
.outer
= self
.outer
.copy()
77 """Return the hash value of this hashing object.
79 This returns a string containing 8-bit data. The object is
80 not altered in any way by this function; you can continue
81 updating the object after calling this function.
84 h
.update(self
.inner
.digest())
88 """Like digest(), but returns a string of hexadecimal digits instead.
90 return "".join([hex(ord(x
))[2:].zfill(2)
91 for x
in tuple(self
.digest())])
93 def new(key
, msg
= None, digestmod
= None):
94 """Create a new hashing object and return it.
96 key: The starting key for the hash.
97 msg: if available, will immediately be hashed into the object's starting
100 You can now feed arbitrary strings into the object using its update()
101 method, and can ask for the hash value at any time by calling its digest()
104 return HMAC(key
, msg
, digestmod
)