blob: 6f2ae2e110df54376e15b374761a69655a8bc449 [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
Guido van Rossuma19f80c2007-11-06 20:51:31 +00006import warnings as _warnings
7
Guido van Rossum3f429082007-07-10 13:35:52 +00008trans_5C = bytes((x ^ 0x5C) for x in range(256))
9trans_36 = bytes((x ^ 0x36) for x in range(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
Thomas Wouters902d6eb2007-01-09 23:18:33 +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:
Guido van Rossuma19f80c2007-11-06 20:51:31 +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 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +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 Rossum3f429082007-07-10 13:35:52 +000035
36 Note: key and msg must be bytes objects.
Guido van Rossum8ceef412001-09-11 15:54:00 +000037 """
Tim Peters934d31b2004-03-20 20:11:29 +000038
39 if key is _secret_backdoor_key: # cheap
40 return
41
Guido van Rossum39478e82007-08-27 17:23:59 +000042 assert isinstance(key, bytes), repr(key)
Guido van Rossum3f429082007-07-10 13:35:52 +000043
Raymond Hettinger7fdfc2d2002-05-31 17:49:10 +000044 if digestmod is None:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000045 import hashlib
46 digestmod = hashlib.md5
Guido van Rossum8ceef412001-09-11 15:54:00 +000047
Guido van Rossumd59da4b2007-05-22 18:11:13 +000048 if hasattr(digestmod, '__call__'):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000049 self.digest_cons = digestmod
50 else:
Guido van Rossum3f429082007-07-10 13:35:52 +000051 self.digest_cons = lambda d=b'': digestmod.new(d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000052
53 self.outer = self.digest_cons()
54 self.inner = self.digest_cons()
55 self.digest_size = self.inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000056
Guido van Rossuma19f80c2007-11-06 20:51:31 +000057 if hasattr(self.inner, 'block_size'):
58 blocksize = self.inner.block_size
59 if blocksize < 16:
60 # Very low blocksize, most likely a legacy value like
61 # Lib/sha.py and Lib/md5.py have.
62 _warnings.warn('block_size of %d seems too small; using our '
63 'default of %d.' % (blocksize, self.blocksize),
64 RuntimeWarning, 2)
65 blocksize = self.blocksize
66 else:
67 _warnings.warn('No block_size attribute on given digest object; '
68 'Assuming %d.' % (self.blocksize),
69 RuntimeWarning, 2)
70 blocksize = self.blocksize
71
Guido van Rossum8ceef412001-09-11 15:54:00 +000072 if len(key) > blocksize:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000073 key = self.digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000074
Guido van Rossum3f429082007-07-10 13:35:52 +000075 key = key + bytes(blocksize - len(key))
Thomas Wouters902d6eb2007-01-09 23:18:33 +000076 self.outer.update(key.translate(trans_5C))
77 self.inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000078 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000079 self.update(msg)
80
81## def clear(self):
82## raise NotImplementedError, "clear() method not available in HMAC."
83
84 def update(self, msg):
85 """Update this hashing object with the string msg.
86 """
Guido van Rossum39478e82007-08-27 17:23:59 +000087 assert isinstance(msg, bytes), repr(msg)
Guido van Rossum8ceef412001-09-11 15:54:00 +000088 self.inner.update(msg)
89
90 def copy(self):
91 """Return a separate copy of this hashing object.
92
93 An update to this copy won't affect the original object.
94 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000095 other = self.__class__(_secret_backdoor_key)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000096 other.digest_cons = self.digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +000097 other.digest_size = self.digest_size
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000098 other.inner = self.inner.copy()
99 other.outer = self.outer.copy()
100 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +0000101
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000102 def _current(self):
103 """Return a hash object for the current state.
104
105 To be used only internally with digest() and hexdigest().
106 """
107 h = self.outer.copy()
108 h.update(self.inner.digest())
109 return h
110
Guido van Rossum8ceef412001-09-11 15:54:00 +0000111 def digest(self):
112 """Return the hash value of this hashing object.
113
114 This returns a string containing 8-bit data. The object is
115 not altered in any way by this function; you can continue
116 updating the object after calling this function.
117 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000118 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000119 return h.digest()
120
121 def hexdigest(self):
122 """Like digest(), but returns a string of hexadecimal digits instead.
123 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000124 h = self._current()
125 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000126
127def new(key, msg = None, digestmod = None):
128 """Create a new hashing object and return it.
129
130 key: The starting key for the hash.
131 msg: if available, will immediately be hashed into the object's starting
Tim Petersb64bec32001-09-18 02:26:39 +0000132 state.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000133
134 You can now feed arbitrary strings into the object using its update()
135 method, and can ask for the hash value at any time by calling its digest()
136 method.
137 """
138 return HMAC(key, msg, digestmod)