blob: 538810630cf3ad5a471082e74f0a1e7d990b10c1 [file] [log] [blame]
Guido van Rossum8ceef412001-09-11 15:54:00 +00001"""HMAC (Keyed-Hashing for Message Authentication) Python module.
2
3Implements the HMAC algorithm as described by RFC 2104.
4"""
5
Gregory P. Smithe1ac4f12007-11-06 00:19:03 +00006import warnings as _warnings
7
Andrew M. Kuchling8fe2d202006-12-19 14:13:05 +00008trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)])
9trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)])
Tim Petersb64bec32001-09-18 02:26:39 +000010
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000011# The size of the digests returned by HMAC depends on the underlying
Andrew M. Kuchlinga7ebb332006-12-27 03:25:31 +000012# hashing module used. Use digest_size from the instance of HMAC instead.
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000013digest_size = None
14
Tim Peters934d31b2004-03-20 20:11:29 +000015# 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
17# expensive.
18_secret_backdoor_key = []
19
Guido van Rossum8ceef412001-09-11 15:54:00 +000020class HMAC:
Gregory P. Smithe1ac4f12007-11-06 00:19:03 +000021 """RFC 2104 HMAC class. Also complies with RFC 4231.
Guido van Rossum8ceef412001-09-11 15:54:00 +000022
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000023 This supports the API for Cryptographic Hash Functions (PEP 247).
Tim Petersb64bec32001-09-18 02:26:39 +000024 """
Andrew M. Kuchlinga7ebb332006-12-27 03:25:31 +000025 blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
Guido van Rossum8ceef412001-09-11 15:54:00 +000026
27 def __init__(self, key, msg = None, digestmod = None):
28 """Create a new HMAC object.
29
30 key: key for the keyed hash object.
31 msg: Initial input for the hash, if provided.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000032 digestmod: A module supporting PEP 247. *OR*
33 A hashlib constructor returning a new hash object.
34 Defaults to hashlib.md5.
Guido van Rossum8ceef412001-09-11 15:54:00 +000035 """
Tim Peters934d31b2004-03-20 20:11:29 +000036
37 if key is _secret_backdoor_key: # cheap
38 return
39
Raymond Hettinger7fdfc2d2002-05-31 17:49:10 +000040 if digestmod is None:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000041 import hashlib
42 digestmod = hashlib.md5
Guido van Rossum8ceef412001-09-11 15:54:00 +000043
Benjamin Peterson4348a252008-08-19 19:07:38 +000044 if hasattr(digestmod, '__call__'):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000045 self.digest_cons = digestmod
46 else:
47 self.digest_cons = lambda d='': digestmod.new(d)
48
49 self.outer = self.digest_cons()
50 self.inner = self.digest_cons()
51 self.digest_size = self.inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000052
Gregory P. Smithe1ac4f12007-11-06 00:19:03 +000053 if hasattr(self.inner, 'block_size'):
54 blocksize = self.inner.block_size
55 if blocksize < 16:
56 # Very low blocksize, most likely a legacy value like
57 # Lib/sha.py and Lib/md5.py have.
58 _warnings.warn('block_size of %d seems too small; using our '
59 'default of %d.' % (blocksize, self.blocksize),
60 RuntimeWarning, 2)
61 blocksize = self.blocksize
62 else:
63 _warnings.warn('No block_size attribute on given digest object; '
64 'Assuming %d.' % (self.blocksize),
65 RuntimeWarning, 2)
66 blocksize = self.blocksize
67
Guido van Rossum8ceef412001-09-11 15:54:00 +000068 if len(key) > blocksize:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000069 key = self.digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000070
71 key = key + chr(0) * (blocksize - len(key))
Andrew M. Kuchling8fe2d202006-12-19 14:13:05 +000072 self.outer.update(key.translate(trans_5C))
73 self.inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000074 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000075 self.update(msg)
76
77## def clear(self):
78## raise NotImplementedError, "clear() method not available in HMAC."
79
80 def update(self, msg):
81 """Update this hashing object with the string msg.
82 """
83 self.inner.update(msg)
84
85 def copy(self):
86 """Return a separate copy of this hashing object.
87
88 An update to this copy won't affect the original object.
89 """
Andrew M. Kuchlinga7ebb332006-12-27 03:25:31 +000090 other = self.__class__(_secret_backdoor_key)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000091 other.digest_cons = self.digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +000092 other.digest_size = self.digest_size
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000093 other.inner = self.inner.copy()
94 other.outer = self.outer.copy()
95 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +000096
Andrew M. Kuchling71662322006-12-27 03:31:24 +000097 def _current(self):
98 """Return a hash object for the current state.
99
100 To be used only internally with digest() and hexdigest().
101 """
102 h = self.outer.copy()
103 h.update(self.inner.digest())
104 return h
105
Guido van Rossum8ceef412001-09-11 15:54:00 +0000106 def digest(self):
107 """Return the hash value of this hashing object.
108
109 This returns a string containing 8-bit data. The object is
110 not altered in any way by this function; you can continue
111 updating the object after calling this function.
112 """
Andrew M. Kuchling71662322006-12-27 03:31:24 +0000113 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000114 return h.digest()
115
116 def hexdigest(self):
117 """Like digest(), but returns a string of hexadecimal digits instead.
118 """
Andrew M. Kuchling71662322006-12-27 03:31:24 +0000119 h = self._current()
120 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000121
122def new(key, msg = None, digestmod = None):
123 """Create a new hashing object and return it.
124
125 key: The starting key for the hash.
126 msg: if available, will immediately be hashed into the object's starting
Tim Petersb64bec32001-09-18 02:26:39 +0000127 state.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000128
129 You can now feed arbitrary strings into the object using its update()
130 method, and can ask for the hash value at any time by calling its digest()
131 method.
132 """
133 return HMAC(key, msg, digestmod)