blob: 8b4f920db954ca8e5e5844c6b91b52ea56d44d81 [file] [log] [blame]
Gregory P. Smithf33c57d52019-10-17 20:30:42 -07001"""HMAC (Keyed-Hashing for Message Authentication) module.
Guido van Rossum8ceef412001-09-11 15:54:00 +00002
3Implements the HMAC algorithm as described by RFC 2104.
4"""
5
Guido van Rossuma19f80c2007-11-06 20:51:31 +00006import warnings as _warnings
Christian Heimes2f050c72018-01-27 09:53:43 +01007try:
8 import _hashlib as _hashopenssl
9except ImportError:
10 _hashopenssl = None
Christian Heimes933dfd72021-03-27 14:55:03 +010011 _functype = None
Christian Heimesdb5aed92020-05-27 21:50:06 +020012 from _operator import _compare_digest as compare_digest
Christian Heimes2f050c72018-01-27 09:53:43 +010013else:
Christian Heimesdb5aed92020-05-27 21:50:06 +020014 compare_digest = _hashopenssl.compare_digest
Christian Heimes933dfd72021-03-27 14:55:03 +010015 _functype = type(_hashopenssl.openssl_sha256) # builtin type
16
Christian Heimes634919a2013-11-20 17:23:06 +010017import hashlib as _hashlib
Guido van Rossuma19f80c2007-11-06 20:51:31 +000018
Guido van Rossum3f429082007-07-10 13:35:52 +000019trans_5C = bytes((x ^ 0x5C) for x in range(256))
20trans_36 = bytes((x ^ 0x36) for x in range(256))
Tim Petersb64bec32001-09-18 02:26:39 +000021
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000022# The size of the digests returned by HMAC depends on the underlying
Thomas Wouters902d6eb2007-01-09 23:18:33 +000023# hashing module used. Use digest_size from the instance of HMAC instead.
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000024digest_size = None
25
Tim Peters934d31b2004-03-20 20:11:29 +000026
Guido van Rossum8ceef412001-09-11 15:54:00 +000027class HMAC:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000028 """RFC 2104 HMAC class. Also complies with RFC 4231.
Guido van Rossum8ceef412001-09-11 15:54:00 +000029
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000030 This supports the API for Cryptographic Hash Functions (PEP 247).
Tim Petersb64bec32001-09-18 02:26:39 +000031 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000032 blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
Guido van Rossum8ceef412001-09-11 15:54:00 +000033
Christian Heimes837f9e42020-05-17 01:05:40 +020034 __slots__ = (
Christian Heimes933dfd72021-03-27 14:55:03 +010035 "_hmac", "_inner", "_outer", "block_size", "digest_size"
Christian Heimes837f9e42020-05-17 01:05:40 +020036 )
37
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070038 def __init__(self, key, msg=None, digestmod=''):
Guido van Rossum8ceef412001-09-11 15:54:00 +000039 """Create a new HMAC object.
40
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070041 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.
Guido van Rossum3f429082007-07-10 13:35:52 +000046
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070047 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.
Guido van Rossum8ceef412001-09-11 15:54:00 +000050 """
Tim Peters934d31b2004-03-20 20:11:29 +000051
Christian Heimes04926ae2013-07-01 13:08:42 +020052 if not isinstance(key, (bytes, bytearray)):
53 raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
Guido van Rossum3f429082007-07-10 13:35:52 +000054
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070055 if not digestmod:
56 raise TypeError("Missing required parameter 'digestmod'.")
Guido van Rossum8ceef412001-09-11 15:54:00 +000057
Christian Heimes933dfd72021-03-27 14:55:03 +010058 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)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000063 else:
Christian Heimes933dfd72021-03-27 14:55:03 +010064 self._init_old(key, msg, digestmod)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000065
Christian Heimes933dfd72021-03-27 14:55:03 +010066 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()
Christian Heimes837f9e42020-05-17 01:05:40 +020082 self.digest_size = self._inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000083
Christian Heimes837f9e42020-05-17 01:05:40 +020084 if hasattr(self._inner, 'block_size'):
85 blocksize = self._inner.block_size
Guido van Rossuma19f80c2007-11-06 20:51:31 +000086 if blocksize < 16:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000087 _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
Christian Heimes933dfd72021-03-27 14:55:03 +010097 if len(key) > blocksize:
98 key = digest_cons(key).digest()
99
Christian Heimesc4ab1102013-11-20 17:35:06 +0100100 # 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
Serhiy Storchaka5f1a5182016-09-11 14:41:02 +0300104 key = key.ljust(blocksize, b'\0')
Christian Heimes837f9e42020-05-17 01:05:40 +0200105 self._outer.update(key.translate(trans_5C))
106 self._inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +0000107 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +0000108 self.update(msg)
109
Christian Heimesc4ab1102013-11-20 17:35:06 +0100110 @property
111 def name(self):
Christian Heimes933dfd72021-03-27 14:55:03 +0100112 if self._hmac:
113 return self._hmac.name
114 else:
115 return f"hmac-{self._inner.name}"
Christian Heimesc4ab1102013-11-20 17:35:06 +0100116
Guido van Rossum8ceef412001-09-11 15:54:00 +0000117 def update(self, msg):
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700118 """Feed data from msg into this hashing object."""
Christian Heimes933dfd72021-03-27 14:55:03 +0100119 inst = self._hmac or self._inner
120 inst.update(msg)
Guido van Rossum8ceef412001-09-11 15:54:00 +0000121
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 """
Benjamin Peterson0cc74442010-08-21 02:45:15 +0000127 # Call __new__ directly to avoid the expensive __init__.
128 other = self.__class__.__new__(self.__class__)
Tim Peters934d31b2004-03-20 20:11:29 +0000129 other.digest_size = self.digest_size
Christian Heimes933dfd72021-03-27 14:55:03 +0100130 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()
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +0000137 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +0000138
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000139 def _current(self):
140 """Return a hash object for the current state.
141
142 To be used only internally with digest() and hexdigest().
143 """
Christian Heimes933dfd72021-03-27 14:55:03 +0100144 if self._hmac:
145 return self._hmac
146 else:
147 h = self._outer.copy()
148 h.update(self._inner.digest())
149 return h
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000150
Guido van Rossum8ceef412001-09-11 15:54:00 +0000151 def digest(self):
152 """Return the hash value of this hashing object.
153
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700154 This returns the hmac value as bytes. The object is
Guido van Rossum8ceef412001-09-11 15:54:00 +0000155 not altered in any way by this function; you can continue
156 updating the object after calling this function.
157 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000158 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000159 return h.digest()
160
161 def hexdigest(self):
162 """Like digest(), but returns a string of hexadecimal digits instead.
163 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000164 h = self._current()
165 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000166
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700167def new(key, msg=None, digestmod=''):
Guido van Rossum8ceef412001-09-11 15:54:00 +0000168 """Create a new hashing object and return it.
169
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700170 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.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000175
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700176 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()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000181 method, and can ask for the hash value at any time by calling its digest()
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700182 or hexdigest() methods.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000183 """
184 return HMAC(key, msg, digestmod)
Christian Heimes2f050c72018-01-27 09:53:43 +0100185
186
187def digest(key, msg, digest):
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700188 """Fast inline implementation of HMAC.
Christian Heimes2f050c72018-01-27 09:53:43 +0100189
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700190 key: bytes or buffer, The key for the keyed hash object.
191 msg: bytes or buffer, Input message.
Christian Heimes2f050c72018-01-27 09:53:43 +0100192 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.
Christian Heimes2f050c72018-01-27 09:53:43 +0100195 """
Christian Heimes933dfd72021-03-27 14:55:03 +0100196 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
Christian Heimes2f050c72018-01-27 09:53:43 +0100201
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()