blob: 54a1ef9bdbdcfb93602d732ade895c388f362b44 [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
Antoine Pitroua85017f2013-04-20 19:21:44 +02007from _operator import _compare_digest as compare_digest
Christian Heimes2f050c72018-01-27 09:53:43 +01008try:
9 import _hashlib as _hashopenssl
10except ImportError:
11 _hashopenssl = None
12 _openssl_md_meths = None
13else:
14 _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names)
Christian Heimes634919a2013-11-20 17:23:06 +010015import hashlib as _hashlib
Guido van Rossuma19f80c2007-11-06 20:51:31 +000016
Guido van Rossum3f429082007-07-10 13:35:52 +000017trans_5C = bytes((x ^ 0x5C) for x in range(256))
18trans_36 = bytes((x ^ 0x36) for x in range(256))
Tim Petersb64bec32001-09-18 02:26:39 +000019
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000020# The size of the digests returned by HMAC depends on the underlying
Thomas Wouters902d6eb2007-01-09 23:18:33 +000021# hashing module used. Use digest_size from the instance of HMAC instead.
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000022digest_size = None
23
Tim Peters934d31b2004-03-20 20:11:29 +000024
Charles-François Natali7feb9f42012-05-13 19:53:07 +020025
Guido van Rossum8ceef412001-09-11 15:54:00 +000026class HMAC:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000027 """RFC 2104 HMAC class. Also complies with RFC 4231.
Guido van Rossum8ceef412001-09-11 15:54:00 +000028
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000029 This supports the API for Cryptographic Hash Functions (PEP 247).
Tim Petersb64bec32001-09-18 02:26:39 +000030 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000031 blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
Guido van Rossum8ceef412001-09-11 15:54:00 +000032
Christian Heimes837f9e42020-05-17 01:05:40 +020033 __slots__ = (
34 "_digest_cons", "_inner", "_outer", "block_size", "digest_size"
35 )
36
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070037 def __init__(self, key, msg=None, digestmod=''):
Guido van Rossum8ceef412001-09-11 15:54:00 +000038 """Create a new HMAC object.
39
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070040 key: bytes or buffer, key for the keyed hash object.
41 msg: bytes or buffer, Initial input for the hash or None.
42 digestmod: A hash name suitable for hashlib.new(). *OR*
43 A hashlib constructor returning a new hash object. *OR*
44 A module supporting PEP 247.
Guido van Rossum3f429082007-07-10 13:35:52 +000045
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070046 Required as of 3.8, despite its position after the optional
47 msg argument. Passing it as a keyword argument is
48 recommended, though not required for legacy API reasons.
Guido van Rossum8ceef412001-09-11 15:54:00 +000049 """
Tim Peters934d31b2004-03-20 20:11:29 +000050
Christian Heimes04926ae2013-07-01 13:08:42 +020051 if not isinstance(key, (bytes, bytearray)):
52 raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
Guido van Rossum3f429082007-07-10 13:35:52 +000053
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070054 if not digestmod:
55 raise TypeError("Missing required parameter 'digestmod'.")
Guido van Rossum8ceef412001-09-11 15:54:00 +000056
Florent Xicluna5d1155c2011-10-28 14:45:05 +020057 if callable(digestmod):
Christian Heimes837f9e42020-05-17 01:05:40 +020058 self._digest_cons = digestmod
Christian Heimes634919a2013-11-20 17:23:06 +010059 elif isinstance(digestmod, str):
Christian Heimes837f9e42020-05-17 01:05:40 +020060 self._digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000061 else:
Christian Heimes837f9e42020-05-17 01:05:40 +020062 self._digest_cons = lambda d=b'': digestmod.new(d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000063
Christian Heimes837f9e42020-05-17 01:05:40 +020064 self._outer = self._digest_cons()
65 self._inner = self._digest_cons()
66 self.digest_size = self._inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000067
Christian Heimes837f9e42020-05-17 01:05:40 +020068 if hasattr(self._inner, 'block_size'):
69 blocksize = self._inner.block_size
Guido van Rossuma19f80c2007-11-06 20:51:31 +000070 if blocksize < 16:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000071 _warnings.warn('block_size of %d seems too small; using our '
72 'default of %d.' % (blocksize, self.blocksize),
73 RuntimeWarning, 2)
74 blocksize = self.blocksize
75 else:
76 _warnings.warn('No block_size attribute on given digest object; '
77 'Assuming %d.' % (self.blocksize),
78 RuntimeWarning, 2)
79 blocksize = self.blocksize
80
Christian Heimesc4ab1102013-11-20 17:35:06 +010081 # self.blocksize is the default blocksize. self.block_size is
82 # effective block size as well as the public API attribute.
83 self.block_size = blocksize
84
Guido van Rossum8ceef412001-09-11 15:54:00 +000085 if len(key) > blocksize:
Christian Heimes837f9e42020-05-17 01:05:40 +020086 key = self._digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000087
Serhiy Storchaka5f1a5182016-09-11 14:41:02 +030088 key = key.ljust(blocksize, b'\0')
Christian Heimes837f9e42020-05-17 01:05:40 +020089 self._outer.update(key.translate(trans_5C))
90 self._inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000091 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000092 self.update(msg)
93
Christian Heimesc4ab1102013-11-20 17:35:06 +010094 @property
95 def name(self):
Christian Heimes837f9e42020-05-17 01:05:40 +020096 return "hmac-" + self._inner.name
97
98 @property
99 def digest_cons(self):
100 return self._digest_cons
101
102 @property
103 def inner(self):
104 return self._inner
105
106 @property
107 def outer(self):
108 return self._outer
Christian Heimesc4ab1102013-11-20 17:35:06 +0100109
Guido van Rossum8ceef412001-09-11 15:54:00 +0000110 def update(self, msg):
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700111 """Feed data from msg into this hashing object."""
Christian Heimes837f9e42020-05-17 01:05:40 +0200112 self._inner.update(msg)
Guido van Rossum8ceef412001-09-11 15:54:00 +0000113
114 def copy(self):
115 """Return a separate copy of this hashing object.
116
117 An update to this copy won't affect the original object.
118 """
Benjamin Peterson0cc74442010-08-21 02:45:15 +0000119 # Call __new__ directly to avoid the expensive __init__.
120 other = self.__class__.__new__(self.__class__)
Christian Heimes837f9e42020-05-17 01:05:40 +0200121 other._digest_cons = self._digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +0000122 other.digest_size = self.digest_size
Christian Heimes837f9e42020-05-17 01:05:40 +0200123 other._inner = self._inner.copy()
124 other._outer = self._outer.copy()
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +0000125 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +0000126
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000127 def _current(self):
128 """Return a hash object for the current state.
129
130 To be used only internally with digest() and hexdigest().
131 """
Christian Heimes837f9e42020-05-17 01:05:40 +0200132 h = self._outer.copy()
133 h.update(self._inner.digest())
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000134 return h
135
Guido van Rossum8ceef412001-09-11 15:54:00 +0000136 def digest(self):
137 """Return the hash value of this hashing object.
138
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700139 This returns the hmac value as bytes. The object is
Guido van Rossum8ceef412001-09-11 15:54:00 +0000140 not altered in any way by this function; you can continue
141 updating the object after calling this function.
142 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000143 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000144 return h.digest()
145
146 def hexdigest(self):
147 """Like digest(), but returns a string of hexadecimal digits instead.
148 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000149 h = self._current()
150 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000151
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700152def new(key, msg=None, digestmod=''):
Guido van Rossum8ceef412001-09-11 15:54:00 +0000153 """Create a new hashing object and return it.
154
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700155 key: bytes or buffer, The starting key for the hash.
156 msg: bytes or buffer, Initial input for the hash, or None.
157 digestmod: A hash name suitable for hashlib.new(). *OR*
158 A hashlib constructor returning a new hash object. *OR*
159 A module supporting PEP 247.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000160
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700161 Required as of 3.8, despite its position after the optional
162 msg argument. Passing it as a keyword argument is
163 recommended, though not required for legacy API reasons.
164
165 You can now feed arbitrary bytes into the object using its update()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000166 method, and can ask for the hash value at any time by calling its digest()
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700167 or hexdigest() methods.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000168 """
169 return HMAC(key, msg, digestmod)
Christian Heimes2f050c72018-01-27 09:53:43 +0100170
171
172def digest(key, msg, digest):
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700173 """Fast inline implementation of HMAC.
Christian Heimes2f050c72018-01-27 09:53:43 +0100174
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700175 key: bytes or buffer, The key for the keyed hash object.
176 msg: bytes or buffer, Input message.
Christian Heimes2f050c72018-01-27 09:53:43 +0100177 digest: A hash name suitable for hashlib.new() for best performance. *OR*
178 A hashlib constructor returning a new hash object. *OR*
179 A module supporting PEP 247.
Christian Heimes2f050c72018-01-27 09:53:43 +0100180 """
181 if (_hashopenssl is not None and
182 isinstance(digest, str) and digest in _openssl_md_meths):
183 return _hashopenssl.hmac_digest(key, msg, digest)
184
185 if callable(digest):
186 digest_cons = digest
187 elif isinstance(digest, str):
188 digest_cons = lambda d=b'': _hashlib.new(digest, d)
189 else:
190 digest_cons = lambda d=b'': digest.new(d)
191
192 inner = digest_cons()
193 outer = digest_cons()
194 blocksize = getattr(inner, 'block_size', 64)
195 if len(key) > blocksize:
196 key = digest_cons(key).digest()
197 key = key + b'\x00' * (blocksize - len(key))
198 inner.update(key.translate(trans_36))
199 outer.update(key.translate(trans_5C))
200 inner.update(msg)
201 outer.update(inner.digest())
202 return outer.digest()