blob: b769876e6f7745d82986e4d5b15e3b970f1a0c3c [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
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070033 def __init__(self, key, msg=None, digestmod=''):
Guido van Rossum8ceef412001-09-11 15:54:00 +000034 """Create a new HMAC object.
35
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070036 key: bytes or buffer, key for the keyed hash object.
37 msg: bytes or buffer, Initial input for the hash or None.
38 digestmod: A hash name suitable for hashlib.new(). *OR*
39 A hashlib constructor returning a new hash object. *OR*
40 A module supporting PEP 247.
Guido van Rossum3f429082007-07-10 13:35:52 +000041
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070042 Required as of 3.8, despite its position after the optional
43 msg argument. Passing it as a keyword argument is
44 recommended, though not required for legacy API reasons.
Guido van Rossum8ceef412001-09-11 15:54:00 +000045 """
Tim Peters934d31b2004-03-20 20:11:29 +000046
Christian Heimes04926ae2013-07-01 13:08:42 +020047 if not isinstance(key, (bytes, bytearray)):
48 raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
Guido van Rossum3f429082007-07-10 13:35:52 +000049
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070050 if not digestmod:
51 raise TypeError("Missing required parameter 'digestmod'.")
Guido van Rossum8ceef412001-09-11 15:54:00 +000052
Florent Xicluna5d1155c2011-10-28 14:45:05 +020053 if callable(digestmod):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000054 self.digest_cons = digestmod
Christian Heimes634919a2013-11-20 17:23:06 +010055 elif isinstance(digestmod, str):
56 self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000057 else:
Guido van Rossum3f429082007-07-10 13:35:52 +000058 self.digest_cons = lambda d=b'': digestmod.new(d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000059
60 self.outer = self.digest_cons()
61 self.inner = self.digest_cons()
62 self.digest_size = self.inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000063
Guido van Rossuma19f80c2007-11-06 20:51:31 +000064 if hasattr(self.inner, 'block_size'):
65 blocksize = self.inner.block_size
66 if blocksize < 16:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000067 _warnings.warn('block_size of %d seems too small; using our '
68 'default of %d.' % (blocksize, self.blocksize),
69 RuntimeWarning, 2)
70 blocksize = self.blocksize
71 else:
72 _warnings.warn('No block_size attribute on given digest object; '
73 'Assuming %d.' % (self.blocksize),
74 RuntimeWarning, 2)
75 blocksize = self.blocksize
76
Christian Heimesc4ab1102013-11-20 17:35:06 +010077 # self.blocksize is the default blocksize. self.block_size is
78 # effective block size as well as the public API attribute.
79 self.block_size = blocksize
80
Guido van Rossum8ceef412001-09-11 15:54:00 +000081 if len(key) > blocksize:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000082 key = self.digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000083
Serhiy Storchaka5f1a5182016-09-11 14:41:02 +030084 key = key.ljust(blocksize, b'\0')
Thomas Wouters902d6eb2007-01-09 23:18:33 +000085 self.outer.update(key.translate(trans_5C))
86 self.inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000087 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000088 self.update(msg)
89
Christian Heimesc4ab1102013-11-20 17:35:06 +010090 @property
91 def name(self):
92 return "hmac-" + self.inner.name
93
Guido van Rossum8ceef412001-09-11 15:54:00 +000094 def update(self, msg):
Gregory P. Smithf33c57d52019-10-17 20:30:42 -070095 """Feed data from msg into this hashing object."""
Guido van Rossum8ceef412001-09-11 15:54:00 +000096 self.inner.update(msg)
97
98 def copy(self):
99 """Return a separate copy of this hashing object.
100
101 An update to this copy won't affect the original object.
102 """
Benjamin Peterson0cc74442010-08-21 02:45:15 +0000103 # Call __new__ directly to avoid the expensive __init__.
104 other = self.__class__.__new__(self.__class__)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000105 other.digest_cons = self.digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +0000106 other.digest_size = self.digest_size
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +0000107 other.inner = self.inner.copy()
108 other.outer = self.outer.copy()
109 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +0000110
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000111 def _current(self):
112 """Return a hash object for the current state.
113
114 To be used only internally with digest() and hexdigest().
115 """
116 h = self.outer.copy()
117 h.update(self.inner.digest())
118 return h
119
Guido van Rossum8ceef412001-09-11 15:54:00 +0000120 def digest(self):
121 """Return the hash value of this hashing object.
122
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700123 This returns the hmac value as bytes. The object is
Guido van Rossum8ceef412001-09-11 15:54:00 +0000124 not altered in any way by this function; you can continue
125 updating the object after calling this function.
126 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000127 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000128 return h.digest()
129
130 def hexdigest(self):
131 """Like digest(), but returns a string of hexadecimal digits instead.
132 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000133 h = self._current()
134 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000135
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700136def new(key, msg=None, digestmod=''):
Guido van Rossum8ceef412001-09-11 15:54:00 +0000137 """Create a new hashing object and return it.
138
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700139 key: bytes or buffer, The starting key for the hash.
140 msg: bytes or buffer, Initial input for the hash, or None.
141 digestmod: A hash name suitable for hashlib.new(). *OR*
142 A hashlib constructor returning a new hash object. *OR*
143 A module supporting PEP 247.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000144
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700145 Required as of 3.8, despite its position after the optional
146 msg argument. Passing it as a keyword argument is
147 recommended, though not required for legacy API reasons.
148
149 You can now feed arbitrary bytes into the object using its update()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000150 method, and can ask for the hash value at any time by calling its digest()
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700151 or hexdigest() methods.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000152 """
153 return HMAC(key, msg, digestmod)
Christian Heimes2f050c72018-01-27 09:53:43 +0100154
155
156def digest(key, msg, digest):
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700157 """Fast inline implementation of HMAC.
Christian Heimes2f050c72018-01-27 09:53:43 +0100158
Gregory P. Smithf33c57d52019-10-17 20:30:42 -0700159 key: bytes or buffer, The key for the keyed hash object.
160 msg: bytes or buffer, Input message.
Christian Heimes2f050c72018-01-27 09:53:43 +0100161 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.
Christian Heimes2f050c72018-01-27 09:53:43 +0100164 """
165 if (_hashopenssl is not None and
166 isinstance(digest, str) and digest in _openssl_md_meths):
167 return _hashopenssl.hmac_digest(key, msg, digest)
168
169 if callable(digest):
170 digest_cons = digest
171 elif isinstance(digest, str):
172 digest_cons = lambda d=b'': _hashlib.new(digest, d)
173 else:
174 digest_cons = lambda d=b'': digest.new(d)
175
176 inner = digest_cons()
177 outer = digest_cons()
178 blocksize = getattr(inner, 'block_size', 64)
179 if len(key) > blocksize:
180 key = digest_cons(key).digest()
181 key = key + b'\x00' * (blocksize - len(key))
182 inner.update(key.translate(trans_36))
183 outer.update(key.translate(trans_5C))
184 inner.update(msg)
185 outer.update(inner.digest())
186 return outer.digest()