blob: 8b4f920db954ca8e5e5844c6b91b52ea56d44d81 [file] [log] [blame]
Haibo Huangd8830302020-03-03 10:09:46 -08001"""HMAC (Keyed-Hashing for Message Authentication) module.
2
3Implements the HMAC algorithm as described by RFC 2104.
4"""
5
6import warnings as _warnings
Haibo Huangd8830302020-03-03 10:09:46 -08007try:
8 import _hashlib as _hashopenssl
9except ImportError:
10 _hashopenssl = None
Yi Kong71199322022-08-30 15:53:45 +080011 _functype = None
Haibo Huang5eba2b42021-01-22 11:22:02 -080012 from _operator import _compare_digest as compare_digest
Haibo Huangd8830302020-03-03 10:09:46 -080013else:
Haibo Huang5eba2b42021-01-22 11:22:02 -080014 compare_digest = _hashopenssl.compare_digest
Yi Kong71199322022-08-30 15:53:45 +080015 _functype = type(_hashopenssl.openssl_sha256) # builtin type
16
Haibo Huangd8830302020-03-03 10:09:46 -080017import hashlib as _hashlib
18
19trans_5C = bytes((x ^ 0x5C) for x in range(256))
20trans_36 = bytes((x ^ 0x36) for x in range(256))
21
22# The size of the digests returned by HMAC depends on the underlying
23# hashing module used. Use digest_size from the instance of HMAC instead.
24digest_size = None
25
26
Haibo Huangd8830302020-03-03 10:09:46 -080027class HMAC:
28 """RFC 2104 HMAC class. Also complies with RFC 4231.
29
30 This supports the API for Cryptographic Hash Functions (PEP 247).
31 """
32 blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
33
Haibo Huang5eba2b42021-01-22 11:22:02 -080034 __slots__ = (
Yi Kong71199322022-08-30 15:53:45 +080035 "_hmac", "_inner", "_outer", "block_size", "digest_size"
Haibo Huang5eba2b42021-01-22 11:22:02 -080036 )
37
Haibo Huangd8830302020-03-03 10:09:46 -080038 def __init__(self, key, msg=None, digestmod=''):
39 """Create a new HMAC object.
40
41 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.
46
47 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.
50 """
51
52 if not isinstance(key, (bytes, bytearray)):
53 raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
54
55 if not digestmod:
56 raise TypeError("Missing required parameter 'digestmod'.")
57
Yi Kong71199322022-08-30 15:53:45 +080058 if _hashopenssl and isinstance(digestmod, (str, _functype)):
59 try:
60 self._init_hmac(key, msg, digestmod)
61 except _hashopenssl.UnsupportedDigestmodError:
62 self._init_old(key, msg, digestmod)
Haibo Huangd8830302020-03-03 10:09:46 -080063 else:
Yi Kong71199322022-08-30 15:53:45 +080064 self._init_old(key, msg, digestmod)
Haibo Huangd8830302020-03-03 10:09:46 -080065
Yi Kong71199322022-08-30 15:53:45 +080066 def _init_hmac(self, key, msg, digestmod):
67 self._hmac = _hashopenssl.hmac_new(key, msg, digestmod=digestmod)
68 self.digest_size = self._hmac.digest_size
69 self.block_size = self._hmac.block_size
70
71 def _init_old(self, key, msg, digestmod):
72 if callable(digestmod):
73 digest_cons = digestmod
74 elif isinstance(digestmod, str):
75 digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
76 else:
77 digest_cons = lambda d=b'': digestmod.new(d)
78
79 self._hmac = None
80 self._outer = digest_cons()
81 self._inner = digest_cons()
Haibo Huang5eba2b42021-01-22 11:22:02 -080082 self.digest_size = self._inner.digest_size
Haibo Huangd8830302020-03-03 10:09:46 -080083
Haibo Huang5eba2b42021-01-22 11:22:02 -080084 if hasattr(self._inner, 'block_size'):
85 blocksize = self._inner.block_size
Haibo Huangd8830302020-03-03 10:09:46 -080086 if blocksize < 16:
87 _warnings.warn('block_size of %d seems too small; using our '
88 'default of %d.' % (blocksize, self.blocksize),
89 RuntimeWarning, 2)
90 blocksize = self.blocksize
91 else:
92 _warnings.warn('No block_size attribute on given digest object; '
93 'Assuming %d.' % (self.blocksize),
94 RuntimeWarning, 2)
95 blocksize = self.blocksize
96
Yi Kong71199322022-08-30 15:53:45 +080097 if len(key) > blocksize:
98 key = digest_cons(key).digest()
99
Haibo Huangd8830302020-03-03 10:09:46 -0800100 # self.blocksize is the default blocksize. self.block_size is
101 # effective block size as well as the public API attribute.
102 self.block_size = blocksize
103
Haibo Huangd8830302020-03-03 10:09:46 -0800104 key = key.ljust(blocksize, b'\0')
Haibo Huang5eba2b42021-01-22 11:22:02 -0800105 self._outer.update(key.translate(trans_5C))
106 self._inner.update(key.translate(trans_36))
Haibo Huangd8830302020-03-03 10:09:46 -0800107 if msg is not None:
108 self.update(msg)
109
110 @property
111 def name(self):
Yi Kong71199322022-08-30 15:53:45 +0800112 if self._hmac:
113 return self._hmac.name
114 else:
115 return f"hmac-{self._inner.name}"
Haibo Huangd8830302020-03-03 10:09:46 -0800116
117 def update(self, msg):
118 """Feed data from msg into this hashing object."""
Yi Kong71199322022-08-30 15:53:45 +0800119 inst = self._hmac or self._inner
120 inst.update(msg)
Haibo Huangd8830302020-03-03 10:09:46 -0800121
122 def copy(self):
123 """Return a separate copy of this hashing object.
124
125 An update to this copy won't affect the original object.
126 """
127 # Call __new__ directly to avoid the expensive __init__.
128 other = self.__class__.__new__(self.__class__)
Haibo Huangd8830302020-03-03 10:09:46 -0800129 other.digest_size = self.digest_size
Yi Kong71199322022-08-30 15:53:45 +0800130 if self._hmac:
131 other._hmac = self._hmac.copy()
132 other._inner = other._outer = None
133 else:
134 other._hmac = None
135 other._inner = self._inner.copy()
136 other._outer = self._outer.copy()
Haibo Huangd8830302020-03-03 10:09:46 -0800137 return other
138
139 def _current(self):
140 """Return a hash object for the current state.
141
142 To be used only internally with digest() and hexdigest().
143 """
Yi Kong71199322022-08-30 15:53:45 +0800144 if self._hmac:
145 return self._hmac
146 else:
147 h = self._outer.copy()
148 h.update(self._inner.digest())
149 return h
Haibo Huangd8830302020-03-03 10:09:46 -0800150
151 def digest(self):
152 """Return the hash value of this hashing object.
153
154 This returns the hmac value as bytes. The object is
155 not altered in any way by this function; you can continue
156 updating the object after calling this function.
157 """
158 h = self._current()
159 return h.digest()
160
161 def hexdigest(self):
162 """Like digest(), but returns a string of hexadecimal digits instead.
163 """
164 h = self._current()
165 return h.hexdigest()
166
167def new(key, msg=None, digestmod=''):
168 """Create a new hashing object and return it.
169
170 key: bytes or buffer, The starting key for the hash.
171 msg: bytes or buffer, Initial input for the hash, or None.
172 digestmod: A hash name suitable for hashlib.new(). *OR*
173 A hashlib constructor returning a new hash object. *OR*
174 A module supporting PEP 247.
175
176 Required as of 3.8, despite its position after the optional
177 msg argument. Passing it as a keyword argument is
178 recommended, though not required for legacy API reasons.
179
180 You can now feed arbitrary bytes into the object using its update()
181 method, and can ask for the hash value at any time by calling its digest()
182 or hexdigest() methods.
183 """
184 return HMAC(key, msg, digestmod)
185
186
187def digest(key, msg, digest):
188 """Fast inline implementation of HMAC.
189
190 key: bytes or buffer, The key for the keyed hash object.
191 msg: bytes or buffer, Input message.
192 digest: A hash name suitable for hashlib.new() for best performance. *OR*
193 A hashlib constructor returning a new hash object. *OR*
194 A module supporting PEP 247.
195 """
Yi Kong71199322022-08-30 15:53:45 +0800196 if _hashopenssl is not None and isinstance(digest, (str, _functype)):
197 try:
198 return _hashopenssl.hmac_digest(key, msg, digest)
199 except _hashopenssl.UnsupportedDigestmodError:
200 pass
Haibo Huangd8830302020-03-03 10:09:46 -0800201
202 if callable(digest):
203 digest_cons = digest
204 elif isinstance(digest, str):
205 digest_cons = lambda d=b'': _hashlib.new(digest, d)
206 else:
207 digest_cons = lambda d=b'': digest.new(d)
208
209 inner = digest_cons()
210 outer = digest_cons()
211 blocksize = getattr(inner, 'block_size', 64)
212 if len(key) > blocksize:
213 key = digest_cons(key).digest()
214 key = key + b'\x00' * (blocksize - len(key))
215 inner.update(key.translate(trans_36))
216 outer.update(key.translate(trans_5C))
217 inner.update(msg)
218 outer.update(inner.digest())
219 return outer.digest()