Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame^] | 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 | _openssl_md_meths = None |
| 12 | from _operator import _compare_digest as compare_digest |
| 13 | else: |
| 14 | _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names) |
| 15 | compare_digest = _hashopenssl.compare_digest |
| 16 | import hashlib as _hashlib |
| 17 | |
| 18 | trans_5C = bytes((x ^ 0x5C) for x in range(256)) |
| 19 | trans_36 = bytes((x ^ 0x36) for x in range(256)) |
| 20 | |
| 21 | # The size of the digests returned by HMAC depends on the underlying |
| 22 | # hashing module used. Use digest_size from the instance of HMAC instead. |
| 23 | digest_size = None |
| 24 | |
| 25 | |
| 26 | |
| 27 | class 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 | |
| 34 | __slots__ = ( |
| 35 | "_digest_cons", "_inner", "_outer", "block_size", "digest_size" |
| 36 | ) |
| 37 | |
| 38 | 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 | |
| 58 | if callable(digestmod): |
| 59 | self._digest_cons = digestmod |
| 60 | elif isinstance(digestmod, str): |
| 61 | self._digest_cons = lambda d=b'': _hashlib.new(digestmod, d) |
| 62 | else: |
| 63 | self._digest_cons = lambda d=b'': digestmod.new(d) |
| 64 | |
| 65 | self._outer = self._digest_cons() |
| 66 | self._inner = self._digest_cons() |
| 67 | self.digest_size = self._inner.digest_size |
| 68 | |
| 69 | if hasattr(self._inner, 'block_size'): |
| 70 | blocksize = self._inner.block_size |
| 71 | if blocksize < 16: |
| 72 | _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 | |
| 82 | # 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 | |
| 86 | if len(key) > blocksize: |
| 87 | key = self._digest_cons(key).digest() |
| 88 | |
| 89 | key = key.ljust(blocksize, b'\0') |
| 90 | self._outer.update(key.translate(trans_5C)) |
| 91 | self._inner.update(key.translate(trans_36)) |
| 92 | if msg is not None: |
| 93 | self.update(msg) |
| 94 | |
| 95 | @property |
| 96 | def name(self): |
| 97 | 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 |
| 110 | |
| 111 | def update(self, msg): |
| 112 | """Feed data from msg into this hashing object.""" |
| 113 | self._inner.update(msg) |
| 114 | |
| 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 | """ |
| 120 | # Call __new__ directly to avoid the expensive __init__. |
| 121 | other = self.__class__.__new__(self.__class__) |
| 122 | other._digest_cons = self._digest_cons |
| 123 | other.digest_size = self.digest_size |
| 124 | other._inner = self._inner.copy() |
| 125 | other._outer = self._outer.copy() |
| 126 | return other |
| 127 | |
| 128 | def _current(self): |
| 129 | """Return a hash object for the current state. |
| 130 | |
| 131 | To be used only internally with digest() and hexdigest(). |
| 132 | """ |
| 133 | h = self._outer.copy() |
| 134 | h.update(self._inner.digest()) |
| 135 | return h |
| 136 | |
| 137 | def digest(self): |
| 138 | """Return the hash value of this hashing object. |
| 139 | |
| 140 | This returns the hmac value as bytes. The object is |
| 141 | not altered in any way by this function; you can continue |
| 142 | updating the object after calling this function. |
| 143 | """ |
| 144 | h = self._current() |
| 145 | return h.digest() |
| 146 | |
| 147 | def hexdigest(self): |
| 148 | """Like digest(), but returns a string of hexadecimal digits instead. |
| 149 | """ |
| 150 | h = self._current() |
| 151 | return h.hexdigest() |
| 152 | |
| 153 | def new(key, msg=None, digestmod=''): |
| 154 | """Create a new hashing object and return it. |
| 155 | |
| 156 | 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. |
| 161 | |
| 162 | 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() |
| 167 | method, and can ask for the hash value at any time by calling its digest() |
| 168 | or hexdigest() methods. |
| 169 | """ |
| 170 | return HMAC(key, msg, digestmod) |
| 171 | |
| 172 | |
| 173 | def digest(key, msg, digest): |
| 174 | """Fast inline implementation of HMAC. |
| 175 | |
| 176 | key: bytes or buffer, The key for the keyed hash object. |
| 177 | msg: bytes or buffer, Input message. |
| 178 | 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. |
| 181 | """ |
| 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() |