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