Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 1 | """HMAC (Keyed-Hashing for Message Authentication) Python module. |
| 2 | |
| 3 | Implements the HMAC algorithm as described by RFC 2104. |
| 4 | """ |
| 5 | |
Guido van Rossum | a19f80c | 2007-11-06 20:51:31 +0000 | [diff] [blame] | 6 | import warnings as _warnings |
Antoine Pitrou | a85017f | 2013-04-20 19:21:44 +0200 | [diff] [blame] | 7 | from _operator import _compare_digest as compare_digest |
Christian Heimes | 2f050c7 | 2018-01-27 09:53:43 +0100 | [diff] [blame] | 8 | try: |
| 9 | import _hashlib as _hashopenssl |
| 10 | except ImportError: |
| 11 | _hashopenssl = None |
| 12 | _openssl_md_meths = None |
| 13 | else: |
| 14 | _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names) |
Christian Heimes | 634919a | 2013-11-20 17:23:06 +0100 | [diff] [blame] | 15 | import hashlib as _hashlib |
Guido van Rossum | a19f80c | 2007-11-06 20:51:31 +0000 | [diff] [blame] | 16 | |
Guido van Rossum | 3f42908 | 2007-07-10 13:35:52 +0000 | [diff] [blame] | 17 | trans_5C = bytes((x ^ 0x5C) for x in range(256)) |
| 18 | trans_36 = bytes((x ^ 0x36) for x in range(256)) |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 19 | |
Andrew M. Kuchling | 1ccdff9 | 2001-11-02 21:49:20 +0000 | [diff] [blame] | 20 | # The size of the digests returned by HMAC depends on the underlying |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 21 | # hashing module used. Use digest_size from the instance of HMAC instead. |
Andrew M. Kuchling | 1ccdff9 | 2001-11-02 21:49:20 +0000 | [diff] [blame] | 22 | digest_size = None |
| 23 | |
Tim Peters | 934d31b | 2004-03-20 20:11:29 +0000 | [diff] [blame] | 24 | |
Charles-François Natali | 7feb9f4 | 2012-05-13 19:53:07 +0200 | [diff] [blame] | 25 | |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 26 | class HMAC: |
Guido van Rossum | a19f80c | 2007-11-06 20:51:31 +0000 | [diff] [blame] | 27 | """RFC 2104 HMAC class. Also complies with RFC 4231. |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 28 | |
Andrew M. Kuchling | 1ccdff9 | 2001-11-02 21:49:20 +0000 | [diff] [blame] | 29 | This supports the API for Cryptographic Hash Functions (PEP 247). |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 30 | """ |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 31 | blocksize = 64 # 512-bit HMAC; can be changed in subclasses. |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 32 | |
| 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. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 38 | digestmod: A module supporting PEP 247. *OR* |
Christian Heimes | 634919a | 2013-11-20 17:23:06 +0100 | [diff] [blame] | 39 | A hashlib constructor returning a new hash object. *OR* |
| 40 | A hash name suitable for hashlib.new(). |
Gregory P. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 41 | Defaults to hashlib.md5. |
Christian Heimes | 634919a | 2013-11-20 17:23:06 +0100 | [diff] [blame] | 42 | Implicit default to hashlib.md5 is deprecated and will be |
| 43 | removed in Python 3.6. |
Guido van Rossum | 3f42908 | 2007-07-10 13:35:52 +0000 | [diff] [blame] | 44 | |
Christian Heimes | 04926ae | 2013-07-01 13:08:42 +0200 | [diff] [blame] | 45 | Note: key and msg must be a bytes or bytearray objects. |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 46 | """ |
Tim Peters | 934d31b | 2004-03-20 20:11:29 +0000 | [diff] [blame] | 47 | |
Christian Heimes | 04926ae | 2013-07-01 13:08:42 +0200 | [diff] [blame] | 48 | if not isinstance(key, (bytes, bytearray)): |
| 49 | raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) |
Guido van Rossum | 3f42908 | 2007-07-10 13:35:52 +0000 | [diff] [blame] | 50 | |
Raymond Hettinger | 7fdfc2d | 2002-05-31 17:49:10 +0000 | [diff] [blame] | 51 | if digestmod is None: |
Christian Heimes | 634919a | 2013-11-20 17:23:06 +0100 | [diff] [blame] | 52 | _warnings.warn("HMAC() without an explicit digestmod argument " |
| 53 | "is deprecated.", PendingDeprecationWarning, 2) |
| 54 | digestmod = _hashlib.md5 |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 55 | |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 56 | if callable(digestmod): |
Gregory P. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 57 | self.digest_cons = digestmod |
Christian Heimes | 634919a | 2013-11-20 17:23:06 +0100 | [diff] [blame] | 58 | elif isinstance(digestmod, str): |
| 59 | self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d) |
Gregory P. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 60 | else: |
Guido van Rossum | 3f42908 | 2007-07-10 13:35:52 +0000 | [diff] [blame] | 61 | self.digest_cons = lambda d=b'': digestmod.new(d) |
Gregory P. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 62 | |
| 63 | self.outer = self.digest_cons() |
| 64 | self.inner = self.digest_cons() |
| 65 | self.digest_size = self.inner.digest_size |
Tim Peters | 8876848 | 2001-11-13 21:51:26 +0000 | [diff] [blame] | 66 | |
Guido van Rossum | a19f80c | 2007-11-06 20:51:31 +0000 | [diff] [blame] | 67 | if hasattr(self.inner, 'block_size'): |
| 68 | blocksize = self.inner.block_size |
| 69 | if blocksize < 16: |
Guido van Rossum | a19f80c | 2007-11-06 20:51:31 +0000 | [diff] [blame] | 70 | _warnings.warn('block_size of %d seems too small; using our ' |
| 71 | 'default of %d.' % (blocksize, self.blocksize), |
| 72 | RuntimeWarning, 2) |
| 73 | blocksize = self.blocksize |
| 74 | else: |
| 75 | _warnings.warn('No block_size attribute on given digest object; ' |
| 76 | 'Assuming %d.' % (self.blocksize), |
| 77 | RuntimeWarning, 2) |
| 78 | blocksize = self.blocksize |
| 79 | |
Christian Heimes | c4ab110 | 2013-11-20 17:35:06 +0100 | [diff] [blame] | 80 | # self.blocksize is the default blocksize. self.block_size is |
| 81 | # effective block size as well as the public API attribute. |
| 82 | self.block_size = blocksize |
| 83 | |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 84 | if len(key) > blocksize: |
Gregory P. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 85 | key = self.digest_cons(key).digest() |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 86 | |
Serhiy Storchaka | 5f1a518 | 2016-09-11 14:41:02 +0300 | [diff] [blame] | 87 | key = key.ljust(blocksize, b'\0') |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 88 | self.outer.update(key.translate(trans_5C)) |
| 89 | self.inner.update(key.translate(trans_36)) |
Raymond Hettinger | 094662a | 2002-06-01 01:29:16 +0000 | [diff] [blame] | 90 | if msg is not None: |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 91 | self.update(msg) |
| 92 | |
Christian Heimes | c4ab110 | 2013-11-20 17:35:06 +0100 | [diff] [blame] | 93 | @property |
| 94 | def name(self): |
| 95 | return "hmac-" + self.inner.name |
| 96 | |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 97 | def update(self, msg): |
| 98 | """Update this hashing object with the string msg. |
| 99 | """ |
| 100 | self.inner.update(msg) |
| 101 | |
| 102 | def copy(self): |
| 103 | """Return a separate copy of this hashing object. |
| 104 | |
| 105 | An update to this copy won't affect the original object. |
| 106 | """ |
Benjamin Peterson | 0cc7444 | 2010-08-21 02:45:15 +0000 | [diff] [blame] | 107 | # Call __new__ directly to avoid the expensive __init__. |
| 108 | other = self.__class__.__new__(self.__class__) |
Gregory P. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 109 | other.digest_cons = self.digest_cons |
Tim Peters | 934d31b | 2004-03-20 20:11:29 +0000 | [diff] [blame] | 110 | other.digest_size = self.digest_size |
Andrew M. Kuchling | 1ccdff9 | 2001-11-02 21:49:20 +0000 | [diff] [blame] | 111 | other.inner = self.inner.copy() |
| 112 | other.outer = self.outer.copy() |
| 113 | return other |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 114 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 115 | def _current(self): |
| 116 | """Return a hash object for the current state. |
| 117 | |
| 118 | To be used only internally with digest() and hexdigest(). |
| 119 | """ |
| 120 | h = self.outer.copy() |
| 121 | h.update(self.inner.digest()) |
| 122 | return h |
| 123 | |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 124 | def digest(self): |
| 125 | """Return the hash value of this hashing object. |
| 126 | |
| 127 | This returns a string containing 8-bit data. The object is |
| 128 | not altered in any way by this function; you can continue |
| 129 | updating the object after calling this function. |
| 130 | """ |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 131 | h = self._current() |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 132 | return h.digest() |
| 133 | |
| 134 | def hexdigest(self): |
| 135 | """Like digest(), but returns a string of hexadecimal digits instead. |
| 136 | """ |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 137 | h = self._current() |
| 138 | return h.hexdigest() |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 139 | |
| 140 | def new(key, msg = None, digestmod = None): |
| 141 | """Create a new hashing object and return it. |
| 142 | |
| 143 | key: The starting key for the hash. |
| 144 | msg: if available, will immediately be hashed into the object's starting |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 145 | state. |
Guido van Rossum | 8ceef41 | 2001-09-11 15:54:00 +0000 | [diff] [blame] | 146 | |
| 147 | You can now feed arbitrary strings into the object using its update() |
| 148 | method, and can ask for the hash value at any time by calling its digest() |
| 149 | method. |
| 150 | """ |
| 151 | return HMAC(key, msg, digestmod) |
Christian Heimes | 2f050c7 | 2018-01-27 09:53:43 +0100 | [diff] [blame] | 152 | |
| 153 | |
| 154 | def digest(key, msg, digest): |
| 155 | """Fast inline implementation of HMAC |
| 156 | |
| 157 | key: key for the keyed hash object. |
| 158 | msg: input message |
| 159 | digest: A hash name suitable for hashlib.new() for best performance. *OR* |
| 160 | A hashlib constructor returning a new hash object. *OR* |
| 161 | A module supporting PEP 247. |
| 162 | |
| 163 | Note: key and msg must be a bytes or bytearray objects. |
| 164 | """ |
| 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() |