Debian Codegraph @

lib-python/3/hmac.py

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