RFC 2104 HMAC class. Also complies with RFC 4231. This supports the API for Cryptographic Hash Functions (PEP 247).
| 40 | |
| 41 | |
| 42 | class HMAC: |
| 43 | """RFC 2104 HMAC class. Also complies with RFC 4231. |
| 44 | |
| 45 | This supports the API for Cryptographic Hash Functions (PEP 247). |
| 46 | """ |
| 47 | |
| 48 | # Note: self.blocksize is the default blocksize; self.block_size |
| 49 | # is effective block size as well as the public API attribute. |
| 50 | blocksize = 64 # 512-bit HMAC; can be changed in subclasses. |
| 51 | |
| 52 | __slots__ = ( |
| 53 | "_hmac", "_inner", "_outer", "block_size", "digest_size" |
| 54 | ) |
| 55 | |
| 56 | def __init__(self, key, msg=None, digestmod=''): |
| 57 | """Create a new HMAC object. |
| 58 | |
| 59 | key: bytes or buffer, key for the keyed hash object. |
| 60 | msg: bytes or buffer, Initial input for the hash or None. |
| 61 | digestmod: A hash name suitable for hashlib.new(). *OR* |
| 62 | A hashlib constructor returning a new hash object. *OR* |
| 63 | A module supporting PEP 247. |
| 64 | |
| 65 | Required as of 3.8, despite its position after the optional |
| 66 | msg argument. Passing it as a keyword argument is |
| 67 | recommended, though not required for legacy API reasons. |
| 68 | """ |
| 69 | |
| 70 | if not isinstance(key, (bytes, bytearray)): |
| 71 | raise TypeError(f"key: expected bytes or bytearray, " |
| 72 | f"but got {type(key).__name__!r}") |
| 73 | |
| 74 | if not digestmod: |
| 75 | raise TypeError("Missing required argument 'digestmod'.") |
| 76 | |
| 77 | self.__init(key, msg, digestmod) |
| 78 | |
| 79 | def __init(self, key, msg, digestmod): |
| 80 | if _hashopenssl and isinstance(digestmod, (str, _functype)): |
| 81 | try: |
| 82 | self._init_openssl_hmac(key, msg, digestmod) |
| 83 | return |
| 84 | except _hashopenssl.UnsupportedDigestmodError: # pragma: no cover |
| 85 | pass |
| 86 | if _hmac and isinstance(digestmod, str): |
| 87 | try: |
| 88 | self._init_builtin_hmac(key, msg, digestmod) |
| 89 | return |
| 90 | except _hmac.UnknownHashError: # pragma: no cover |
| 91 | pass |
| 92 | self._init_old(key, msg, digestmod) |
| 93 | |
| 94 | def _init_openssl_hmac(self, key, msg, digestmod): |
| 95 | self._hmac = _hashopenssl.hmac_new(key, msg, digestmod=digestmod) |
| 96 | self._inner = self._outer = None # because the slots are defined |
| 97 | self.digest_size = self._hmac.digest_size |
| 98 | self.block_size = self._hmac.block_size |
| 99 |