blob: 43b7212976372c4945b1718f16a0c6de00b88a83 [file] [log] [blame]
Guido van Rossum8ceef412001-09-11 15:54:00 +00001"""HMAC (Keyed-Hashing for Message Authentication) Python module.
2
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
33 def __init__(self, key, msg = None, digestmod = None):
34 """Create a new HMAC object.
35
36 key: key for the keyed hash object.
37 msg: Initial input for the hash, if provided.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000038 digestmod: A module supporting PEP 247. *OR*
Christian Heimes634919a2013-11-20 17:23:06 +010039 A hashlib constructor returning a new hash object. *OR*
40 A hash name suitable for hashlib.new().
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000041 Defaults to hashlib.md5.
Matthias Bussonnier8bb0b5b2018-05-22 15:55:31 -070042 Implicit default to hashlib.md5 is deprecated since Python
43 3.4 and will be removed in Python 3.8.
Guido van Rossum3f429082007-07-10 13:35:52 +000044
Christian Heimes04926ae2013-07-01 13:08:42 +020045 Note: key and msg must be a bytes or bytearray objects.
Guido van Rossum8ceef412001-09-11 15:54:00 +000046 """
Tim Peters934d31b2004-03-20 20:11:29 +000047
Christian Heimes04926ae2013-07-01 13:08:42 +020048 if not isinstance(key, (bytes, bytearray)):
49 raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
Guido van Rossum3f429082007-07-10 13:35:52 +000050
Raymond Hettinger7fdfc2d2002-05-31 17:49:10 +000051 if digestmod is None:
Christian Heimes634919a2013-11-20 17:23:06 +010052 _warnings.warn("HMAC() without an explicit digestmod argument "
Matthias Bussonnier8bb0b5b2018-05-22 15:55:31 -070053 "is deprecated since Python 3.4, and will be removed "
54 "in 3.8",
55 DeprecationWarning, 2)
Christian Heimes634919a2013-11-20 17:23:06 +010056 digestmod = _hashlib.md5
Guido van Rossum8ceef412001-09-11 15:54:00 +000057
Florent Xicluna5d1155c2011-10-28 14:45:05 +020058 if callable(digestmod):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000059 self.digest_cons = digestmod
Christian Heimes634919a2013-11-20 17:23:06 +010060 elif isinstance(digestmod, str):
61 self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000062 else:
Guido van Rossum3f429082007-07-10 13:35:52 +000063 self.digest_cons = lambda d=b'': digestmod.new(d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000064
65 self.outer = self.digest_cons()
66 self.inner = self.digest_cons()
67 self.digest_size = self.inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000068
Guido van Rossuma19f80c2007-11-06 20:51:31 +000069 if hasattr(self.inner, 'block_size'):
70 blocksize = self.inner.block_size
71 if blocksize < 16:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000072 _warnings.warn('block_size of %d seems too small; using our '
73 'default of %d.' % (blocksize, self.blocksize),
74 RuntimeWarning, 2)
75 blocksize = self.blocksize
76 else:
77 _warnings.warn('No block_size attribute on given digest object; '
78 'Assuming %d.' % (self.blocksize),
79 RuntimeWarning, 2)
80 blocksize = self.blocksize
81
Christian Heimesc4ab1102013-11-20 17:35:06 +010082 # self.blocksize is the default blocksize. self.block_size is
83 # effective block size as well as the public API attribute.
84 self.block_size = blocksize
85
Guido van Rossum8ceef412001-09-11 15:54:00 +000086 if len(key) > blocksize:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000087 key = self.digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000088
Serhiy Storchaka5f1a5182016-09-11 14:41:02 +030089 key = key.ljust(blocksize, b'\0')
Thomas Wouters902d6eb2007-01-09 23:18:33 +000090 self.outer.update(key.translate(trans_5C))
91 self.inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000092 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000093 self.update(msg)
94
Christian Heimesc4ab1102013-11-20 17:35:06 +010095 @property
96 def name(self):
97 return "hmac-" + self.inner.name
98
Guido van Rossum8ceef412001-09-11 15:54:00 +000099 def update(self, msg):
100 """Update this hashing object with the string msg.
101 """
102 self.inner.update(msg)
103
104 def copy(self):
105 """Return a separate copy of this hashing object.
106
107 An update to this copy won't affect the original object.
108 """
Benjamin Peterson0cc74442010-08-21 02:45:15 +0000109 # Call __new__ directly to avoid the expensive __init__.
110 other = self.__class__.__new__(self.__class__)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000111 other.digest_cons = self.digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +0000112 other.digest_size = self.digest_size
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +0000113 other.inner = self.inner.copy()
114 other.outer = self.outer.copy()
115 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +0000116
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000117 def _current(self):
118 """Return a hash object for the current state.
119
120 To be used only internally with digest() and hexdigest().
121 """
122 h = self.outer.copy()
123 h.update(self.inner.digest())
124 return h
125
Guido van Rossum8ceef412001-09-11 15:54:00 +0000126 def digest(self):
127 """Return the hash value of this hashing object.
128
129 This returns a string containing 8-bit data. The object is
130 not altered in any way by this function; you can continue
131 updating the object after calling this function.
132 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000133 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000134 return h.digest()
135
136 def hexdigest(self):
137 """Like digest(), but returns a string of hexadecimal digits instead.
138 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000139 h = self._current()
140 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000141
142def new(key, msg = None, digestmod = None):
143 """Create a new hashing object and return it.
144
145 key: The starting key for the hash.
146 msg: if available, will immediately be hashed into the object's starting
Tim Petersb64bec32001-09-18 02:26:39 +0000147 state.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000148
149 You can now feed arbitrary strings into the object using its update()
150 method, and can ask for the hash value at any time by calling its digest()
151 method.
152 """
153 return HMAC(key, msg, digestmod)
Christian Heimes2f050c72018-01-27 09:53:43 +0100154
155
156def digest(key, msg, digest):
157 """Fast inline implementation of HMAC
158
159 key: key for the keyed hash object.
160 msg: 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 Note: key and msg must be a bytes or bytearray objects.
166 """
167 if (_hashopenssl is not None and
168 isinstance(digest, str) and digest in _openssl_md_meths):
169 return _hashopenssl.hmac_digest(key, msg, digest)
170
171 if callable(digest):
172 digest_cons = digest
173 elif isinstance(digest, str):
174 digest_cons = lambda d=b'': _hashlib.new(digest, d)
175 else:
176 digest_cons = lambda d=b'': digest.new(d)
177
178 inner = digest_cons()
179 outer = digest_cons()
180 blocksize = getattr(inner, 'block_size', 64)
181 if len(key) > blocksize:
182 key = digest_cons(key).digest()
183 key = key + b'\x00' * (blocksize - len(key))
184 inner.update(key.translate(trans_36))
185 outer.update(key.translate(trans_5C))
186 inner.update(msg)
187 outer.update(inner.digest())
188 return outer.digest()