blob: 180bc378b52d6214ccde61d53adb9a05ba311113 [file] [log] [blame]
Gregory P. Smithf33c57d52019-10-17 20:30:42 -07001"""HMAC (Keyed-Hashing for Message Authentication) module.
Guido van Rossum8ceef412001-09-11 15:54:00 +00002
3Implements the HMAC algorithm as described by RFC 2104.
4"""
5
Guido van Rossuma19f80c2007-11-06 20:51:31 +00006import warnings as _warnings
Christian Heimes2f050c72018-01-27 09:53:43 +01007try:
8 import _hashlib as _hashopenssl
9except ImportError:
10 _hashopenssl = None
11 _openssl_md_meths = None
Christian Heimesdb5aed92020-05-27 21:50:06 +020012 from _operator import _compare_digest as compare_digest
Christian Heimes2f050c72018-01-27 09:53:43 +010013else:
14 _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names)
Christian Heimesdb5aed92020-05-27 21:50:06 +020015 compare_digest = _hashopenssl.compare_digest
Christian Heimes634919a2013-11-20 17:23:06 +010016import hashlib as _hashlib
Guido van Rossuma19f80c2007-11-06 20:51:31 +000017
Guido van Rossum3f429082007-07-10 13:35:52 +000018trans_5C = bytes((x ^ 0x5C) for x in range(256))
19trans_36 = bytes((x ^ 0x36) for x in range(256))
Tim Petersb64bec32001-09-18 02:26:39 +000020
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000021# The size of the digests returned by HMAC depends on the underlying
Thomas Wouters902d6eb2007-01-09 23:18:33 +000022# hashing module used. Use digest_size from the instance of HMAC instead.
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000023digest_size = None
24
Tim Peters934d31b2004-03-20 20:11:29 +000025
Charles-François Natali7feb9f42012-05-13 19:53:07 +020026
Guido van Rossum8ceef412001-09-11 15:54:00 +000027class HMAC:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000028 """RFC 2104 HMAC class. Also complies with RFC 4231.
Guido van Rossum8ceef412001-09-11 15:54:00 +000029
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000030 This supports the API for Cryptographic Hash Functions (PEP 247).
Tim Petersb64bec32001-09-18 02:26:39 +000031 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000032 blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
Guido van Rossum8ceef412001-09-11 15:54:00 +000033
Christian Heimes837f9e42020-05-17 01:05:40 +020034 __slots__ = (
35 "_digest_cons", "_inner", "_outer", "block_size", "digest_size"
36 )
37
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070038 def __init__(self, key, msg=None, digestmod=''):
Guido van Rossum8ceef412001-09-11 15:54:00 +000039 """Create a new HMAC object.
40
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070041 key: bytes or buffer, key for the keyed hash object.
42 msg: bytes or buffer, Initial input for the hash or None.
43 digestmod: A hash name suitable for hashlib.new(). *OR*
44 A hashlib constructor returning a new hash object. *OR*
45 A module supporting PEP 247.
Guido van Rossum3f429082007-07-10 13:35:52 +000046
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070047 Required as of 3.8, despite its position after the optional
48 msg argument. Passing it as a keyword argument is
49 recommended, though not required for legacy API reasons.
Guido van Rossum8ceef412001-09-11 15:54:00 +000050 """
Tim Peters934d31b2004-03-20 20:11:29 +000051
Christian Heimes04926ae2013-07-01 13:08:42 +020052 if not isinstance(key, (bytes, bytearray)):
53 raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
Guido van Rossum3f429082007-07-10 13:35:52 +000054
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070055 if not digestmod:
56 raise TypeError("Missing required parameter 'digestmod'.")
Guido van Rossum8ceef412001-09-11 15:54:00 +000057
Florent Xicluna5d1155c2011-10-28 14:45:05 +020058 if callable(digestmod):
Christian Heimes837f9e42020-05-17 01:05:40 +020059 self._digest_cons = digestmod
Christian Heimes634919a2013-11-20 17:23:06 +010060 elif isinstance(digestmod, str):
Christian Heimes837f9e42020-05-17 01:05:40 +020061 self._digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000062 else:
Christian Heimes837f9e42020-05-17 01:05:40 +020063 self._digest_cons = lambda d=b'': digestmod.new(d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000064
Christian Heimes837f9e42020-05-17 01:05:40 +020065 self._outer = self._digest_cons()
66 self._inner = self._digest_cons()
67 self.digest_size = self._inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000068
Christian Heimes837f9e42020-05-17 01:05:40 +020069 if hasattr(self._inner, 'block_size'):
70 blocksize = self._inner.block_size
Guido van Rossuma19f80c2007-11-06 20:51:31 +000071 if blocksize < 16:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000072 _warnings.warn('block_size of %d seems too small; using our '
73 'default of %d.' % (blocksize, self.blocksize),
74 RuntimeWarning, 2)
75 blocksize = self.blocksize
76 else:
77 _warnings.warn('No block_size attribute on given digest object; '
78 'Assuming %d.' % (self.blocksize),
79 RuntimeWarning, 2)
80 blocksize = self.blocksize
81
Christian Heimesc4ab1102013-11-20 17:35:06 +010082 # self.blocksize is the default blocksize. self.block_size is
83 # effective block size as well as the public API attribute.
84 self.block_size = blocksize
85
Guido van Rossum8ceef412001-09-11 15:54:00 +000086 if len(key) > blocksize:
Christian Heimes837f9e42020-05-17 01:05:40 +020087 key = self._digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000088
Serhiy Storchaka5f1a5182016-09-11 14:41:02 +030089 key = key.ljust(blocksize, b'\0')
Christian Heimes837f9e42020-05-17 01:05:40 +020090 self._outer.update(key.translate(trans_5C))
91 self._inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000092 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000093 self.update(msg)
94
Christian Heimesc4ab1102013-11-20 17:35:06 +010095 @property
96 def name(self):
Christian Heimes837f9e42020-05-17 01:05:40 +020097 return "hmac-" + self._inner.name
98
99 @property
100 def digest_cons(self):
101 return self._digest_cons
102
103 @property
104 def inner(self):
105 return self._inner
106
107 @property
108 def outer(self):
109 return self._outer
Christian Heimesc4ab1102013-11-20 17:35:06 +0100110
Guido van Rossum8ceef412001-09-11 15:54:00 +0000111 def update(self, msg):
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700112 """Feed data from msg into this hashing object."""
Christian Heimes837f9e42020-05-17 01:05:40 +0200113 self._inner.update(msg)
Guido van Rossum8ceef412001-09-11 15:54:00 +0000114
115 def copy(self):
116 """Return a separate copy of this hashing object.
117
118 An update to this copy won't affect the original object.
119 """
Benjamin Peterson0cc74442010-08-21 02:45:15 +0000120 # Call __new__ directly to avoid the expensive __init__.
121 other = self.__class__.__new__(self.__class__)
Christian Heimes837f9e42020-05-17 01:05:40 +0200122 other._digest_cons = self._digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +0000123 other.digest_size = self.digest_size
Christian Heimes837f9e42020-05-17 01:05:40 +0200124 other._inner = self._inner.copy()
125 other._outer = self._outer.copy()
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +0000126 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +0000127
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000128 def _current(self):
129 """Return a hash object for the current state.
130
131 To be used only internally with digest() and hexdigest().
132 """
Christian Heimes837f9e42020-05-17 01:05:40 +0200133 h = self._outer.copy()
134 h.update(self._inner.digest())
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000135 return h
136
Guido van Rossum8ceef412001-09-11 15:54:00 +0000137 def digest(self):
138 """Return the hash value of this hashing object.
139
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700140 This returns the hmac value as bytes. The object is
Guido van Rossum8ceef412001-09-11 15:54:00 +0000141 not altered in any way by this function; you can continue
142 updating the object after calling this function.
143 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000144 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000145 return h.digest()
146
147 def hexdigest(self):
148 """Like digest(), but returns a string of hexadecimal digits instead.
149 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000150 h = self._current()
151 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000152
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700153def new(key, msg=None, digestmod=''):
Guido van Rossum8ceef412001-09-11 15:54:00 +0000154 """Create a new hashing object and return it.
155
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700156 key: bytes or buffer, The starting key for the hash.
157 msg: bytes or buffer, Initial input for the hash, or None.
158 digestmod: A hash name suitable for hashlib.new(). *OR*
159 A hashlib constructor returning a new hash object. *OR*
160 A module supporting PEP 247.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000161
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700162 Required as of 3.8, despite its position after the optional
163 msg argument. Passing it as a keyword argument is
164 recommended, though not required for legacy API reasons.
165
166 You can now feed arbitrary bytes into the object using its update()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000167 method, and can ask for the hash value at any time by calling its digest()
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700168 or hexdigest() methods.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000169 """
170 return HMAC(key, msg, digestmod)
Christian Heimes2f050c72018-01-27 09:53:43 +0100171
172
173def digest(key, msg, digest):
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700174 """Fast inline implementation of HMAC.
Christian Heimes2f050c72018-01-27 09:53:43 +0100175
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700176 key: bytes or buffer, The key for the keyed hash object.
177 msg: bytes or buffer, Input message.
Christian Heimes2f050c72018-01-27 09:53:43 +0100178 digest: A hash name suitable for hashlib.new() for best performance. *OR*
179 A hashlib constructor returning a new hash object. *OR*
180 A module supporting PEP 247.
Christian Heimes2f050c72018-01-27 09:53:43 +0100181 """
182 if (_hashopenssl is not None and
183 isinstance(digest, str) and digest in _openssl_md_meths):
184 return _hashopenssl.hmac_digest(key, msg, digest)
185
186 if callable(digest):
187 digest_cons = digest
188 elif isinstance(digest, str):
189 digest_cons = lambda d=b'': _hashlib.new(digest, d)
190 else:
191 digest_cons = lambda d=b'': digest.new(d)
192
193 inner = digest_cons()
194 outer = digest_cons()
195 blocksize = getattr(inner, 'block_size', 64)
196 if len(key) > blocksize:
197 key = digest_cons(key).digest()
198 key = key + b'\x00' * (blocksize - len(key))
199 inner.update(key.translate(trans_36))
200 outer.update(key.translate(trans_5C))
201 inner.update(msg)
202 outer.update(inner.digest())
203 return outer.digest()